Spring database access (oracle) configuration, spring Data Access
Chen kezhao: http://blog.csdn.net/u013474104/article/details/44279309
======================
1. spring's support for database access
When developing the persistence layer, we are faced with a variety of options, such as using JDBC, Hibernate, java persistence API or other Persistence frameworks. Fortunately, spring supports all these persistence mechanisms.
DAO (data access boject) data access object, this name is a good description of the role DAO plays in the application. DAO provides a way to read and write data to the database. They should publish functions as interfaces, and other parts of the application can be accessed through interfaces.
Note: The service object itself does not process data access, but delegates Data Access to DAO. The DAO interface ensures its loose coupling with the service object.
2. Configure the data source
Spring provides multiple methods to configure the data source Bean in the spring context, including:
A. Data sources defined by the JDBC driver;
B. Data Sources searched through JNDI;
C. Data Source of the connection pool;
Next we will talk about how to obtain the connected data source from the connection pool! (Point c)
Code for configuring Bean in context:
<! -- Configure the data source --> <bean id = "dataSource" class = "org. apache. commons. dbcp. basicDataSource "> <property name =" driverClassName "value =" oracle. jdbc. driver. oracleDriver "/> <property name =" url "value =" jdbc: oracle: thin: @ localhost: 1521: orcl "/> <property name =" username "value =" wwo "/> <property name =" password "value =" wwo "/> <! -- Initial value when the connection pool starts --> <property name = "initialSize" value = "3"/> <! -- Maximum value of the connection pool --> <property name = "maxActive" value = "300"/> <! -- Maximum idle value. after a peak time, the connection pool can slowly release a portion of connections that are no longer in use, until maxIdle --> <property name = "maxIdle" value = "2"/> <! -- Minimum idle value. when the number of idle connections is less than the threshold value, the connection pool will pre-apply for some connections, so that you do not have time to apply when the peak traffic arrives --> <property name = "minIdle" value = "1"/> <! -- End --> </bean>
Note: The JDBC driver data source does not have a pool concept, so there is no pool attribute configuration!
Now, we have established a connection to the database through the data source, and the next step is to actually access the database.
3. Integrate Hibernate in Spring
Some Hibernate features:
A. lazy loading: for example, a Bean object consists of its attributes and another Bean object. If we only focus on the attributes of this Bean object, we can use delayed loading, only capture the required data;
B. Pre-Fetch (Eager fetching): This is relative to delayed loading. Other beans associated with a Bean will be queried, which saves the cost of multiple queries;
C. Cascading: Sometimes, after deleting a Bean object, you also want it to delete other beans associated with it in the database.
Spring's support for the Hibernate ORM framework provides integration points with these frameworks and some additional services, as shown below:
A. Spring declarative transaction integration support;
B. Transparent exception handling;
C. Thread-safe, lightweight template class;
D. DAO Support class;
E. manage resources.
4. declare a Session Factory)
The main interface for using Hibernate is org. hibernate. Session. Session provides basic data access functions, such as saving, updating, deleting, and loading objects from the database.
You can use the SessionFactory of Hibernate to obtain the Session object. SessionFactory is mainly responsible for opening, closing, and managing the Hibernate Session.
The Bean configured in the xml context is as follows:
<Bean id = "sessionFactory" class = "org. springframework. orm. hibernate4.LocalSessionFactoryBean "> <property name =" dataSource "ref =" dataSource "/> <property name =" packagesToScan "> <! -- Scan the object directory --> <list> <value> com. blog. entity </value> </list> </property> <property name = "hibernateProperties"> <props> <prop key = "hibernate. dialect "> org. hibernate. dialect. oracle10gDialect </prop> <prop key = "hibernate. show_ SQL "> true </prop> <prop key =" hibernate. format_ SQL "> true </prop> <prop key =" current_session_context_class "> thread </prop> </props> </property> </bean>
5. Create your own basic DAO class
Spring can use the Hibernate template of Spring to ensure that each transaction uses the same session. Since Hibernate can manage itself, it is unnecessary to use the template class. Next, we directly assemble the Hibernate Session into our DAO class.
/*** Basic dao ** @ author ckz ** @ param <T> */public abstract class BaseDAO <T> {private Class <T> baseEntity; protected BaseDao (Class <T> baseEntity) {this. baseEntity = baseEntity;}/*** inject sessionFactory */@ Autowiredprivate SessionFactory sessionFactory;/*** get session *** @ return */protected Session getCurrentSession () {return sessionFactory. getCurrentSession ();}/*** save ** @ param entity * @ throws Exception */public void add (T entity) throws Exception {getCurrentSession (). save (entity);}/*** call the Stored Procedure ** @ param proName * @ return */public CallableStatement citePro (final String proName) {Session session Session = getCurrentSession (); callableStatement proc = session. doReturningWork (new ReturningWork <CallableStatement> () {@ Override public CallableStatement execute (Connection connection) throws SQLException {CallableStatement resultSet = connection. prepareCall (proName); return resultSet;}); return proc;}/*** update ** @ param entity * @ throws Exception */public void update (T entity) throws Exception {getCurrentSession (). update (entity);}/*** save or update ** @ param entity * @ throws Exception */public void saveOrUpdate (T entity) throws Exception {getCurrentSession (). saveOrUpdate (entity);}/*** delete ** @ param entity * @ throws Exception */public void delete (T entity) throws Exception {getCurrentSession (). delete (entity);}/*** get object by id ** @ param Id * @ return */@ SuppressWarnings ("unchecked") public T getById (final Serializable Id) {return (T) getCurrentSession (). get (this. baseEntity, Id );}}
Note:
1. T indicates the generic parameter type. java generic description -- http://blog.csdn.net/u013474264/article/details/44337145;
2.T
-ThusClass
Type of the class for Object Modeling. For example,String.class
IsClass<String>
. If the class to be modeled is unknown, useClass<?>;