Explore Spring Technology Insider (eight): Spring +JDBC Portfolio development and transaction control

Source: Internet
Author: User
Tags aop connection pooling

I. Configuring the data source

 <bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" destroy-method= "Close" > <property Name= "Driverclassname" value= "Org.gjt.mm.mysql.Driver"/> <property name= "url" value= "Jdbc:mysql://localhost : 3306/itcast?useunicode=true&characterencoding=utf-8 "/> <property name=" username "value=" root "/> < Property name= "Password" value= "123456"/> <!--initial value when connection pooling starts--<property name= "InitialSize" value= "1"/>    ; <!--The maximum value of the connection pool--<property name= "maxactive" value= "$"/> <!--maximum idle value. After a peak time, the connection pool can slowly release a connection that has not been used section, has been reduced to maxidle and <property name= "Maxidle" value= "2"/> <!--minimum idle value. When the number of idle connections is less than the threshold, the connection pool will pre-request some connections to avoid flooding Too late to apply--<property name= "Minidle" value= "1"/> </bean> 


Use < Context:property -placeholderlocation= " jdbc.properties "/> Property Placeholder

<context :p roperty-placeholder location= "jdbc.properties"/> <bean id= "DataSource" class= " Org.apache.commons.dbcp.BasicDataSource "destroy-method=" Close "> <property name=" driverclassname "value=" ${ Driverclassname} "/> <property name=" url "value=" ${url} "/> <property name=" username "value=" ${username} "/ > <property name= "password" value= "${password}"/> <!--initial value when connection pooling starts--<property name= "Initialsi Ze "value=" ${initialsize} "/> <!--connection Pool max--<property name=" maxactive "value=" ${maxactive} "/> &L t;! --Maximum idle value. After a peak time, the connection pool can slowly release a portion of the connection that has not been used, until it has been reduced to maxidle-<property name= "Maxidle" value= "${maxidle}"/ > <!--minimum idle value. When the number of idle connections is less than the threshold, the connection pool will pre-apply for some connections, lest the flood peak come too late to apply--<property name= "Minidle" value= "${minidle}"/> ; </bean> 
jdbc.properties

driverclassname=org.gjt.mm.mysql.driverurl=jdbc\:mysql\://localhost\:3306/itcast?useunicode\=true& Characterencoding\=utf-8username=rootpassword=123456initialsize=1maxactive=500maxidle=2minidle=1


Two. Configure Transactions

[Annotation Configuration]

<bean id= "Txmanager" class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager" >  < Property Name= "DataSource" ref= "DataSource"/></bean><!– use transaction @transactional using--><TX annotations  : Annotation-driven transaction-manager= "Txmanager"/> @Service @Transactionalpublic class Personservicebean Implements Personservice {}

[XML Configuration]

<bean id= "Txmanager" class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager" >  < Property Name= "DataSource" ref= "DataSource"/></bean><aop:config>  <aop:pointcut id= " Transactionpointcut "expression=" Execution (* com.zdp.service). *.*(..))" />  <aop:advisor advice-ref= "Txadvice" pointcut-ref= "Transactionpointcut"/></aop:config> <tx : Advice id= "Txadvice" transaction-manager= "Txmanager" ><tx:attributes>    <tx:method name= "get*" Read-only= "true" propagation= "not_supported"/>  <!--query do not set transaction--    <tx:method name= "*"/></ Tx:attributes></tx:advice>


Three. Transaction propagation Properties

REQUIRED: The business method needs to run in a transaction. If the method is running and is already in a transaction, join the transaction, or create a new transaction for yourself.
Not_supported: Declaring a method does not require a transaction. If the method is not associated to a transaction, the container does not open the transaction for it. If the method is called in a transaction, the transaction is suspended and the original transaction resumes execution after the method call ends.
RequiresNew: property indicates that the business method always initiates a new transaction for itself, regardless of whether there is a transaction. If the method is already running in a transaction, the original transaction is suspended, the new transaction is created, and the new transaction is completed until the method executes, and the original transaction resumes execution.
MANDATORY: This property specifies that the business method can only be executed in a transaction that already exists, and the business method cannot initiate its own transaction. If the business method is called in an environment without transactions, the container throws an exception.
SUPPORTS: This transaction property indicates that if a business method is called within a transaction scope, the method becomes part of the transaction. If the business method is called outside the scope of the transaction, the method executes in an environment without transactions.
Never: Specifies that the business method must never be executed within the scope of the transaction. If the business method executes in a transaction, the container throws an exception, and only the business method is not associated to any transaction for normal execution.
NESTED: If an active transaction exists, it is run in a nested transaction. If there is no active transaction, it is performed by the required property. It uses a separate transaction that has multiple savepoint that can be rolled back. The rollback of internal transactions does not affect external transactions. It only works with the Datasourcetransactionmanager transaction manager


Four. Using JdbcTemplate

1. A practical example:

public class Personserviceimpl implements Personservice {private jdbctemplate jdbctemplate;public void Setdatasource ( DataSource DataSource) {this.jdbctemplate = new JdbcTemplate (DataSource);}             Delete a user record public void Delete (Integer PersonID) throws Exception {jdbctemplate.update ("Delete from person where id=?",  New object[] {PersonID}, new int[] {Java.sql.Types.INTEGER});} Query for a user record public person Getperson (Integer PersonID) {return (people) jdbctemplate.queryforobject ("SELECT * FROM-person W Here id=? ', new object[] {PersonID},new int[] {Java.sql.Types.INTEGER}, new Personrowmapper () {public Object Maprow (Re Sultset RS, int index) throws SQLException {person person = new Person (rs.getstring ("name"));p Erson.setid (rs.getint ("id" ); return person;}}); Querying multiple user records @suppresswarnings ("unchecked") public list<person> getpersons () {return (list<person>) Jdbctemplate.query ("Select * from", new Personrowmapper () {public Object Maprow (ResultSet rs, int Index) throws SQLException {person person = new Person (rs.getstring ("name"));p Erson.setid (rs.getint ("id")); return Person;}}); Insert a user record public void save (person person) {jdbctemplate.update (' INSERT into person (name) values (?) ', New OBJ Ect[] {person.getname ()}, new int[] {Java.sql.Types.VARCHAR});} Update a user record public void update (person person) {jdbctemplate.update ("Update Name="?  Where id=? ", new object[] {person.getname (), Person.getid ()}, new int[] {Java.sql.Types.VARCHAR, Java.sql.Types.INTEGER});}}


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.