[SSM-Spring Chapter 06] Spring Database Programming-JdbcTemplate (Spring jdbc template)

Spring database programming

  The Spring framework provides developers with a JDBC template mode, jdbcTemplate, which can simplify many codes, but jdbcTemplate is not commonly used in practical applications. When I work more, I use Hibernate framework and MyBatis framework for database programming

Spring JDBC configuration (jdbcTemplate)

  Spring database programming mainly uses the core and dataSource packages of the Spring JDBC module. The core package is the core function package of JDBC, including the commonly used JdbcTemplate class; the dataSource package is a tool package for accessing data sources. To use Spring JDBC to operate the database, it needs to be configured.
  When configuring the JDBC template, you need to inject the dataSource into the jdbcTemplate. When the data access layer (Dao class) needs to use the jdbcTemplate, you also need to inject the jdbcTemplate into the corresponding Bean.

Case realization

  1. pom.xml import jdbc dependency
<!-- jdbc连接 -->
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.0.2.RELEASE</version>
    </dependency>
  1. Configure the data source and jdbc template in applicationContext.xml (when configuring the JDBC template, you need to inject the dataSource into the jdbcTemplate)
<?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.xgf.transaction.springjdbc"/>

    <!-- 配置数据源数据库连接 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
        <property name="url" value="jdbc:mysql://localhost:3306/spring?useUnicode=true&amp;characterEncoding=utf-8"/>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    </bean>

    <!-- 将dataSource注入到jdbcTemplate 封装数据库操作方法,简化数据库操作  -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--  事务管理器 完成手动事务管理  -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
        <property name="transactionManager" ref="transactionManager"/>
    </bean>

</beans>
  1. Create UserDao database access layer template.
    When jdbcTemplate is needed in the data access layer (Dao class), jdbcTemplate needs to be injected into the corresponding Bean when configuring applicationContext.xml.
@Repository
public class UserDaoTemplete {
    
    
    /*注入 JdbcTemplate*/
    @Autowired
    private JdbcTemplate jdbcTemplate;
    // 注入事务管理
    @Autowired
    private TransactionTemplate transactionTemplate;

    public void save(){
    
    
        transactionTemplate.execute(new TransactionCallback(){
    
    
            /*业务逻辑*/
            @Override
            public Object doInTransaction(TransactionStatus transactionStatus) {
    
    
                String sql = "insert into user(id,username,password,age) values(?,?,?,?)";
                Object[] params = new Object[]{
    
    null,"springjdbc - study day","123456",20};
                jdbcTemplate.update(sql,params);
                //出现异常,事务会回滚,不会写入数据库中
                //int i = 100/0;
                System.out.println("save() - 用户数据保存成功");
                return null;
            }
        });
    }
}

  1. Write test class
public class SpringJDBCTest {
    
    

    public static void main(String[] args) {
    
    

        ApplicationContext context =
                new ClassPathXmlApplicationContext("com/xgf/transaction/springjdbc/applicationContext.xml");
        UserDaoTemplete userDao = (UserDaoTemplete)context.getBean("userDaoTemplete");
        userDao.save();
    }
}

  1. operation result
    Insert picture description here
    Insert picture description here
  2. The test is abnormal, whether the transaction is rolled back (i = 100/0)
      update the data first, and then the abnormal
    Insert picture description here

  Check the update status of the database and find that the data is not updated, the transaction is rolled back, and the wrong addition is deleted.
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_40542534/article/details/108690462