Spring Access Database (Oracle) configuration

Source: Internet
Author: User

Chen Kozhan: http://blog.csdn.net/u013474104/article/details/44279309

================

1.spring Support for database access

When we develop a persistence layer, we face a variety of options, such as using JDBC, Hibernate, the Java Persistence API, or other persistence frameworks. Fortunately, Spring is able to support all of these persistence mechanisms.

DAO (data Access Boject) is a name that describes the role that DAO plays in the application. DAO provides a way for data to be read, written to the database. They should publish the functionality as an interface, and the rest of the application can be accessed through the interface.

Note: The service object itself does not handle data access, but instead delegates data access to DAO. The DAO interface ensures that it is loosely coupled to the service object.

2. Configure the data source

Spring provides several ways to configure the data source Bean in the spring context, including:

A. Data sources defined through the JDBC driver;

B. Data sources that are found through Jndi;

C. The data source of the connection pool;

And then we'll talk about the data source that gets the connection from using the connection pool! (i.e. C point)

The code for the context configuration bean:

<!--Configuring 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 of connection pool startup--><property name= "InitialSize" value= "3"/><!--connection pool maximum--><property name= " Maxactive "value="/><!--maximum idle value. After a peak time, the connection pool can slowly release a portion of the connection that has not been used, and has been reduced to maxidle until--><property name = "Maxidle" value= "2"/><!--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 time to apply for--><property name= "Minidle" Value= "1"/><!--end--></bean>
Note: The JDBC-driven data source does not have a pool concept, so there is no configuration for pool properties!
Well, at this point, we've completed the connection to the database through the data source, and the next step is to actually access the database.

3. Integrating hibernate in spring

Hibernate some features:

A. Lazy loading: For example, a Bean object is composed of its properties and another bean object, if we only focus on the properties of this bean object, then we can rely on lazy loading, only fetch the required data;

B. Pre-fetch (Eager fetching): This is relative to lazy loading, and the other beans associated with a bean will be queried, which saves the cost of multiple queries;

C. Cascade (cascading): Sometimes after you delete a Bean object, you also want it to be able to delete other beans associated with it in the database at the same time.

Spring's support for Hibernate ORM frameworks provides integration points with these frameworks as well as some additional services, as follows:

A.spring Integrated support for declarative transactions;

B. Transparent exception handling;

C. Thread-safe, lightweight template classes;

D.dao support class;

E. Resource management.

4. Declaring the session factory (session Factory)

The primary interface for using Hibernate is org.hibernate.Session. Session provides basic data access capabilities, such as saving, updating, deleting, and loading objects from a database.

With the help of Hibernate sessionfactory to get the session object,Sessionfactory is mainly responsible for opening, closing and managing hibernate session.

The beans configured in the XML context are as follows:

<bean id= "Sessionfactory" class= "Org.springframework.orm.hibernate4.LocalSessionFactoryBean" ><property Name= "DataSource" ref= "DataSource"/><property name= "Packagestoscan" ><!--Scan the entity 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 base DAO class

Spring can use the spring Hibernate template to ensure that each transaction uses the same session. Since Hibernate is able to manage itself, it is not necessary to use a template class. We then assemble the hibernate session directly into our own DAO class.

/** * Basic DAO * * @author ckz * * @param <T> */public abstract class Basedao<t> {private class<t> Baseen tity;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 (ENT ity);} /** * Call Stored procedure * * @param proname * @return */public callablestatement citepro (final String Proname) {Session session = GetC Urrentsession ();                    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 (). Updat E (entity);} /** * Save or UPDATE * * @param entity * @throws Exception */public void saveorupdate (T entity) throws Exception {Getcurrentsessio N (). Saveorupdate (entity);} /** * Delete * * @param entity * @throws Exception */public void Delete (T entity) throws Exception {getcurrentsession (). delet E (entity);} /** * Gets the object by ID * * @param ID * @return */@SuppressWarnings ("unchecked") public T getById (final Serializable Id) {return (T ) getcurrentsession (). Get (This.baseentity, Id);}}


Note: t represents a generic type of parameter, Java generics brief--http://blog.csdn.net/u013474104/article/details/44337145


Spring Access Database (Oracle) configuration

Related Article

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.