Spring使用jdbc模板增删改查

发布时间 2023-04-04 16:35:25作者: Tokaitei32

 

 

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置数据源-->
    <bean id="dataSource" class=
            "org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!-- 数据库驱动 -->
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <!-- 连接数据库url -->
        <property name="url" value="jdbc:mysql://localhost/spring?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=Asia/Shanghai" />
        <property name="username" value="root"/><!-- 连接数据库用户名 -->
        <property name="password" value="1234"/><!-- 连接数据库密码 -->
    </bean>
<!--    配置jdbc模板-->
    <bean id="JdbcTemplate"
          class="org.springframework.jdbc.core.JdbcTemplate">
        <!-- 默认必须使用数据源 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>


    <!--    注册一个bean-->
<!--    <bean name="userDao" class="com.niuzhuang.dao.impl.UserDaoImpl"/>-->
<!--    <bean name="xmlAdvice" class="com.niuzhuang.demo.XmlAdice"/>-->
    <bean id="accountDao" class="com.niuzhuang.dao.impl.AccountDaoImpl">
        <property name="jdbcTemplate" ref="JdbcTemplate"/>
    </bean>
<!--    &lt;!&ndash;    配置spring AOP&ndash;&gt;-->
<!--    <aop:config>-->
<!--&lt;!&ndash;        指定切入点&ndash;&gt;-->
<!--        <aop:pointcut id="pointcut" expression="execution(* com.niuzhuang.dao.impl.UserDaoImpl.*(..))"/>-->
<!--&lt;!&ndash;        指定切面&ndash;&gt;-->
<!--        <aop:aspect ref="xmlAdvice">-->
<!--&lt;!&ndash;            前置通知&ndash;&gt;-->
<!--            <aop:before method="before" pointcut-ref="pointcut"/>-->
<!--            &lt;!&ndash;            返回通知&ndash;&gt;-->
<!--            <aop:after-returning method="afteReturnning" pointcut-ref="pointcut"/>-->
<!--            &lt;!&ndash;            环绕通知&ndash;&gt;-->
<!--            <aop:around method="around" pointcut-ref="pointcut"/>-->
<!--            &lt;!&ndash;            异常通知&ndash;&gt;-->
<!--            <aop:after-throwing method="afterException" pointcut-ref="pointcut"/>-->
<!--            &lt;!&ndash;            后置通知&ndash;&gt;-->
<!--            <aop:after method="after" pointcut-ref="pointcut"/>-->

<!--        </aop:aspect>-->
<!--    </aop:config>-->
    <!--使用context命名空间,开启注解处理器-->
<!--    <context:component-scan base-package="com.niuzhuang"/>-->
<!--    &lt;!&ndash;将类配置到容器当中,让容器创建实例&ndash;&gt;-->
<!--    &lt;!&ndash;setter注入&ndash;&gt;-->
<!--    <bean id="hello" class="com.niuzhuang.HelloSpring">-->
<!--        &lt;!&ndash;给属性赋值&ndash;&gt;-->
<!--        <property name="name" value="张三"/>-->
<!--    </bean>-->
<!--    &lt;!&ndash;构造方法注入&ndash;&gt;-->
<!--    <bean id="user" class="com.niuzhuang.User">-->
<!--        <constructor-arg name="id" value="1"/>-->
<!--        <constructor-arg name="username" value="zs"/>-->
<!--        <constructor-arg name="password" value="1234"/>-->
<!--    </bean>-->
<!--    &lt;!&ndash;注入dao&ndash;&gt;-->
<!--    <bean id="userDao" class="com.niuzhuang.dao.impl.UserDaoImpl"/>-->
<!--    &lt;!&ndash;注入service&ndash;&gt;-->
<!--    <bean id="userService" class="com.niuzhuang.service.impl.UserServiceImpl">-->
<!--        <property name="userDao" ref="userDao"/>-->
<!--    </bean>-->
</beans>

 

Account.java

package com.niuzhuang.entity;

public class Account {
    private int id;
    private String name;
    private double balance;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", balance=" + balance +
                '}';
    }
}

UserDao.interface

package com.niuzhuang.dao;

import com.niuzhuang.entity.Account;

import java.util.List;
//这是接口
public interface AccountDao {
    public int addAccount(Account account);
    public int update(Account account);
    public int deleteAccount(Account account);
    public Account findByIdAndName(int id,String name);
    public List<Account> findAll();
}

AccountDaoImpl.java

package com.niuzhuang.dao.impl;

import com.niuzhuang.dao.AccountDao;
import com.niuzhuang.entity.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.util.List;

public class AccountDaoImpl implements AccountDao {
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public int addAccount(Account account) {
        String sql = "insert into account(name,balance) values(?,?)";
        Object[] args = {account.getName(),account.getBalance()};
        int num = jdbcTemplate.update(sql,args);
        return num;
    }

    public int update(Account account) {
        String sql = "update account set name=?,balance=? where id=?";
        int num = jdbcTemplate.update(sql,account.getName(),account.getBalance(),account.getId());
        return num;
    }

    public int deleteAccount(Account account) {
        String sql = "delete from account where id=?";
        return jdbcTemplate.update(sql,account.getId());
    }

    public Account findByIdAndName(int id, String name) {
        String sql = "select*from account where id=? and name=?";
        RowMapper rm = new BeanPropertyRowMapper<Account>(Account.class);//用于将查询的每一条结果转为对象
        Account account = (Account) jdbcTemplate.queryForObject(sql,rm,id,name);
        return account;
    }

    public List<Account> findAll() {
        String sql = "select*from account";
        RowMapper rm = new BeanPropertyRowMapper<Account>(Account.class);//用于将查询的每一条结果转为对象
        return jdbcTemplate.query(sql,rm);
    }
}

 

TestAddAccount.java

package com.niuzhuang.test;

import com.niuzhuang.dao.AccountDao;
import com.niuzhuang.entity.Account;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestAddAccount {
    public static void main(String[] args) {
        ApplicationContext applicationContext =  new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountDao dao = applicationContext.getBean("accountDao",AccountDao.class);
        Account account = new Account();
        account.setBalance(94840.0);
        account.setName("里斯");
        int num = dao.addAccount(account);
        System.out.println("添加了"+num+"条记录");
    }
}
TestFindByIdAndName.java
package com.niuzhuang.test;

import com.niuzhuang.dao.AccountDao;
import com.niuzhuang.entity.Account;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class TestFindByIdAndName {
    public static void main(String[] args) {
        ApplicationContext applicationContext =  new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountDao dao = applicationContext.getBean("accountDao",AccountDao.class);
//        System.out.println(dao.findByIdAndName(1,"1111"));
        List<Account> list = dao.findAll();
        if (list.size()>0){
            for (Account a:list){
                System.out.println(a);
            }
        }else{
            System.out.println("查询不到数据");
        }
    }
}
TestUpdate.java
package com.niuzhuang.test;

import com.niuzhuang.dao.AccountDao;
import com.niuzhuang.entity.Account;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestUpdate {
    public static void main(String[] args) {
        ApplicationContext applicationContext =  new ClassPathXmlApplicationContext("applicationContext.xml");
        AccountDao dao = applicationContext.getBean("accountDao",AccountDao.class);
        Account account = new Account();
        account.setBalance(11111);
        account.setName("1111");
        account.setId(4);
        dao.update(account);
    }
}