JAVAEE -- spring03: spring integrates JDBC and aop transactions, javaeespring03

Source: Internet
Author: User

JAVAEE -- spring03: spring integrates JDBC and aop transactions, javaeespring03
I. Integrate spring with JDBC 1. spring provides a lot of Dao technology for template Integration

  

2. spring provides an object for database operations. The object encapsulates the jdbc technology.

JDBCTemplate => JDBC template object

It is very similar to QueryRunner in DBUtils.

// 0 prepare the connection pool ComboPooledDataSource dataSource = new ComboPooledDataSource (); dataSource. setDriverClass ("com. mysql. jdbc. driver "); dataSource. setJdbcUrl ("jdbc: mysql: // xieyupeng"); dataSource. setUser ("root"); dataSource. setPassword ("1234"); // 1 create the JDBC template object JdbcTemplate jt = new JdbcTemplate (); jt. setDataSource (dataSource); // 2 Write the SQL statement and run String SQL = "insert into t_user values (null, 'Rose ')"; jt. update (SQL );
3. Integration Step 3.1 import package

4 + 2: 4 represents:

2 representative: com.springsource.org. apache. commons. logging-1.1.1.jar, com.springsource.org. apache. log4j-1.2.15.jar (the old version to import, the import can be guaranteed to run)

Spring-test, spring-aop, and junit4 Class Libraries

C3p0 connection pool, JDBC driver

Spring-jdbc and spring-tx transactions

3.2 prepare the database (two Field IDS (auto-increment) and name) 3.3 write Dao
// Use the JDBC template to add, delete, modify, and query 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 into the 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. put JDBCTemplate into the spring container --> <bean name = "jdbcTemplate" class = "org. springframework. jdbc. core. jdbcTemplate "> <property name =" dataSource "ref =" dataSource "> </property> </bean> <! -- 3. Add UserDao to the 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
// Demonstrate the 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 content 4.1 JDBCDaoSupport
public class UserDaoImpl extends JdbcDaoSupport

<! -- 3. Add UserDao to the spring container (inherit from JDBCDaoSupport and directly inject into sponse) --> <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 external Properties configuration

Db. properties pay attention to prefix (better differentiation to prevent duplicate names)

jdbc.jdbcUrl=jdbc:mysql:///hibernate_32jdbc.driverClass=com.mysql.jdbc.Driverjdbc.user=rootjdbc.password=1234
<! -- Specify spring to read db. properties configuration --> <context: property-placeholder location = "classpath: db. properties"/> <! -- 1. put the connection pool into the 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>
Ii. Use annotations to configure spring 1. Transaction review

Transaction Features: acid

Transaction concurrency problems: dirty reads, non-repeated reads, Phantom reads

Transaction isolation level: 1 read uncommitted, 2 read committed, 4 Repeatable read, 8 serialize

2. spring encapsulates the Transaction Management Code

Transaction operations: open transactions, commit transactions, roll back transactions

Transaction operation object

Because the code for operating transactions varies on different platforms. spring provides an interface

2.1 PlatformTransactionManager Interface

DataSourceTransactionManager

HibernateTransitionmanager

Note: In spring, the most important object is the TransactionManager object.

2.2 Introduction to spring's transaction management attributes

Transaction isolation level: 1 read uncommitted, 2 read committed, 4 Repeatable read, 8 serialize

Read-Only: true; read-only; false; operable

Propagation Behavior of transactions:

  

3. spring transaction management method

  

 

3.1 understand (understand) 3.1.1 configure the core Transaction Manager to the spring container
<! -- The core Transaction Manager encapsulates all transaction operations. dependent on the connection pool --> <bean name = "transactionManager" class = "org. springframework. jdbc. datasource. dataSourceTransactionManager "> <property name =" dataSource "ref =" dataSource "> </property> </bean>
3.1.2 configure the TransactionTemplate Template
<! -- Transaction template object --> <bean name = "transactionTemplate" class = "org. springframework. transaction. support. transactionTemplate "> <property name =" transactionManager "ref =" transactionManager "> </property> </bean>
3.1.3 inject the transaction Template into the 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.exe cute (new TransactionCallbackWithoutResult () {@ Override protected void doInTransactionWithoutResult (TransactionStatus arg0) {// deduct money ad. decreaseMoney (from, money); int I = 1/0; // trigger an error to verify whether the code is correct // Add money to ad. increaseMoney (to, money );}});}
3.2 xml configuration (aop) 3.2.1 import package

Aop, aspect, aop alliance, and weaving

3.2.2 import new constraints (tx)

  

Beans: Basic
Context: Read properties configuration
Aop: Configure aop
Tx: Configure transaction notifications

3.2.3 configuration notification
<! -- Configure transaction notification --> <tx: advice id = "txAdvice" transaction-manager = "transactionManager"> <tx: attributes> <! -- In the unit of method, specify the transaction attribute isolation used by the method: isolation level propagation: propagation Behavior read-only: read-only --> <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 configure to route notifications to the target
<! -- Configure woven --> <aop: config> <! -- Configure the cut expression --> <aop: pointcut expression = "execution (* cn. itcast. service. * ServiceImpl. *(..)) "id =" txPc "/> <! -- Configuration aspect: Notification + cut point advice-ref: Notification name pointcut-ref: Cut Point name --> <aop: advisor advice-ref = "txAdvice" pointcut-ref = "txPc"/> </aop: config>
3.3 annotation configuration (aop) pilot package, tx constraint, and xml configuration (aop) Same 3.3.1 enable annotation management transaction
<! -- Enable the use of annotations to manage aop transactions --> <tx: annotation-driven/>
3.3.2 Annotation
@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) {

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.