Gestione delle transazioni dichiarative di primavera

L'approccio di gestione delle transazioni dichiarativo consente di gestire la transazione con l'aiuto della configurazione invece dell'hard coding nel codice sorgente. Ciò significa che puoi separare la gestione delle transazioni dal codice aziendale. Utilizzi solo annotazioni o configurazioni basate su XML per gestire le transazioni. La configurazione del bean specificherà i metodi per essere transazionali. Ecco i passaggi associati alla transazione dichiarativa:

  • Usiamo il tag <tx: counsel />, che crea un avviso di gestione delle transazioni e allo stesso tempo definiamo un pointcut che corrisponde a tutti i metodi che desideriamo effettuare la transazione e fa riferimento al consiglio di transazione.

  • Se un nome di metodo è stato incluso nella configurazione transazionale, il consiglio creato inizierà la transazione prima di chiamare il metodo.

  • Il metodo di destinazione verrà eseguito in un blocco try / catch .

  • Se il metodo termina normalmente, l'avviso AOP esegue correttamente il commit della transazione altrimenti esegue un rollback.

Vediamo come funzionano i passaggi sopra menzionati ma prima di iniziare, è importante avere almeno due tabelle di database su cui possiamo eseguire varie operazioni CRUD con l'aiuto delle transazioni. Prendiamo un fileStudent tabella, che può essere creata nel database MySQL TEST con il seguente DDL -

CREATE TABLE Student(
   ID   INT NOT NULL AUTO_INCREMENT,
   NAME VARCHAR(20) NOT NULL,
   AGE  INT NOT NULL,
   PRIMARY KEY (ID)
);

Il secondo tavolo è Marksin cui manterremo i voti per gli studenti in base agli anni. QuiSID è la chiave esterna per la tabella Studente.

CREATE TABLE Marks(
   SID INT NOT NULL,
   MARKS  INT NOT NULL,
   YEAR   INT NOT NULL
);

Ora, scriviamo la nostra applicazione Spring JDBC che implementerà semplici operazioni sulle tabelle Student e Marks. Cerchiamo di avere un IDE Eclipse funzionante e di eseguire i seguenti passaggi per creare un'applicazione Spring:

Passo Descrizione
1 Crea un progetto con un nome SpringExample e crea un pacchetto com.tutorialspoint sottosrc cartella nel progetto creato.
2 Aggiungere le librerie Spring richieste utilizzando l' opzione Aggiungi JAR esterni come spiegato nel capitolo Esempio Spring Hello World .
3 Aggiungi altre librerie richieste mysql-connector-java.jar , aopalliance-xyjar , org.springframework.jdbc.jar e org.springframework.transaction.jar nel progetto. Puoi scaricare le librerie richieste se non le hai già.
4 Crea l'interfaccia DAO StudentDAO ed elenca tutti i metodi richiesti. Anche se non è richiesto e puoi scrivere direttamente nella classe StudentJDBCTemplate , ma come buona pratica, facciamolo.
5 Crea altre classi Java richieste StudentMarks , StudentMarksMapper , StudentJDBCTemplate e MainApp nel pacchetto com.tutorialspoint . Se necessario, puoi creare il resto delle classi POJO.
6 Assicurati di aver già creato Student e Markstabelle nel database TEST. Assicurati inoltre che il tuo server MySQL funzioni correttamente e di avere accesso in lettura / scrittura al database utilizzando il nome utente e la password forniti.
7 Crea il file di configurazione Beans Beans.xml sottosrc cartella.
8 Il passaggio finale consiste nel creare il contenuto di tutti i file Java e nel file di configurazione Bean ed eseguire l'applicazione come spiegato di seguito.

Di seguito è riportato il contenuto del file di interfaccia dell'oggetto di accesso ai dati StudentDAO.java

package com.tutorialspoint;

import java.util.List;
import javax.sql.DataSource;

public interface StudentDAO {
   /** 
      * This is the method to be used to initialize
      * database resources ie. connection.
   */
   public void setDataSource(DataSource ds);
   
   /** 
      * This is the method to be used to create
      * a record in the Student and Marks tables.
   */
   public void create(String name, Integer age, Integer marks, Integer year);
   
   /** 
      * This is the method to be used to list down
      * all the records from the Student and Marks tables.
   */
   public List<StudentMarks> listStudents();
}

Di seguito è riportato il contenuto del file StudentMarks.java file

package com.tutorialspoint;

public class StudentMarks {
   private Integer age;
   private String name;
   private Integer id;
   private Integer marks;
   private Integer year;
   private Integer sid;

   public void setAge(Integer age) {
      this.age = age;
   }
   public Integer getAge() {
      return age;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getName() {
      return name;
   }
   public void setId(Integer id) {
      this.id = id;
   }
   public Integer getId() {
      return id;
   }
   public void setMarks(Integer marks) {
      this.marks = marks;
   }
   public Integer getMarks() {
      return marks;
   }
   public void setYear(Integer year) {
      this.year = year;
   }
   public Integer getYear() {
      return year;
   }
   public void setSid(Integer sid) {
      this.sid = sid;
   }
   public Integer getSid() {
      return sid;
   }
}

Di seguito è riportato il contenuto del file StudentMarksMapper.java file

package com.tutorialspoint;

import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;

public class StudentMarksMapper implements RowMapper<StudentMarks> {
   public StudentMarks mapRow(ResultSet rs, int rowNum) throws SQLException {
      StudentMarks studentMarks = new StudentMarks();
      studentMarks.setId(rs.getInt("id"));
      studentMarks.setName(rs.getString("name"));
      studentMarks.setAge(rs.getInt("age"));
      studentMarks.setSid(rs.getInt("sid"));
      studentMarks.setMarks(rs.getInt("marks"));
      studentMarks.setYear(rs.getInt("year"));

      return studentMarks;
   }
}

Di seguito è riportato il file della classe di implementazione StudentJDBCTemplate.java per l'interfaccia DAO definita StudentDAO

package com.tutorialspoint;

import java.util.List;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

public class StudentJDBCTemplate implements StudentDAO {
   private JdbcTemplate jdbcTemplateObject;

   public void setDataSource(DataSource dataSource) {
      this.jdbcTemplateObject = new JdbcTemplate(dataSource);
   }
   public void create(String name, Integer age, Integer marks, Integer year){
      try {
         String SQL1 = "insert into Student (name, age) values (?, ?)";
         jdbcTemplateObject.update( SQL1, name, age);

         // Get the latest student id to be used in Marks table
         String SQL2 = "select max(id) from Student";
         int sid = jdbcTemplateObject.queryForInt( SQL2 );

         String SQL3 = "insert into Marks(sid, marks, year) " + "values (?, ?, ?)";
         jdbcTemplateObject.update( SQL3, sid, marks, year);
         System.out.println("Created Name = " + name + ", Age = " + age);
         
         // to simulate the exception.
         throw new RuntimeException("simulate Error condition") ;
      } 
      catch (DataAccessException e) {
         System.out.println("Error in creating record, rolling back");
         throw e;
      }
   }
   public List<StudentMarks> listStudents() {
      String SQL = "select * from Student, Marks where Student.id = Marks.sid";
      List <StudentMarks> studentMarks = jdbcTemplateObject.query(SQL, 
         new StudentMarksMapper());
      
      return studentMarks;
   }
}

Ora passiamo al file dell'applicazione principale MainApp.java, che è il seguente

package com.tutorialspoint;

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

      StudentDAO studentJDBCTemplate = 
         (StudentDAO)context.getBean("studentJDBCTemplate");
      
      System.out.println("------Records creation--------" );
      studentJDBCTemplate.create("Zara", 11, 99, 2010);
      studentJDBCTemplate.create("Nuha", 20, 97, 2010);
      studentJDBCTemplate.create("Ayan", 25, 100, 2011);

      System.out.println("------Listing all the records--------" );
      List<StudentMarks> studentMarks = studentJDBCTemplate.listStudents();
      
      for (StudentMarks record : studentMarks) {
         System.out.print("ID : " + record.getId() );
         System.out.print(", Name : " + record.getName() );
         System.out.print(", Marks : " + record.getMarks());
         System.out.print(", Year : " + record.getYear());
         System.out.println(", Age : " + record.getAge());
      }
   }
}

Di seguito è riportato il file di configurazione Beans.xml

<?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:tx = "http://www.springframework.org/schema/tx"
   xmlns:aop = "http://www.springframework.org/schema/aop"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

   <!-- Initialization for data source -->
   <bean id="dataSource" 
      class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name = "driverClassName" value = "com.mysql.jdbc.Driver"/>
      <property name = "url" value = "jdbc:mysql://localhost:3306/TEST"/>
      <property name = "username" value = "root"/>
      <property name = "password" value = "cohondob"/>
   </bean>
  
   <tx:advice id = "txAdvice" transaction-manager = "transactionManager">
      <tx:attributes>
      <tx:method name = "create"/>
      </tx:attributes>
   </tx:advice>
	
   <aop:config>
      <aop:pointcut id = "createOperation" 
         expression = "execution(* com.tutorialspoint.StudentJDBCTemplate.create(..))"/>
      
      <aop:advisor advice-ref = "txAdvice" pointcut-ref = "createOperation"/>
   </aop:config>
	
   <!-- Initialization for TransactionManager -->
   <bean id = "transactionManager"
      class = "org.springframework.jdbc.datasource.DataSourceTransactionManager">
      
      <property name = "dataSource" ref = "dataSource" />    
   </bean>

   <!-- Definition for studentJDBCTemplate bean -->
   <bean id = "studentJDBCTemplate"  
      class = "com.tutorialspoint.StudentJDBCTemplate">
      <property name = "dataSource" ref = "dataSource"/>  
   </bean>

</beans>

Una volta terminata la creazione dei file di configurazione dei bean e dei sorgenti, eseguiamo l'applicazione. Se tutto va bene con la tua applicazione, stamperà la seguente eccezione. In questo caso, verrà eseguito il rollback della transazione e non verrà creato alcun record nella tabella del database.

------Records creation--------
Created Name = Zara, Age = 11
Exception in thread "main" java.lang.RuntimeException: simulate Error condition

Puoi provare l'esempio precedente dopo aver rimosso l'eccezione, e in questo caso dovrebbe eseguire il commit della transazione e dovresti vedere un record nel database.