SPRING4 Integrated Hibernate3 Basic use (by injecting sessionfactory)
- SPRING4 integrated Hibernate3 Basic use by injecting sessionfactory
- Step 1 Import Maven dependencies
- Step 2 Writing the beans core configuration file
- Step 3 Writing the entity class
- Step 4 Writing the Hibernate-based DAO layer
- Step 5 Writing test methods
- Further study
Step 1: Import Maven dependencies
1, the Spring4 module
Spring-core, Spring-context, Spring-beans, Spring-jdbc, Spring-orm, Spring-tx, spring-test
Specific MAVEN configuration, can go to maven repository:search/browse/explore http://mvnrepository.com/query, here in order to save space is not pasted out.
2. mysql Driver
Mysql-connector-java
3, Hibernate3
In this section we integrate Hibernate3, and we'll show you how to integrate Hibernate4 in a future article.
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>3.6.10.Final</version></dependency>
4. Druid Data source
Druid
5, Javassist
This is Hibernate's dependency package.
<dependency> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> <version>3.20.0-GA</version></dependency>
6, Aspectjweaver
(Spring AOP dependency)
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.7</version></dependency>
Step 2: Write the beans core configuration file
0. Basic Configuration
<context:component-scan base-package="com.liwei.dao"/>
1. Configure the data source
<beanID="DataSource" class="Com.alibaba.druid.pool.DruidDataSource"Destroy-method="Close"> < Property name="username"Value="Root"></ Property> < Property name="Password"Value="123456"></ Property> < Property name="url"Value="Jdbc:mysql://127.0.0.1:3306/spring_hibernate"></ Property> < Property name="Driverclassname"Value="Com.mysql.jdbc.Driver"></ Property> </bean>
2, Configuration Sessionfactory
Create a Spring SessionFactory
factory, if you are using the Annotation method, you cannot use it LocalSessionFactoryBean
, and you should use it org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
.
<beanID="Sessionfactory" class="Org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> < Property name="DataSource" ref="DataSource"></ Property> < Property name="Packagestoscan"> <value>com.liwei.model</value> </ Property> < Property name="Hibernateproperties"> <props> <propkey="Hibernate.dialect">org.hibernate.dialect.mysqldialect</prop> <propkey="Hibernate.show_sql">true</prop> <propkey="Hibernate.hbm2ddl.auto">update</prop> <propkey="Hibernate.format_sql">false</prop> </props> </ Property></bean>
Note: The classes we use to integrate Hibernate3 are org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
.
3. Configuration and transaction related
Spring transactions are configured so that spring can effectively manage transactions only after the transaction has been configured .
(1) Configuring the transaction manager
Note: Note that there are different transaction managers to choose from depending on the persistence framework.
id="txManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <propertyname="sessionFactory"ref="sessionFactory"/></bean>
(2) Configuring transaction notifications
<!--configuring AOP, Spring is transaction management through AOP--<aop:config> <!--setting PointCut indicates which methods to add to the transaction -- <aop:pointcut id="Allmethods" expression="Execution (* Com.liwei.dao.*.* (..)) " /> <!--Use the advisor to determine the specific way to add transaction control-- <aop:advisor advice-ref="Txadvice" pointcut-ref="Allmethods" /></aop:config><!--Configure which methods to join transaction control --<tx:advice id="Txadvice" transaction-manager="Txmanager"> <tx:attributes> <!--Let all the methods join the transaction management- <tx:method name="*" propagation="REQUIRED"/> </tx:attributes></tx:advice>
Step 3: Write the entity class
Add Hibernate Annotation or HBM files to the entity class.
and add standardized JPA annotations.
Table (name ="T_group")@Entity Public class Group { PrivateInteger ID;PrivateString name;@GeneratedValue @Id PublicIntegergetId() {returnId } Public void setId(Integer ID) { This. id = ID; } PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; }}
Step 4: Write the Hibernate-based DAO layer
Note: The Hibernate3 persistence operation here is done by dependency injection SessionFactory
. So we have to rely on the injection in each DAO layer SessionFactory
, through SessionFactory
the getCurrentSession()
method to complete the operation of the entity class.
That is, 1, in the corresponding DAO injected corresponding SessionFactory
(supplementary instructions SessionFactory
are many, according to the integrated persistence framework and version of the decision);
2, if through spring to manage the corresponding SessionFactory
, no longer use the open factory.openSession()
session, but should be used to open the session with Facotry.getcurrentsession, this session will be managed by spring, this Developers do not have to do transaction control, and do not close the Session, all by the Spring container to complete.
Our problem: All the DAO layer classes have to rely on injection SessionFactory
, then get the Session, repeat the code too much.
Solution: Write a base class for the DAO layer, and all the DAO layer classes inherit this base class.
@Repository (value="Grouphibernatedao") Public classGrouphibernatedao {PrivateSessionfactory sessionfactory; PublicSessionfactorygetsessionfactory() {returnSessionfactory; } @Autowired Public void setsessionfactory(Sessionfactory sessionfactory) { This. sessionfactory = Sessionfactory; } PublicSessiongetsession(){returnSessionfactory.getcurrentsession (); } Public void Groupadd(GroupGroup) {getsession (). Save (Group); System. out. println (Group. GetId ()); }}
Step 5: Write the test method:
@RunWith (Springjunit4classrunner.class) @ContextConfiguration (value= {"Classpath:beans.xml"}) Public classhibernatespringtest {@AutowiredPrivateGrouphibernatedao Grouphibernatedao; @Test Public void Testadd() {GroupGroup=NewGroup ();Group. SetName ("Technology Research and Development Department"); Grouphibernatedao.groupadd (Group); User User =NewUser ("Liwei","123456","Lee Weiwei"); User.setgroup (Group); Userhibernatedao.add (user); }}
Further study
We need to abstract the DAO layer into an interface so that we can add different implementations.
public Interface Igroupdao {public void add (Group group ); public Group load (int ID);}
publicinterface IUserDao { publicvoidadd(User user); publicvoidupdate(User user); publicvoiddelete(User user); publicload(int id); publiclistparams);}
At this point the declaration portion of the implementation class becomes:
@Repository(value="groupHibernateDao")publicclass GroupHibernateDao implements IGroupDao{
@Repositorypublicclass UserHibernateDao implements IUserDao{
Above we point out that each of the DAO layers is injected SessionFactory
, and we can write a base class to BaseDao
complete the dependency injection.
public Class Basedao {private sessionfactory sessionfactory; public Sessionfactory getsessionfactory () {return sess Ionfactory; } @Autowired public void setsessionfactory (sessionfactory sessionfactory) {this . Sessionfactory = sessionfactory; } //get Session, note: opensession () is not used, use getcurrentsession () to be managed by Spring public Session getsession () {return sessionfactory.getcurrentsession (); }}
At this point the declaration portion of the implementation class becomes:
@Repository(value="groupHibernateDao")publicclass GroupHibernateDao extends BaseDao implements IGroupDao{
@Repositorypublicclass UserHibernateDao extends BaseDao implements IUserDao{
The source code can be downloaded in the following URL:
Weimingge14/spring4integrationhibernate3: Basic configuration using SPRING4 integrated Hibernate3 https://github.com/weimingge14/ Spring4integrationhibernate3
SPRING4 Integrated Hibernate3 Basic use (by injecting sessionfactory)