Spring中配合hibernate使用的简单例子
最近在看SPRING和hibernate,学习了spring和hibernate之间整合,下面举出一个例子予以说明.
首先,可以注入的是sessionfactory,因为sessionfactory的Datasource可以用spring注入.比如一个下面的例子,是对对象进行增加的
接口IUserDAO:
publicinterfaceIUserDAO{
publicvoidinsert(Useruser);
}
User.java:
publicclassUser{
privateStringname;
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
}
UserDao.java:
(这里省去了import等东西了)
publicclassUserDAOimplementsIUserDAO{
privateSessionFactorysessionFactory;
publicUserDAO(){
}
publicUserDAO(SessionFactorysessionFactory){
this.setSessionFactory(sessionFactory);
}
//注入sessionFactory
publicvoidsetSessionFactory(
SessionFactorysessionFactory){
this.sessionFactory=sessionFactory;
}
publicvoidinsert(Useruser){
Sessionsession=sessionFactory.openSession();
Transactiontx=session.beginTransaction();
session.save(user);
tx.commit();
session.close();
}
关键的base-config.xml:
<beans>
//基本的datasource,存放实际连接串等东西
<beanid="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<propertyname="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<propertyname="url">
<value>jdbc:mysql://localhost:3306/SpringHibernateDemo</value>
</property>
<propertyname="username">
<value>root</value>
</property>
<propertyname="password">
<value>123456</value>
</property>
</bean>
<beanid="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<propertyname="dataSource">
<refbean="dataSource"/>
</property>
<propertyname="mappingResources">
<list>
<value>liaoo/springhibernatear/User.hbm.xml</value>
</list>
</property>
<propertyname="hibernateProperties">
<props>
<propkey="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
</props>
</property>
</bean><beanid="userDAO"class="liao.springhibernate.UserDAO">
<propertyname="sessionFactory">
<refbean="sessionFactory"/>
</property>
</bean>
可以看到,这里对userDAO类的sessionFactory进行了注入,而参考到其中的bean-config.xml里sessionFactory里实现.可以看到,可以将datasource注入到LocalSessionFactoryBean中.要注意的是org.springframework.orm.hibernate3.LocalSessionFactoryBean是hibernate3整合使用的,org.springframework.orm.hibernate.LocalSessionFactoryBean是hibernate2中使用的.
最后是测试程序
publicstaticvoidmain(String[]args){
ApplicationContextcontext=
newFileSystemXmlApplicationContext(
"beans-config.xml");
IUserDAOuserDAO=(IUserDAO)context.getBean("userDAO");
Useruser=newUser();
user.setName("jackyrong");
userDAO.insert(user);<script type="text/javascript"></script>