Spring Framework: Spring and persistence

Source: Internet
Author: User

The persistence of spring is used to simplify the operation of the data.


Data source

There are several types of data sources: JNDI, Connection pool, JDBC.


The configuration method for Jndi. The example uses Tomcat as the Web container. First, add the following code to the context.xml.

<resource name= "Jdbc/testdb" auth= "Container" type= "Javax.sql.DataSource" maxactive= "" "maxidle="               30 " Maxwait= "10000"               username= "Javauser" password= "Javadude" driverclassname= "Com.mysql.jdbc.Driver" url= "               Jdbc:mysql://localhost:3306/javatest "/>

After you restart Tomcat, you can access the data source directly from the following configuration in your app.

<jee:jndi-lookup id= "DataSource" jndi-name= "/jdbc/testdb" resource-ref= "true"/>


Connection pool configuration. Another way is to use a database connection pool as the data source. The general mainstream connection pool is Apache DBCP. It needs to be configured as follows.

<bean id= "DataSource" class= "Org.apache.commons.dbcp.BasicDataSource" >  <property name= " Driverclassname "value=" Com.mysql.jdbc.Driver "/>  <property name=" url "value=" Jdbc:mysql://localhost : 3306/javatest "/>  <property name=" username "value=" root "/>  <property name=" password "value=" 123456 "/>  <property name=" InitialSize "value=" 5 "/>  <property name=" maxactive "value="/> " </bean>


JDBC Configuration.

<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/javatest "/>  <property name=" username "value=" test "/>  <property name=" password "Value=" Test "/></bean>


JDBC Templates

Everyone who has written the JDBC program knows that the exception handling section occupies a lot of code. To eliminate these boilerplate code, Spring provides a JDBC template.


The following example shows how to access data using JdbcTemplate. The first is the bean configuration, which creates a global jdbctemplate.

<bean id= "JdbcTemplate" class= "org.springframework.jdbc.core.JdbcTemplate" >  <constructor-arg ref= " DataSource "/></bean>


The following example shows the process of inserting a new row of data.

Anonymous parameter public void AddUser (user user) {    jdbctemplate.update ("INSERT into User (Username,password) VALUES (?,?)",        user.getusername (),        User.getpassword ());} Named parameter public void AddUser (user user) {    map<string, object> params = new hashmap<string, object> ();    Params.put ("username", user.getusername ());    Params.put ("Password", User.getpassword ());    Jdbctemplate.update ("INSERT into User (Username,password) VALUES (: username,:p assword)", params);}


The following example shows the process of reading data from a database. Where RowMapper's role is to convert a row of data into an object.

Public list<user> getuserlist () {    return jdbctemplate.query (        "Select Id,username,password from User",        New Rowmapper<user> () {Public            user Maprow (ResultSet rs, int rowNum) throws SQLException {                User user = New User ();                User.setid (Rs.getint (1));                User.setusername (rs.getnstring (2));                User.setpassword (Rs.getnstring (3));                return user;}}    );


Transaction

The transaction in spring is managed by a specialized class named TransactionManager. The following bean configurations are required.

<bean id= "TransactionManager" class= "Org.springframework.jdbc.datasource.DataSourceTransactionManager" >  <property name= "DataSource" ref= "DataSource"/></bean>

After the configuration is complete, the transaction can be executed using TransactionManager. The following is an example of executing a transaction.

public void Test () {    transactiontemplate.execute (new transactioncallback<void> () {public        void Dointransaction (transactionstatus status) {            jdbctemplate.update ("INSERT into ...", X, Y, z);}}    

From the code you can see that transactiontemplate and JdbcTemplate are two ordinary beans, and we don't tell them the connection. That begs to ask, jdbctemplate how to know in not in the transaction, in which transactiontemplate? I came to the conclusion after reviewing the source code. Each database connection can only open one transaction at a time, so jdbctemplate only gets the database connection to Transactiontemplate, and the database connection comes with transaction management. Transactiontemplate the current database connection into the threadlocal in Transactionsynchronizationmanager (TSM) when the transaction is started. JdbcTemplate gets the current database connection from TSM, submits the SQL request, the transaction is controlled by the database connection, and JdbcTemplate does not need to consider the transaction.

Spring Framework: Spring and persistence

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.