Spring framework: Spring and persistence

Source: Internet
Author: User

Spring framework: Spring and persistence

Spring persistence is used to simplify data operations.


Data Source

Data sources can be divided into multiple types: JNDI, connection pool, and JDBC.


The configuration method of JNDI. In this example, Tomcat is used as a Web container. First, add the upper and lower sections of code in context. xml.

 

After restarting Tomcat, you can directly access the data source through the following configuration in the application.

 


Connection Pool configuration. Another method is to use the database connection pool as the data source. Generally, the mainstream connection pool is Apache DBCP. It needs to be configured as follows.

   
    
    
    
    
    
  
 


JDBC configuration.

   
    
    
    
  
 


JDBC Template

Anyone who has written a JDBC program knows that the exception handling part occupies a lot of code. To eliminate the sample code, Spring provides a JDBC template.


The following example shows how to use JdbcTemplate to access data. First, create a global jdbcTemplate for bean configuration.

   
  
 


The following example shows how to Insert a new row of data.

// Anonymous parameter public void addUser (User user) {jdbcTemplate. update ("insert into user (username, password) VALUES (?,?) ", User. getUsername (), user. getPassword ();} // name parameter public void addUser (User user) {Map
 
  
Params = new HashMap
  
   
(); Params. put ("username", user. getUsername (); params. put ("password", user. getPassword (); jdbcTemplate. update ("insert into user (username, password) VALUES (: username,: password)", params );}
  
 


The following example demonstrates how to read data from a database. RowMapper converts a row of data into an object.

public List
 
   getUserList() {    return jdbcTemplate.query(        "SELECT id,username,password FROM user",        new RowMapper
  
   () {            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;            }        }    );}
  
 


Transactions

Transactions in Spring are managed by special classes named TransactionManager. The following bean configuration is required.

   
  
 

After the configuration is complete, you can use transactionManager to execute the transaction. The following is an example of executing a transaction.

public void test() {    transactionTemplate.execute(new TransactionCallback
 
  () {        public Void doInTransaction(TransactionStatus status) {            jdbcTemplate.update("INSERT INTO ...",x,y,z);        }    }}
 

From the code, we can see that transactionTemplate and jdbcTemplate are two common beans, and we didn't tell them the relationship. I cannot help wondering, how does jdbcTemplate know which transactionTemplate is not in the transaction? I checked the source code and came to the conclusion. Each database connection can only open one transaction at a time, so jdbcTemplate only needs to obtain the database connection of transactionTemplate, and the database connection comes with transaction management. When starting a transaction, transactionTemplate puts the current database connection into ThreadLocal in TransactionSynchronizationManager (TSM. When jdbcTemplate obtains the current database connection from TSM, it can submit SQL requests. The transaction is controlled by the database connection. jdbcTemplate does not need to consider the transaction.

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.