Summary of important knowledge points of the Spring framework (4)

JDBC template technology of Spring framework

One, JDBC template technology

(1) What is template technology

The Spring framework provides a lot of template classes for the persistence layer to simplify programming. Using template classes to write programs will become simpler. The JdbcTemplate class provided by the Spring framework, Connection represents the connection, and manages the transaction Statement ResultSet.

(Two) the use of templates

①Create a maven project and introduce coordinates

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.12</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>
    
    <dependency>
        <groupId>aopalliance</groupId>
        <artifactId>aopalliance</artifactId>
        <version>1.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.8.13</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.6</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>
  </dependencies>

②Write test code (using the new object method)

public class Demo1 {

@Test
public void run1(){
    // 创建连接池对象,Spring框架内置了连接池对象
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    // 设置4个参数
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql:///数据库");
    dataSource.setUsername("用户名");
    dataSource.setPassword("密码");
    
    // 提供模板,创建对象
    JdbcTemplate template = new JdbcTemplate(dataSource);
    // 完成数据的增删改查
    template.update("insert into account values (null,?,?)","熊大",1000);
}}

(3) Use the Spring framework to manage template classes

①Spring management built-in connection pool

<?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"
       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">

        <!--配置连接池-->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
                <!--设置4个值-->
                <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///spring_db"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
        </bean>
        <!--配置模板类-->
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
                <property name="dataSource" ref="dataSource"/>
        </bean>
</beans>

②Write test method

@RunWith(SpringJUnit4ClassRunner.class)//单元测试
@ContextConfiguration("classpath:applicationContext5.xml")//加载配置文件
public class demo5 {
	//按类型自动导入
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Test
    public void run1(){
        //提供数据的增删改查
        jdbcTemplate.update("insert into account values (null,?,?)","雄二",9989);
    }
}

(4) Spring framework management open source connection pool

①Import the Druid open source connection pool
②Configure the database connection information to the properties file (jdbc.properties) ③Change the
core configuration

		<!--使用提供标签的方式-->
        <context:property-placeholder location="classpath:jdbc.properties"/>

        <!--加载属性文件-->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
                <property name="driverClassName" value="${jdbc.driverClassName}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />

        </bean>

        <!--配置模板类-->
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
                <property name="dataSource" ref="dataSource"/>
        </bean>

(5) Simple operations of the JDBC template of the Spring framework (add, delete, modify, check)

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "classpath:applicationContext_jdbc.xml")
public class Demo1_1 {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 测试的方式  增
     */
    @Test
    public void run1(){
        jdbcTemplate.update("insert into account values (null,?,?)","熊四",800);
    }
    /**
     * 修改
     */
    @Test
    public void run2(){
        jdbcTemplate.update("update account set name = ?,money = ? where id = ?","光头强",100,7);
    }
    /**
     * 删除
     */
    @Test
    public void run3(){
        jdbcTemplate.update("delete from account where id = ?",7);
    }
    /**
     * 通过id查询
     */
    @Test
    public void run4(){
        Account account = jdbcTemplate.queryForObject("select * from account where id = ?", new BeanMapper(), 6);
        System.out.println(account);
    }
    /**
     * 查询所有的数据
     */
    @Test
    public void run5(){
        List<Account> list = jdbcTemplate.query("select * from account", new BeanMapper());
        for (Account account : list) {
            System.out.println(account);
        }
    }
}
/**
 * 实现类,用来进行数据封装的
 */
class BeanMapper implements RowMapper<Account>{
    /**
     * 是一行一行进行数据封装的
     */
    @Override
    public Account mapRow(ResultSet resultSet, int i) throws SQLException {
        Account account = new Account();
        account.setId(resultSet.getInt("id"));
        account.setName(resultSet.getString("name"));
        account.setMoney(resultSet.getDouble("money"));
        return account;
    }
}

2. Simulated transfer development (exercise)

First set up the environment (maven project coordinates)

(1) Preparation of service code

接口:
public interface AccountService {
    public void pay(String out,String in,double money);
}
实现类:
public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao;
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }
	//转账方法
    @Override
    public void pay(String out, String in, double money) {
        // 调用dao方法
        accountDao.outMoney(out,money);
        accountDao.inMoney(in,money);
    }
}

(Two) the preparation of dao code

接口:
public interface AccountDao {
	//付款
    public void outMoney(String out,double money);
   	//收款
    public void inMoney(String in,double money);
}
实现类:
public class AccountDaoImpl implements AccountDao {
    private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
 	//付款
    public void outMoney(String out, double money) {
        jdbcTemplate.update("update account set money = money - ? where name = ?",money,out);
    }
    //收款
    public void inMoney(String in, double money) {
        jdbcTemplate.update("update account set money = money + ? where name = ?",money,in);
    }
}
The second way of writing dao code

Inherit JdbcDaoSupport

(Three) configuration file code writing

Same constraints as above

<!--第二种写法:使用提供标签的方式-->
    <context:property-placeholder location="classpath:jdbc.properties" />

    <!--加载属性的文件-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <!--配置Jdbc模板类-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!--配置service-->
    <bean id="accountService" class="cn.tx.demo2.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"/>
     </bean>

    <!--配置dao-->
    <bean id="accountDao" class="cn.tx.demo2.AccountDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate" />
    </bean>

(4) Test code writing

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "classpath:配置文件")
public class Demo2 {
	//按照类型自动导入
    @Autowired
    private AccountService accountService;
    /**
     * 测试转账的方法
     */
    @Test
    public void testPay(){
        accountService.pay("熊大","熊二",100);
    }
}

Three, Spring framework declarative transaction management

PlatformTransactionManager interface
Platform transaction manager. The interface has a specific implementation class. According to different persistence layer frameworks, you need to choose different implementation classes!
The interface method is as follows:
void commit(TransactionStatus status)
void rollback(TransactionStatus status)
If you use Spring's JDBC template or MyBatis framework, you need to select the DataSourceTransactionManager implementation class

(1) How to configure files

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>

<!--配置事务的通知(没有自己编写切面类,通知方法也不是自己编写,Spring框架提供的)-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <!--对pay进行增强,设置隔离级别,传播行为,超时的时间-->
        <tx:method name="pay" isolation="DEFAULT" propagation="REQUIRED" />
        <tx:method name="find*" read-only="true" />
    </tx:attributes>
</tx:advice>

<!--配置AOP的增强-->
<aop:config>
    <!--Spring框架提供系统通知,使用advisor标签-->
    <aop:advisor advice-ref="txAdvice" pointcut="execution(public * cn.tx.demo4.AccountServiceImpl.pay(..))" />
</aop:config>

(2) Configuration file + annotation method

①Leave the configuration file, configure the configuration of the platform transaction manager
②Inject the service and @Transactional(isolation = Isolation.DEFAULT)

(3) Pure annotation method

The purpose of pure annotation is to replace all configuration files, but you need to write configuration classes

	/**
     * 配置类
     * @author Administrator
     */
    @Configuration  //声明配置类
    @ComponentScan(basePackages="cn.tx.demo6")  //扫描
    @EnableTransactionManagement        // 开启事务注解
    public class SpringConfig {
      
        @Bean(name="dataSource")
        public DataSource createDataSource() throws Exception{
            // 创建连接池对象,Spring框架内置了连接池对象
            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            // 设置4个参数
            dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            dataSource.setUrl("jdbc:mysql:///spring_db");
            dataSource.setUsername("root");
            dataSource.setPassword("root");
            return dataSource;
        }
        /**
         * 创建模板对象
         * @return
         */
        @Resource(name="dataSource")        // 不仅可以作用在属性上,也可以作用方法上。
        @Bean(name="jdbcTemplate")          // 把JdbcTemplate保存到IOC容器中
        public JdbcTemplate createJdbcTemplate(DataSource dataSource){
            JdbcTemplate template = new JdbcTemplate(dataSource);
            return template;
        }
        /**
         * 创建平台事务管理器对象
         * @param dataSource
         * @return
         */
        @Resource(name="dataSource")
        @Bean(name="transactionManager")
        public PlatformTransactionManager createTransactionManager(DataSource dataSource){
            DataSourceTransactionManager manager = new DataSourceTransactionManager(dataSource);
            return manager;
        }     
    }

Guess you like

Origin blog.csdn.net/javaScript1997/article/details/108113521