[Spring5] Use JdbcTemplate to operate mysql database

insert image description here



1 JdbcTemplate introduction and operation preparation

The Spring framework encapsulates JDBC and uses JdbcTemplate to facilitate the operation of the database.

Operation preparation:

1. Import related dependencies, and the download link is attached at the end of the article.
insert image description here

2. Create a database for easy use. Take creating user_db in the mysql database as an example.
insert image description here

3. Configure the xml file and add information related to database connection, such as password and user name. (Configuration of the connection pool)
insert image description here

4. Configure the JdbcTemplate object and inject DataSource.
insert image description here

5. Create a Service class, create a Dao class, and inject the jdbcTemplate object into the Dao class. Component scanning needs to be enabled. The complete spring configuration file is as follows:
insert image description here

<?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: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">
    <!-- 组件扫描 -->
    <context:component-scan base-package="com.ithxh.spring5"></context:component-scan>


    <!-- 数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close">
        <property name="url" value="jdbc:mysql:///user_db"/>
        <property name="username" value="root"/>
        <property name="password" value="111"/>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    </bean>

    <!-- JdbcTemplate对象 -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!-- 注入dataSource -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
</beans>

6. Add corresponding annotations to each category.
insert image description here

insert image description here

At this point, the preparation work is complete!


2 add operation

1. Create the t_user table in the user_db database, the sql statement is as follows:

CREATE TABLE t_user(
    user_id BIGINT PRIMARY KEY NOT NULL ,
    username VARCHAR(100) NOT NULL ,
    ustatus VARCHAR(50) NOT NULL
)

2. Create a new package entity to store the entity class, create the entity class User corresponding to the t_user table, and add the corresponding set and get methods.
insert image description here

3. Write service and dao, and add database in dao. The UserDao interface declares the add method, UserService performs the add operation, and UserDaoImp ​​specifically implements the database add operation. You need to use the update method of jdbcTemplate.
insert image description here
The first parameter is the written sql statement, and the second parameter is a variable parameter, which is used to set the value.

insert image description here
The specific code is as follows:
UserDao

import com.ithxh.spring5.entity.User;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 */
public interface UserDao {
    
    
    void add(User user);
}

UserDaoImp

import com.ithxh.spring5.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 */
@Repository
public class UserDaoImp implements UserDao{
    
    

    //注入JdbcTemplate
    @Autowired
    private JdbcTemplate jdbcTemplate;

    //实现添加的方法
    @Override
    public void add(User user) {
    
    
        //编写sql语句
        String sql = "insert into t_user values(?,?,?)";
        //调用方法实现
        Object[] args = {
    
    user.getUserId(), user.getUsername(), user.getUstatus()};
        int update = jdbcTemplate.update(sql, args);//返回影响行数
        System.out.println("影响的行数: " + update);
    }
}

UserService

import com.ithxh.spring5.dao.UserDao;
import com.ithxh.spring5.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 */
@Service
public class UserService {
    
    

    //注入dao
    @Autowired
    private UserDao userDao;

    //添加的方法
    public void addUser(User user){
    
    
        userDao.add(user);
    }
}

4. Write a test class and try to add data to the table.

    @Test
    public void testJdbcTemplate(){
    
    
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean.xml");
        UserService userService = context.getBean("userService", UserService.class);
        User user = new User();
        user.setUserId("120");
        user.setUsername("黄小黄");
        user.setUstatus("true");
        userService.addUser(user);
    }

insert image description here
Please add a picture description


3 Modify and delete operations

The modification and deletion operations are generally consistent with the addition operation, and only the corresponding sql statement needs to be modified. Here is a brief description of the core code:

Modify and delete operations

The method of implementing modification and deletion in UserDaoImp

    //实现修改的方法
    @Override
    public void update(User user) {
    
    
        String sql = "update t_user set user_id = ?, username = ?, ustatus = ?";
        Object[] args = {
    
    user.getUserId(), user.getUsername(), user.getUstatus()};
        int update = jdbcTemplate.update(sql, args);
        System.out.println("影响的行数: " + update);
    }

    //实现删除的方法
    @Override
    public void delete(String id) {
    
    
        String sql = "delete from t_user where user_id = ?";
        int update = jdbcTemplate.update(sql, id);
        System.out.println(update);
    }

It should be noted that UserDao should declare the modification and deletion methods, and UserService needs to call the method in UserDaoImp ​​like this:
insert image description here

Test modification:

    @Test
    public void testJdbcTemplate(){
    
    
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean.xml");
        UserService userService = context.getBean("userService", UserService.class);
        User user = new User();
        user.setUserId("111");
        user.setUsername("懒羊羊");
        user.setUstatus("true");
        userService.updateUser(user);
    }

insert image description here

Test delete:

    @Test
    public void testJdbcTemplate(){
    
    
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean.xml");
        UserService userService = context.getBean("userService", UserService.class);
        String id = "111";
        userService.deleteUser(id);
    }

insert image description here


4 Database query operation

4.1 Returning a value

Example: query how many records there are in the table, and return a value indicating the number of data in the table

    //查询有多少条记录
    @Override
    public int findCountUser() {
    
    
        String sql = "select count(*) from t_user";
        Integer res = jdbcTemplate.queryForObject(sql, Integer.class);//第二个参数是返回值类型
        return res;
    }

4.2 return object

Example: Query user details.

Through the queryForObject method in jdbcTemlate:
insert image description here

  • The first parameter: sql statement;
  • The second parameter: RowMapper is an interface that returns different types of data, and the implementation class of this interface is used to complete the data encapsulation.
  • The third parameter: sql statement value.

First insert the following information into the t_user table in the database:

INSERT INTO t_user VALUES (111, '黄小黄', 'true');
INSERT INTO t_user VALUES (222, '懒羊羊', 'true');

Declare in UserDao, implement the query method in UserDaoImp, and use UserService:

    //查询返回对象
    @Override
    public User findUserInfo(String id) {
    
    
        String sql = "select * from t_user where user_id = ?";
        User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), id);
        return user;
    }

Query test:

    @Test
    public void testJdbcTemplate(){
    
    
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean.xml");
        UserService userService = context.getBean("userService", UserService.class);
        User one = userService.findOne("111");
        System.out.println(one);
    }

insert image description here

4.3 Return collection

Similar to the returned object, here we take querying user information as an example to return all records in t_user

Through the query method in jdbcTemlate:
insert image description here

  • The first parameter: sql statement;
  • The second parameter: RowMapper is an interface that returns different types of data, and the implementation class of this interface is used to complete the data encapsulation.
  • The third parameter: sql statement value (can be omitted if none).

Declare in UserDao, implement the query method in UserDaoImp, and use UserService:

    //查询返回集合
    @Override
    public List<User> findAllUser() {
    
    
        String sql = "select * from t_user";
        List<User> userList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class));
        return userList;
    }

Test and iterate:

    @Test
    public void testJdbcTemplate(){
    
    
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean.xml");
        UserService userService = context.getBean("userService", UserService.class);
        List<User> userList = userService.findAll();
        for (User user :
                userList) {
    
    
            System.out.println(user);
        }
    }

insert image description here


5 batch operations

To operate on multiple records in the table, the batch operation is mainly realized through the batchUpdate method in javaTemplate
insert image description here

  • The first parameter: sql statement;
  • The second parameter: List collection, add multiple records of data.

5.1 Batch add and modify

The code added in batches in the UserDaoImp ​​class is as follows:

    //批量添加
    @Override
    public void batchAddUser(List<Object[]> batchArgs) {
    
    
        String sql = "insert into t_user values(?,?,?)";
        int[] update = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println("影响的行数: " + update);
    }

Add in batches in the test class:

    @Test
    public void testJdbcTemplate(){
    
    
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean.xml");
        UserService userService = context.getBean("userService", UserService.class);
        //向表中添加三条记录
        List<Object[]> batchArgs = new ArrayList<>();
        Object[] o1 = {
    
    1, "nezuko", "true"};
        Object[] o2 = {
    
    2, "dog", "true"};
        Object[] o3 = {
    
    3, "participant", "true"};
        batchArgs.add(o1);
        batchArgs.add(o2);
        batchArgs.add(o3);
        userService.batchAdd(batchArgs);
    }

insert image description here
insert image description here

5.2 Batch modification and batch deletion

Batch modification is similar to batch deletion and batch addition. You only need to change the corresponding sql statement. Only the core code is shown here:

Batch Edit

    //批量修改
    @Override
    public void batchUpdate(List<Object[]> batchArgs) {
    
    
        String sql = "update t_user set username = ?, ustatus = ? where user_id = ?";
        int[] update = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println("影响的行数: " + Arrays.toString(update));
    }

batch deletion

    //批量删除
    @Override
    public void batchDelete(List<Object[]> batchArgs) {
    
    
        String sql = "delete from t_user where user_id = ?";
        int[] update = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println("影响的行数: " + Arrays.toString(update));
    }

write at the end

 So far, the simple addition, deletion, modification and query operations of the database using JdbcTemplate have been explained. The next section will continue to explain the operation of related transactions. The relevant environment dependencies of the JdbcTemplate experiment have been uploaded. The download link is attached: druid-1.1.9.jar+ mysql -connector-java-8.0.29.jar and other JdbcTempate operation resources

insert image description here

Guess you like

Origin blog.csdn.net/m0_60353039/article/details/127891820