Spring learning summary (ten): introduction and use of JdbcTemplate

1. Introduction of JdbcTemplate

      The Spring framework provides the JdbcTemplate class for applications in database development. This class is the core of Spring's support for JDBC. It provides all the support for database operation functions. JdbcTemplate mainly provides the following methods:

method description
execute method Can be used to execute any SQL statement, generally used to execute DDL statements
update method and batchUpdate method The update method is used to execute statements such as adding, modifying, and deleting. The batchUpdate method is used to execute batch-related statements.
query method and queryForXXX method Used to execute query related statements
call method Used to execute stored procedures and function-related statements.

      Use JdbcTemplate to import the three jar packages of Spring's database module and the jar package of mysql database as follows:

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.35</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.6.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>5.2.6.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.2.6.RELEASE</version>
    </dependency>

Two, JdbcTemplate realizes the addition, deletion and modification of the database

      (1) Create an external configuration file jdbc.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.userName=root
jdbc.password=root

      (2) Create bean.xml, configure data source, jdbcTemplate and package for annotation scanning.

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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"><!--引入context名称空间-->

    <!--  配置注解扫描的包  -->
    <context:component-scan base-package="com.yht.example7"></context:component-scan>

    <!--引入外部属性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--配置连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClass}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.userName}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!--  配置jdbcTemplate -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

</beans>

       (3) Create the t_user table and insert some data.

create table t_user(
    id int primary key auto_increment,
    name varchar(20),
    address varchar(20));
insert into t_user(name, address) values("张玉","山西");
insert into t_user(name, address) values("李红","江西");
insert into t_user(name, address) values("江峰","福建");

       (4) Create entity class User

public class User {
    private Integer id;
    private String name;
    private String address;

    public User() {
    }

    public User(String name, String address) {
        this.name = name;
        this.address = address;
    }

    public User(Integer id, String name, String address) {
        this.id = id;
        this.name = name;
        this.address = address;
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

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

      (5) Create UserService

@Service
public class UserService {
    @Autowired
    private IUserDao userDao;
    /**
     * 添加用户
     */
    public void addUser(User user){
        userDao.addUser(user);
    }
    /**
     * 删除用户
     */
    public void deleteUser(int id){
        userDao.deleteUser(id);
    }
    /**
     * 更新用户
     */
    public void updateUser(User user){
        userDao.updateUser(user);
    }
    /**
     * 查询数据库中数据总数
     */
    public void getCount(){
        userDao.getCount();
    }
    /**
     * 查询单个用户
     */
    public void findOne(int id){
        userDao.findOne(id);
    }
    /**
     * 查询所有用户
     */
    public void findAll(){
        userDao.findAll();
    }
}

      (6) Create IUserDao and implement class UserDaoImpl

public interface IUserDao {
    /**
     * 添加用户
     */
    void addUser(User user);
    /**
     * 删除用户
     */
    void deleteUser(int id);
    /**
     * 更新用户
     */
    void updateUser(User user);
    /**
     * 查询数据库中数据总数
     */
    void getCount();
    /**
     * 查询单个用户
     */
    void findOne(int id);
    /**
     * 查询所有用户
     */
    void findAll();
}

 

@Repository
public class UserDaoImpl implements IUserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public void addUser(User user) {
        String sql = "insert into t_user(name, address) values(?,?)";
        jdbcTemplate.update(sql, user.getName(), user.getAddress());
    }

    @Override
    public void deleteUser(int id) {
        String sql = "delete from t_user where id = ?";
        jdbcTemplate.update(sql, id);
    }

    @Override
    public void updateUser(User user) {
        String sql = "update t_user set name =?, address=? where id = ?";
        jdbcTemplate.update(sql, user.getName(), user.getAddress(), user.getId());
    }

    @Override
    public void getCount() {
        String sql = "select count(*) from t_user";
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
        System.out.println(count);
    }

    @Override
    public void findOne(int id) {
        String sql = "select  * from t_user where id = ?";
        User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), id);
        System.out.println(user);
    }

    @Override
    public void findAll() {
        String sql = "select  * from t_user";
        List<User> lists = jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class));
        System.out.println(lists);
    }
}

      (7) Perform unit testing 

public class JdbcTemplateTest {
    UserService userService = null;
    @Before
    public void init(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        userService = context.getBean("userService", UserService.class);
    }

    @Test
    public void testAddUser(){
        userService.addUser(new User("YHT", "陕西"));
    }
    @Test
    public void testFindCount(){
        userService.getCount();
    }
    @Test
    public void testFindOne(){
        userService.findOne(3);
    }
    @Test
    public void testFindAll(){
        userService.findAll();
    }
    @Test
    public void testUpdateUser(){
        User user = new User(3, "张倩","北京");
        userService.updateUser(user);
    }
    @Test
    public void testDeleteUser(){
        userService.deleteUser(2);
    }
}

Three, JdbcTemplate realizes the batch operation of the database

      Take adding users in batches as an example:

      (1) Add methods in UserService, IUserDao, UserDaoImpl-batchAddUser()

    /**
     * 批量添加数据
     */
    public void batchAddUser(List<Object[]> lists){
        userDao.batchAddUser(lists);
    }
    /**
     * 批量添加用户
     */
    void batchAddUser(List<Object[]> lists);
    @Override
    public void batchAddUser(List<Object[]> lists) {
        String sql = "insert into t_user(name, address) values(?,?)";
        jdbcTemplate.batchUpdate(sql, lists);
    }

      (2) Perform unit testing

    @Test
    public void testBatch(){
        List<Object[]> batchArgs=new ArrayList<>();
        batchArgs.add(new Object[]{"张三","新疆"});
        batchArgs.add(new Object[]{"李四","吉林"});
        batchArgs.add(new Object[]{"王五","河北"});
        userService.batchAddUser(batchArgs);
    }

 

Guess you like

Origin blog.csdn.net/weixin_47382783/article/details/112852151