Chapter 4 of Spring3 development practices: Support for JDBC and ORM

Source: Internet
Author: User

Introduction
The DAO (Data Access Object) support provided by Spring aims to facilitate the use of different data access technologies in a standard way, such as JDBC, Hibernate, and JDO. It not only allows you to easily switch between these Persistence Technologies, but also frees you from considering handling specific exceptions in various technologies during coding.
Consistent exception levels
Spring provides a convenient way to convert a technology-specific exception, such as SQLException, to its own exception. This exception belongs to the exception level with DataAccessException as the root. These exceptions encapsulate the original exception object, so that there is no risk of losing any error information.
If the interceptor method is used, you must handle HibernateException and JDOException carefully in the application. It is best to delegate convertHibernateAccessException and convertJdoAccessException to SessionFactoryUtils. These methods can convert the corresponding exceptions to exceptions compatible with the exception levels defined in org. springframework. dao.
The same DAO supports abstract classes.
To facilitate the use of various data access technologies in a consistent way, such as JDBC, JDO, and Hibernate, Spring provides an abstract DAO class for you to expand. These abstract classes provide methods for you to obtain data sources and other configuration information related to your current data access technology.
1: JdbcDaoSupport-base class of the JDBC Data Access Object. A DataSource is required and a JdbcTemplate is provided for the subclass.
2: HibernateDaoSupport-base class of the Hibernate Data Access Object. A SessionFactory is required and HibernateTemplate is provided for the subclass. You can also choose to initialize it directly by providing a HibernateTemplate.
3: base class of the JdoDaoSupport-JDO Data Access Object. You need to set a PersistenceManagerFactory and provide a JdoTemplate for the subclass.
4: base class of the JpaDaoSupport-JPA Data Access Object. An EntityManagerFactory is required and JpaTemplate is provided for the subclass.
Introduction
The value of the Spring JDBC abstract framework will be embodied in the following aspects: (Note: after the Spring JDBC abstract framework is used, the application developer only needs to encode the italic bold text .)
1: Specify database connection Parameters
2: Open the database connection
3: declare an SQL statement
4: Pre-compile and execute SQL statements
5: traverse the query results (if needed)
6. process each traversal operation
7. handle any exceptions thrown
8. process transactions.
9. Close the database connection.
Spring will complete all tedious JDBC underlying details processing for us.
The Spring JDBC abstraction framework consists of four packages: core, dataSource, object, and support.
1: The core package consists of the JdbcTemplate class and related callback interfaces and classes.
2: The datasource package consists of some tool classes used to simplify DataSource access and simple implementation of various DataSource interfaces (mainly used for unit testing and JDBC outside the J2EE container.
3: The object package consists of classes that encapsulate queries, updates, and stored procedures. The objects of these classes are thread-safe and reusable. They are similar to JDO. The difference with JDO is that the query results are "disconnected" from the database. These are high-level abstractions of JDBC based on core packages.
4: The support package provides some SQLException conversion classes and Related tool classes.
 
The exception thrown during the JDBC processing will be converted to the exception defined in the org. springframework. dao package. Therefore, Spring JDBC does not need to handle exceptions thrown by JDBC or specific RDBMS. All exceptions are unchecked exceptions, so that we can capture the exceptions passed to the caller.
JdbcTemplate is the core class of the core package. It completes the creation and release of resources for us, thus simplifying the use of JDBC. It also helps us avoid some common errors, such as forgetting to close the database connection.
The interface is defined as follows:

Java code:
View copies to clipboard and print
Public interface Api {
Public boolean create (UserModel um );
}
The definition implementation class is as follows:

Java code:
View copies to clipboard and print
Public class Impl implements Api {
Private DataSource ds = null;
Public void setDs (DataSource ds ){
This. ds = ds;
}
Public boolean create (UserModel um ){
JdbcTemplate jt = new JdbcTemplate (ds );
Jt.exe cute ("insert into tbl_user (uuid, name) values ('" + um. getUuid () + "','" + um. getName () + "')");
Return false;
}
}
Configuration File

Java code:
View copies to clipboard and print
<Bean name = "api" class = "cn. S. Spring3.jdbc. Impl">
<Property name = "ds" ref = "dataSource"> </property>
</Bean>
<Bean name = "dataSource" class = "org. apache. commons. dbcp. BasicDataSource">
<Property name = "driverClassName"> <value> oracle. jdbc. driver. OracleDriver </value> </property>
<Property name = "url"> <value> jdbc: oracle: thin: @ localhost: 1521: orcl </value> </property>
<Property name = "username"> <value> test </value> </property>
<Property name = "password" value = "test"/>
</Bean>
Client

Java code:
View copies to clipboard and print
Public static void main (String [] args) throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext (
New String [] {"applicationContext-jdbc.xml "});
Api api = (Api) context. getBean ("api ");
UserModel um = new UserModel ();
Um. setUuid ("test1 ");
Um. setName ("test1 ");
Api. create (um );
}
If you want to pass parameters to it, you need a callback interface, as shown below:
 

Java code:
View copies to clipboard and print
Public boolean create (UserModel um1 ){
JdbcTemplate jt = new JdbcTemplate (ds );
Final UserModel um = um1;
Class myCallBack implements PreparedStatementCallback {
Public Object doInPreparedStatement (PreparedStatement pstmt)
Throws SQLException, DataAccessException {
Pstmt. setString (1, um. getUuid ());
Pstmt. setString (2, um. getName ());
System. out. println ("dddddddddd ");
Return pstmt.exe cuteUpdate ();
}
}
Jt.exe cute ("insert into tbl_user (uuid, name) values (?,?) ", New myCallBack ());
Return false;
}

 
The NamedParameterJdbcTemplate class supports using named parameters in SQL statements and is suitable for queries. If updated, you also need to use the callback method as follows:

Java code:
View copies to clipboard and print
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate (ds );
Map paramMap = new HashMap ();
ParamMap. put ("uuid", um. getUuid ());
List list = jt. queryForList ("select * from tbl_user where uuid =: uuid", paramMap );
Iterator it = list. iterator ();
While (it. hasNext ()){
Map map = (Map) it. next ();
System. out. println ("uuid =" + map. get ("uuid") + ", name =" + map. get ("name "));
}
The NamedParameterJdbcTemplate class is thread-safe. The best way to use this class is not to instantiate a new NamedParameterJdbcTemplate during each operation, but to configure only one NamedParameterJdbcTemplate instance for each DataSource.
NamedParameterJdbcTemplate can also be used as mapper by itself, as shown below:

Java code:
View copies to clipboard and print
NamedParameterJdbcTemplate jt = new NamedParameterJdbcTemplate (ds );
Map paramMap = new HashMap ();
ParamMap. put ("uuid", um1.getUuid ());
RowMapper mapper = new RowMapper (){
Public Object mapRow (ResultSet rs, int rowNum) throws SQLException {
UserModel um = new UserModel ();
Um. setName (rs. getString ("name "));
Um. setUuid (rs. getString ("uuid "));
Return um;
}
};
List list = jt. query ("select * from tbl_user where uuid =: uuid", paramMap, mapper );
Iterator it = list. iterator ();
While (it. hasNext ()){
UserModel tempUm = (UserModel) it. next ();
System. out. println ("uuid =" + tempUm. getUuid () + ", name =" + tempUm. getName ());
}
SimpleJdbcTemplate class
SimpleJdbcTemplate is a wrapper of the JdbcTemplate class. It utilizes some language features of Java 5, such as Varargs and Autoboxing.
SQLExceptionTranslator Interface
SQLExceptionTranslator is an interface. If you need to convert between SQLException and org. springframework. dao. DataAccessException, you must implement this interface.
The implementation of the converter class can adopt common practices (for example, the SQLState code of JDBC). To make the conversion more accurate, you can also customize it (for example, the error code of Oracle ).
SQLErrorCodeSQLExceptionTranslator is the default Implementation of SQLExceptionTranslator. This implementation uses the error code of the specified database vendor, which is more accurate than SQLState.
DataSourceUtils class
DataSourceUtils is a help class that provides easy-to-use and powerful database access capabilities. You can use the static methods provided by this class to obtain database connections from JNDI and disable them when necessary.
It is best to obtain the JDBC connection from the DataSourceUtils class when using standard JDBC but Spring transactions.
SmartDataSource Interface
SmartDataSource is an extension of the DataSource interface to provide database connections. The class using this interface can check whether the connection needs to be closed after the specified operation.
 
AbstractDataSource class
It implements some irrelevant methods of the DataSource interface. If you need to implement your own DataSource, it is a good idea to inherit this class.
SingleConnectionDataSource class
Is an implementation of the SmartDataSource interface, which encapsulates a single connection internally. The connection will not be closed after it is used. Obviously, it cannot be used in a multi-threaded environment.
Introduction
Spring provides integration with JDO, JPA, Hibernate, TopLink, and iBATIS in terms of resource management, DAO implementation support, and transaction policies. Taking Hibernate as an example, Spring provides first-class support by using many convenient features of IoC, helping you deal with many typical Hibernate integration problems. All such support follows the general transaction and DAO exception system of Spring. Generally, there are two different integration styles: You can use the DAO template provided by Spring, or directly use the native API of tools such as Hibernate, JDO, and TopLink to write DAO. Regardless of the style, these DAO can be configured through IoC and involved in Spring resource and transaction management.
Benefits of using Spring to build your O/R Mapping DAO include:
1: simple test
2: exception Encapsulation
3: General Resource Management
4: Integrated Transaction Management
5: avoid binding specific technologies to allow mix-and-match implementation policies
Create SessionFactory in Spring application context as follows:

Java code:
View copies to clipboard and print
<Bean id = "hbConfig"
Class = "org. springframework. orm. hibernate3.LocalSessionFactoryBean">
<Property name = "dataSource"> <ref local = "dataSource"/> </property>
<Property name = "mappingResources">
<List>
<Value> com/lx/Parent. hbm. xml </value>
</List>
</Property>
<Property name = "hibernateProperties">
<Props>
<Prop key = "hibernate. dialect">
Org. hibernate. dialect. Oracle9Dialect
</Prop>
<Prop key = "hibernate. show_ SQL"> true </prop>
</Props>
</Property>
</Bean>
The interface is defined as follows:

Java code:
View copies to clipboard and print
Public interface Api {
Public boolean create (UserModel um );
}
The implementation class is as follows:

Java code:
View copies to clipboard and print
Public class Impl implements Api {
Private SessionFactory sf = null;
Public void setSf (SessionFactory sf ){
This. sf = sf;
}
Public boolean create (UserModel um ){
HibernateTemplate ht = new HibernateTemplate (sf );
Ht. save (um );
Return false;
}
}
The configuration file is as follows:

Java code:
View copies to clipboard and print
<Bean name = "api" class = "cn. S. Spring3.h3. Impl">
<Property name = "sf" ref = "hbConfig"> </property>
</Bean>
<Bean id = "dataSource" class = "org. apache. commons. dbcp. BasicDataSource">
<Property name = "driverClassName">
<Value> oracle. jdbc. driver. OracleDriver </value>
</Property>
<Property name = "url">
<Value> jdbc: oracle: thin: @ localhost: 1521: orcl </value>
</Property>
<Property name = "username"> <value> test </value> </property>
<Property name = "password" value = "test"/>
</Bean>
The configuration file is as follows:

Java code:
View copies to clipboard and print
<Bean id = "hbConfig" class = "org. springframework. orm. hibernate3.LocalSessionFactoryBean">
<Property name = "dataSource"> <ref local = "dataSource"/> </property>
<Property name = "mappingResources">
<List> <value> cn/S/Spring3/h3/UserModel. hbm. xml </value>
</List>
</Property>
<Property name = "hibernateProperties">
<Props>
<Prop key = "hibernate. dialect">
Org. hibernate. dialect. Oracle8iDialect
</Prop>
<Prop key = "hibernate. show_ SQL"> true </prop>
</Props>
</Property>
</Bean>
The client file is as follows:

Java code:
View copies to clipboard and print
Public static void main (String [] args) throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext (
New String [] {"applicationContext-h3.xml "});
Api api = (Api) context. getBean ("api ");
UserModel um = new UserModel ();
Um. setUuid ("test1 ");
Um. setName ("test1 ");
Api. create (um );
}
In the previous demonstration, the update operation is used. How can this problem be solved? As follows:

Java code:
View copies to clipboard and print
List <UserModel> list = ht. find ("select o from UserModel o ");
How do I input parameters? As follows:

Java code:
View copies to clipboard and print
Object params [] = new Object [1];
Params [0] = "test1 ";
List <UserModel> list = ht. find ("select o from UserModel o where o. uuid =? ", Params );
How do I input a name parameter? As follows:

Java code:
View copies to clipboard and print
Object params [] = new Object [1];
Params [0] = "test1 ";
String names [] = new String [1];
Names [0] = "uuid ";
List <UserModel> list = ht. findByNamedParam ("select o from UserModel o where o. uuid =: uuid", names, params );
What should I do if I need to use the Hibernate Query interface? As follows:

Java code:
View copies to clipboard and print
HibernateCallback hcb = new HibernateCallback (){
Public Object doInHibernate (Session session) throws HibernateException, SQLException {
Query q = session. createQuery ("select o from UserModel o where o. uuid =: uuid ");
Q. setString ("uuid", um. getUuid ());
Return q. list (); www.2cto.com
}
};
Collection <UserModel> list = (Collection <UserModel> cmdht.exe cute (hcb );
One callback can be effectively used in any Hibernate data access. HibernateTemplate ensures that the current Hibernate Session object is correctly opened and closed, and is directly involved in transaction management. A Template instance is thread-safe and reusable. Therefore, they can be held as instance variables of external objects.
The implementation class is changed to the following:

Java code:
View copies to clipboard and print
Public class Impl extends HibernateDaoSupport implements Api {
Public Collection testQuery (){
List <UserModel> list = this. getHibernateTemplate (). find ("select o from UserModel o ");
For (UserModel tempUm: list ){
System. out. println ("uuid =" + tempUm. getUuid () + ", name =" + tempUm. getName ());
}
Return list;
}
}
The configuration file is changed to the following:

Java code:
View copies to clipboard and print
<Bean name = "api" class = "cn. S. Spring3.h3. Impl">
<Property name = "sessionFactory" ref = "hbConfig"> </property>
</Bean>
What should I do if I want to use Session? As follows:

Java code:
View copies to clipboard and print
Session session = getSession (getSessionFactory (), false );
Generally, a false parameter (indicating whether to allow creation) is passed to the getSession (...) method for calling. At this point, the entire call will be completed in the same transaction (its entire lifecycle is controlled by the transaction, avoiding the need to close the returned Session ).
Author: jinnianshilongnian

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.