JAVAEE - spring 03: spring integrates JDBC and aop transactions

Keywords: Java JDBC Spring SQL MySQL

1. spring Integration JDBC

1.spring provides many templates to integrate Dao Technology

  

2.spring provides an object that can operate database. Objects encapsulate jdbc technology.

JDBCTemplate => JDBC template object

It is very similar to Query Runner in DBUtils.

        //0 Prepare connection pool
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql:///xieyupeng");
        dataSource.setUser("root");
        dataSource.setPassword("1234");
        //1 Establish JDBC Template object
        JdbcTemplate jt = new JdbcTemplate();
        jt.setDataSource(dataSource);
        //2 write sql,And execute
        String sql = "insert into t_user values(null,'rose') ";
        jt.update(sql);

3. Integration steps

3.1 Guide

4+2:4 stands for:

2 Representatives: com.springsource.org.apache.commons.logging-1.1.1.jar, com.springsource.org.apache.log4j-1.2.15.jar.

Spr-test, spring-aop, junit4 Libraries

c3p0 connection pool, JDBC driver

Spr-jdbc, spring-tx transactions

3.2 Prepare the database (two fields id (self-growth) and name will do)

3.3 Writing Dao

//Use JDBC Template for Addition, Deletion, Change and Check
public class UserDaoImpl extends JdbcDaoSupport implements UserDao {
    @Override
    public void save(User u) {
        String sql = "insert into t_user values(null,?) ";
        super.getJdbcTemplate().update(sql, u.getName());
    }
    @Override
    public void delete(Integer id) {
        String sql = "delete from t_user where id = ? ";
        super.getJdbcTemplate().update(sql,id);
    }
    @Override
    public void update(User u) {
        String sql = "update  t_user set name = ? where id=? ";
        super.getJdbcTemplate().update(sql, u.getName(),u.getId());
    }
    @Override
    public User getById(Integer id) {
        String sql = "select * from t_user where id = ? ";
        return super.getJdbcTemplate().queryForObject(sql,new RowMapper<User>(){
            @Override
            public User mapRow(ResultSet rs, int arg1) throws SQLException {
                User u = new User();
                u.setId(rs.getInt("id"));
                u.setName(rs.getString("name"));
                return u;
            }}, id);
        
    }
    @Override
    public int getTotalCount() {
        String sql = "select count(*) from t_user  ";
        Integer count = super.getJdbcTemplate().queryForObject(sql, Integer.class);
        return count;
    }

    @Override
    public List<User> getAll() {
        String sql = "select * from t_user  ";
        List<User> list = super.getJdbcTemplate().query(sql, new RowMapper<User>(){
            @Override
            public User mapRow(ResultSet rs, int arg1) throws SQLException {
                User u = new User();
                u.setId(rs.getInt("id"));
                u.setName(rs.getString("name"));
                return u;
            }});
        return list;
    }
}

3.4 spring configuration

Dependency

<!-- 1.Put the connection pool in spring container -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
    <property name="driverClass" value="${jdbc.driverClass}" ></property>
    <property name="user" value="${jdbc.user}" ></property>
    <property name="password" value="${jdbc.password}" ></property>
</bean>


<!-- 2.take JDBCTemplate Put in spring container -->
<bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >
    <property name="dataSource" ref="dataSource" ></property>
</bean>

<!-- 3.take UserDao Put in spring container -->
<bean name="userDao" class="cn.itcast.a_jdbctemplate.UserDaoImpl" >
    <!-- <property name="jt" ref="jdbcTemplate" ></property> -->
    <property name="dataSource" ref="dataSource" ></property>
</bean>

3.5 Test

//Demonstration JDBC Template
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {
    @Resource(name="userDao")
    private UserDao ud;

    @Test
    public void fun2() throws Exception{
        User u = new User();
        u.setName("tom");
        ud.save(u);
    }
    @Test
    public void fun3() throws Exception{
        User u = new User();
        u.setId(2);
        u.setName("jack");
        ud.update(u);
        
    }
    
    @Test
    public void fun4() throws Exception{
        ud.delete(2);
    }
    
    @Test
    public void fun5() throws Exception{
        System.out.println(ud.getTotalCount());
    }
    
    @Test
    public void fun6() throws Exception{
        System.out.println(ud.getById(1));
    }
    
    @Test
    public void fun7() throws Exception{
        System.out.println(ud.getAll());
    }
    
}

4. Advanced Contents

   4.1 JDBCDaoSupport

public class UserDaoImpl extends JdbcDaoSupport

<!-- 3.take UserDao Put in spring container(inherit JDBCDaoSupport,Direct injection dataSourse that will do) -->
<bean name="userDao" class="cn.itcast.a_jdbctemplate.UserDaoImpl" >
    <!-- <property name="jt" ref="jdbcTemplate" ></property> -->
    <property name="dataSource" ref="dataSource" ></property>
</bean>

4.1 Read the external Proerties configuration

Attention should be paid to prefixing db.properties (better distinction, avoid renaming)

jdbc.jdbcUrl=jdbc:mysql:///hibernate_32
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=1234
<!-- Appoint spring read db.properties To configure -->
<context:property-placeholder location="classpath:db.properties"  />

<!-- 1.Put the connection pool in spring container -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
    <property name="driverClass" value="${jdbc.driverClass}" ></property>
    <property name="user" value="${jdbc.user}" ></property>
    <property name="password" value="${jdbc.password}" ></property>
</bean>

 

Configuring spring with annotations

1. Business Review

Transaction characteristics: acid

Transaction Concurrency Problems: Dirty Reading, Non-repeatable Reading, Illusive Reading

Transaction isolation level: 1 read uncommitted, 2 read submitted, 4 repeatable read, 8 serialization

2.spring encapsulates transaction management code

Transaction operation: Open transaction, commit transaction, rollback transaction

Transaction Operating Objects

Because the code for operating transactions varies from platform to platform. spring provides an interface

2.1 Platform Transaction Manager interface

   DataSourceTransactionManager

   HibernateTransitionmanager

Note: Play transaction management in spring. The core object is the Transaction Manager object.

2.2 Introduction to the attributes of spring management transactions

Transaction isolation level: 1 read uncommitted, 2 read submitted, 4 repeatable read, 8 serialization

Read-Only: true Read-Only, false Operational

Transaction communication behavior:

  

3.spring Management Transaction Mode

  

 

3.1 Encoding Formula (Understanding)

3.1.1 Configure the core transaction manager to the spring container

<! - Transaction Core Manager, which encapsulates all transaction operations. Depends on connection pools - >.
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
    <property name="dataSource" ref="dataSource" ></property>
</bean>

3.1.2 Configure the Transaction Template template

<!-- Transaction template object -->
<bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate" >
    <property name="transactionManager" ref="transactionManager" ></property>
</bean>

3.1.3 Injecting Transaction Template into Service

<!-- 3.Service-->
<bean name="accountService" class="cn.itcast.service.AccountServiceImpl" >
    <property name="ad" ref="accountDao" ></property>
    <property name="tt" ref="transactionTemplate" ></property>
</bean> 

3.1.4 Call Template in Service

    public void transfer(final Integer from,final Integer to,final Double money) {
        
        tt.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus arg0) {
                //Reduce money
                ad.decreaseMoney(from, money);
                int i = 1/0;//Trigger an error to verify that the code is correct
                //Add money
                ad.increaseMoney(to, money);
            }
        });
    }

3.2 xml configuration (aop)

3.2.1 Guide

aop, aspect, aop alliance and weaving weaving package

3.2.2 Import new constraints (tx)

  

beans: Basically
context: Read the properties configuration
aop: Configure aop
tx: Configuration transaction notification

3.2.3 Configuration Notification

<!-- Configuration transaction notification -->
<tx:advice id="txAdvice" transaction-manager="transactionManager" >
    <tx:attributes>
        <!-- In terms of methods,Specify what transaction attributes the method applies
            isolation:Isolation level
            propagation:Communication behavior
            read-only:readOnly
         -->
        <tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="modify*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
        <tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
        <tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
    </tx:attributes>
</tx:advice>

3.2.4 configuration will inform weaving target

<! - Configuration weaving - >
<aop:config  >
    <! - Configure the tangent expression - >
    <aop:pointcut expression="execution(* cn.itcast.service.*ServiceImpl.*(..))" id="txPc"/>
    <! - Configuration Aspect: Notification + Cut Point
             advice-ref: Name of notification
             pointcut-ref: The name of the pointcut
     -->
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPc" />
</aop:config>

3.3 Annotation Configuration (aop)

Guide packages, tx constraints, and xml configuration (aop) are the same

3.3.1 Open Annotation Management Services

<! - Open the use of annotations to manage aop transactions - >
<tx:annotation-driven/>

3.3.2 Use of annotations

@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=true)
public class AccountServiceImpl implements AccountService {

    private AccountDao ad ;
    private TransactionTemplate tt;
    
    @Override
    @Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false)
    public void transfer(final Integer from,final Integer to,final Double money) {

Posted by marsupillami on Fri, 11 Jan 2019 22:27:10 -0800