Example of implementing declarative transaction operation with annotation in spring practice

Time:2020-6-22

The example of this article describes the implementation of declarative transaction operations with annotations in spring practice. To share with you for your reference, as follows:

One configuration file

<?xml version="1.0" encoding="GBK"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="http://www.springframework.org/schema/beans"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:aop="http://www.springframework.org/schema/aop"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
   <! -- define data source bean, use c3p0 data source to implement, and inject necessary information of data source -- >
   <bean
      destroy-method="close"
      p:driverClass="com.mysql.jdbc.Driver"
      p:jdbcUrl="jdbc:mysql://localhost/spring"
      p:user="root"
      p:password="32147"
      p:maxPoolSize="40"
      p:minPoolSize="2"
      p:initialPoolSize="2"
      p:maxIdleTime="30"/>
   <! -- configure a business logic bean -- >
   <bean
      p:ds-ref="dataSource"/>
   <! -- configure the local transaction manager of the JDBC data source using the DataSourceTransactionManager class -- >
   <! -- this class implements the platformtransactionmanager interface, which is a specific implementation of adopting data source connection -- >
   <! -- configure datasourcetransactionmanager according to the reference injected into datasource -- >
   <bean
     
      p:dataSource-ref="dataSource"/>
   <! -- generate transaction agent based on annotation -- >
   <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

Two Dao

1 interface


package org.crazyit.app.dao;
public interface NewsDao
{
   public void insert(String title, String content);
}

2 implementation class

package org.crazyit.app.dao.impl;
import javax.sql.DataSource;
import java.sql.Connection;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.*;
import org.crazyit.app.dao.*;
public class NewsDaoImpl implements NewsDao
{
  private DataSource ds;
  public void setDs(DataSource ds)
  {
    this.ds = ds;
  }
  @Transactional(propagation=Propagation.REQUIRED ,
    isolation=Isolation.DEFAULT , timeout=5)
  public void insert(String title, String content)
  {
    JdbcTemplate jt = new JdbcTemplate(ds);
    jt.update("insert into news_inf"
      + " values(null , ? , ?)"
      , title , content);
    //Data inserted twice violates unique key constraint
    jt.update("insert into news_inf"
      + " values(null , ? , ?)"
      , title , content);
    //If there is no transaction control, the first record can be inserted
    //If transaction control is added, the first record will not be inserted.
  }
}

III. testing

package lee;
import org.springframework.context.support.*;
import org.springframework.context.*;
import org.crazyit.app.dao.*;
public class SpringTest
{
  public static void main(String[] args)
  {
    //Create spring container
    ApplicationContext ctx = new
      ClassPathXmlApplicationContext("beans.xml");
    //Get transaction agent bean
    NewsDao dao = (NewsDao)ctx
      .getBean("newsDaoTrans" , NewsDao.class);
    //Perform insert operation
    dao.insert ("crazy Java", "lightweight Java EE enterprise application practice");
  }
}

IV. test

The database does not generate data, indicating that the transaction is effective.

Exception in thread “main”  org.springframework.dao .DuplicateKeyException:  PreparedStatementCallback; SQL [insert into news_ Inf values (null,?,?)]; duplicate entry ‘crazy Java’ for key ‘news_ title’; nested exception is  com.mysql.jdbc . exceptions.jdbc4 . MySQL integrity constraintviolationexception: duplicate entry ‘crazy Java’ for key ‘news_ title’
     at  org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:239)
     at  org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
     at  org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:660)
     at  org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:909)
     at  org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:970)
     at  org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:980)
     at  org.crazyit.app.dao.impl.NewsDaoImpl.insert(NewsDaoImpl.java:33)
     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native  Method)
     at  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
     at  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
     at java.lang.reflect.Method.invoke(Method.java:498)
     at  org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
     at  org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
     at  org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
     at  org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
     at  org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
     at  org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
     at  org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
     at  org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
     at com.sun.proxy.$Proxy4.insert(Unknown Source)
     at lee.SpringTest.main(SpringTest.java:28)
Caused by:  com.mysql.jdbc . exceptions.jdbc4 . MySQL integrity constraintviolationexception: duplicate entry ‘crazy Java’ for key ‘news_ title’
     at  sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native  Method)
     at  sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
     at  sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
     at  java.lang.reflect.Constructor.newInstance(Constructor.java:423)
     at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
     at com.mysql.jdbc.Util.getInstance(Util.java:384)
     at  com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1039)
     at  com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4232)
     at  com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4164)
     at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2615)
     at  com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2776)
     at  com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2838)
     at  com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2082)
     at  com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2334)
     at  com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2262)
     at  com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2246)
     at  com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:147)
     at  org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(JdbcTemplate.java:916)
     at  org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(JdbcTemplate.java:909)
     at  org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:644)
     … 18 more

For more information about Java related content, you can see our special topics: introduction and advanced course of spring framework, Java data structure and algorithm course, summary of Java operation DOM node skills, summary of java file and directory operation skills and summary of Java cache operation skills

I hope this article will be helpful to you in Java programming.