Programmatic Transactions of Spring (14)

Source: Internet
Author: User
Tags tutorialspoint

Spring-Programmed Transaction management

The programmatic transaction management approach allows you to manage transactions with the help of programming your source code. This gives you a great deal of flexibility, but it's hard to maintain.

Before we get started, there are at least two database tables, and with the help of the transaction we can perform a variety of CRUD operations.

One, prepare two sheets

CREATE TABLE Student (   ID   INT not null auto_increment,   NAME VARCHAR () is not NULL, age  INT not NULL,   PRIMARY KEY (ID)); CREATE TABLE Marks (   SID int not null,   Marks  int NOT NULL, year INT NOT null   );

Ii. Preparation of Studentmarks

 PackageCom.tutorialspoint; Public classStudentmarks {PrivateInteger age; PrivateString name; PrivateInteger ID; PrivateInteger marks; PrivateInteger Year; PrivateInteger SID;  Public voidsetage (Integer age) { This. Age =Age ; }    PublicInteger getage () {returnAge ; }    Public voidsetName (String name) { This. Name =name; }    PublicString GetName () {returnname; }    Public voidsetId (Integer id) { This. ID =ID; }    PublicInteger getId () {returnID; }    Public voidSetmarks (Integer marks) { This. Marks =marks; }    PublicInteger Getmarks () {returnmarks; }    Public voidSetyear (Integer year) { This. Year =Year ; }    PublicInteger getYear () {returnYear ; }    Public voidSetsid (Integer sid) { This. Sid =SID; }    PublicInteger GetSID () {returnSID; }}

Iii. Preparation of Studentdao

 PackageCom.tutorialspoint;Importjava.util.List;ImportJavax.sql.DataSource; Public InterfaceStudentdao {/*** This was the method to being used to initialize * database resources ie. connection. */    Public voidSetdatasource (DataSource DS); /*** This was the method to being used to create * A record in the Student and Marks tables. */    Public voidCreate (String name, Integer age, Integer marks, integer year); /*** This was the method to being used to list down * All the records from the Student and Marks tables. */    PublicList<studentmarks>liststudents ();}

Iv. Preparation of Studentmapper.java

 PackageCom.tutorialspoint;ImportJava.sql.ResultSet;Importjava.sql.SQLException;ImportOrg.springframework.jdbc.core.RowMapper; Public classStudentmapperImplementsRowmapper<student> {    PublicStudent Maprow (ResultSet RS,intRowNum)throwsSQLException {Student Student=NewStudent (); Student.setid (Rs.getint ("id")); Student.setname (Rs.getstring ("Name")); Student.setage (Rs.getint ("Age")); returnstudent; }}

V. Preparation of Studentjdbctemplate.java

 PackageCom.tutorialspoint;Importjava.util.List;ImportJavax.sql.DataSource;Importorg.springframework.dao.DataAccessException;Importorg.springframework.jdbc.core.JdbcTemplate;ImportOrg.springframework.transaction.PlatformTransactionManager;Importorg.springframework.transaction.TransactionDefinition;ImportOrg.springframework.transaction.TransactionStatus;Importorg.springframework.transaction.support.DefaultTransactionDefinition; Public classStudentjdbctemplateImplementsStudentdao {PrivateDataSource DataSource; PrivateJdbcTemplate Jdbctemplateobject; PrivatePlatformtransactionmanager TransactionManager;  Public voidSetdatasource (DataSource DataSource) { This. DataSource =DataSource;  This. Jdbctemplateobject =NewJdbcTemplate (DataSource); }    Public voidSettransactionmanager (Platformtransactionmanager transactionmanager) { This. TransactionManager =TransactionManager; }    Public voidCreate (String name, Integer age, Integer marks, integer year) {transactiondefinition def=Newdefaulttransactiondefinition (); Transactionstatus Status=transactionmanager.gettransaction (def); Try{String SQL1= "INSERT into Student (name, age) VALUES (?,?)";         Jdbctemplateobject.update (SQL1, name, age); //Get The latest student ID to being used in Marks tableString SQL2 = "SELECT Max (ID) from Student"; intSid =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 );      Transactionmanager.commit (status); } Catch(DataAccessException e) {System.out.println ("Error in creating record, rolling back");         Transactionmanager.rollback (status); Throwe; }      return; }    PublicList<studentmarks>liststudents () {String SQL= "SELECT * from Student, Marks where Student.id=marks.sid"; List<StudentMarks> Studentmarks =jdbctemplateobject.query (SQL,NewStudentmarksmapper ()); returnStudentmarks; }}

Vi. Preparation of Mainapp.java

 PackageCom.tutorialspoint;Importjava.util.List;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;Importcom.tutorialspoint.StudentJDBCTemplate; Public classMainapp { Public Static voidMain (string[] args) {ApplicationContext context=NewClasspathxmlapplicationcontext ("Beans.xml"); Studentjdbctemplate studentjdbctemplate=(studentjdbctemplate) 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 ()); }   }}

Vii. Preparation of 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"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd "><!--initialization forData 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 N Ame= "username" value= "root"/> <property name= "password" value= "1234"/> </bean> <!--Initializat Ion forTransactionManager--<bean id= "TransactionManager"class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager" > <property name= "DataSource" ref= " DataSource "/> </bean> <!--Definition forStudentjdbctemplate Beans--<bean id= "Studentjdbctemplate"class= "Com.tutorialspoint.StudentJDBCTemplate" > <property name= "dataSource" ref= "DataSource"/> <propert Y name= "TransactionManager" ref= "TransactionManager"/> </bean></beans>

Eight, run Mainapp.java

Results:

Usually the situation does not error, it means that there is no problem.

Programmatic Transactions of Spring (14)

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.