Detailed use of Spring JdbcTemplate

Introduction to JdbcTemplate

  Spring's database operations are deeply encapsulated on jdbc. Using spring's injection function, DataSource can be registered in JdbcTemplate.

  JdbcTemplate is located in. Its fully qualified name is org.springframework.jdbc.core.JdbcTemplate. To use JdbcTemlate, you need a package that includes transaction and exception control

  

JdbcTemplate mainly provides the following five types of methods:

  • 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, function-related statements.

The following case analysis

Create a new property configuration file under src

jdbc.user=root
jdbc.password=123456
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc\:mysql\:///test

We usually put the configuration information of the database into a separate file, which is also convenient for later maintenance.

Configure the Spring configuration file applicationContext.xml

<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="user" value="${jdbc.user}"></property>
    <property name="password" value="${jdbc.password}"></property>
    <property name="driverClass" value="${jdbc.driverClass}"></property>
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
</bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"></property>
</bean>

The first line of code: used to read the data in the db.properties file.

  The second line of code: used to configure a data source, where the data implementation class comes from an attribute class in C3P0. The value of the property is from db.properties

  The ninth line of code: configure a JdbcTemplate instance and inject a dataSource data source

test code

1. update() method

a. Insert data through update

//Start the IoC container
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
//Get the instance of JdbcTemplate in the IoC container
JdbcTemplate jdbcTemplate=(JdbcTemplate) ctx.getBean("jdbcTemplate");
String sql="insert into user (name,deptid) values (?,?)";
int count= jdbcTemplate.update(sql, new Object[]{"caoyc",3});
System.out.println(count);

Here in the update method, the second parameter can be a variable parameter. As you can see in the database, the data is inserted correctly

b. Modify data through update

String sql="update user set name=?,deptid=? where id=?";
jdbcTemplate.update(sql,new Object[]{"zhh",5,51});
 c. Delete data through update
String sql="delete from user where id=?";
jdbcTemplate.update(sql,51);

2. batchUpdate() batch insert, update and delete methods

a, batch insert

String sql="insert into user (name,deptid) values (?,?)";

List<Object[]> batchArgs=new ArrayList<Object[]>();
batchArgs.add(new Object[]{"caoyc",6});
batchArgs.add(new Object[]{"zhh",8});
batchArgs.add(new Object[]{"cjx",8});

jdbcTemplate.batchUpdate(sql, batchArgs);
The second parameter of the batchUpdate method is a List collection whose elements are Object[] array types

3. Read data from data to entity object

  First define a User entity class

package com.proc;

public class User {
    private Integer id;
    private String name;
    private Integer deptid;
    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 Integer getDeptid() {
        return deptid;
    }
    public void setDeptid(Integer deptid) {
        this.deptid = deptid;
    }

    public String toString() {
        return "User [id=" + id + ", name=" + name + ", deptid=" + deptid + "]";
    }
}
a, read a single object
String sql="select id,name,deptid from user where id=?";
RowMapper<User> rowMapper=new BeanPropertyRowMapper<User>(User.class);
User user= jdbcTemplate.queryForObject(sql, rowMapper,52);
System.out.println(user);

Output result:

  User [id=52, name=caoyc, deptid=6]

[Note]: 1. Using BeanProperytRowMapper requires that the columns and entity attributes queried from sql data need to be in one-to-one correspondence. If the data listed and the attribute name are inconsistent, you need to use as to take a new alias in the sql statement

     2. The associated object cannot be obtained using the JdbcTemplate object

b. Read multiple objects

String sql="select id,name,deptid from user";

RowMapper<User> rowMapper=new BeanPropertyRowMapper<User>(User.class);
List<User> users= jdbcTemplate.query(sql, rowMapper);
for (User user : users) {
    System.out.println(user);
}

output result

...

User [id=49, name=姓名49, deptid=5]
User [id=50, name=姓名50, deptid=8]
User [id=52, name=caoyc, deptid=6]
User [id=53, name=zhh, deptid=8]
User [id=54, name=cjx, deptid=8]

---

c. Get a column of a record or return a unique value from functions such as count, avg, sum, etc.

String sql="select count(*) from user";
int count= jdbcTemplate.queryForObject(sql, Integer.class);
System.out.println(count);

How can it be used in actual development

UserDao.java

package com.proc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

@Repository
public class UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    public User get(int id){
        String sql="select id,name,deptid from user where id=?";
        RowMapper<User> rowMapper=new BeanPropertyRowMapper<User>(User.class);
        return jdbcTemplate.queryForObject(sql, rowMapper,id);
    }
}
xml placement:
<?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/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        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-4.3.xsd">

<context:component-scan base-package="com.proc"></context:component-scan>
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="user" value="${jdbc.user}"></property>
    <property name="password" value="${jdbc.password}"></property>
    <property name="driverClass" value="${jdbc.driverClass}"></property>
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
</bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
代码测试
UserDao userDao=(UserDao) ctx.getBean("userDao");
2 System.out.println(userDao.get(53));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324691718&siteId=291194637