在context中定义DataSource,创建SessionFactoy,设置参数;
DAO类继承HibernateDaoSupport,实现具体接口,从中获得HibernateTemplate进行具体操作。
在使用中如果遇到OpenSessionInView的问题,可以添加OpenSessionInViewFilter或OpenSessionInViewInterceptor
最近在看SPRING和hibernate,学习了spring和hibernate之间整合,下面举出一个例子予以说明.
首先,可以注入的是sessionfactory,因为sessionfactory的Datasource可以用spring注入.比如一个下面的例子,是对对象进行增加的
接口IUserDAO:
public interface IUserDAO {
public void insert(User user);
}
User.java:
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
UserDao.java:
(这里省去了import等东西了)
public class UserDAO implements IUserDAO {
private SessionFactory sessionFactory;
public UserDAO() {
}
public UserDAO(SessionFactory sessionFactory) {
this.setSessionFactory(sessionFactory);
}
//注入sessionFactory
public void setSessionFactory(
SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void insert(User user) {
Session session = sessionFactory.openSession();
Transaction tx= session.beginTransaction();
session.save(user);
tx.commit();
session.close();
}
//基本的datasource,存放实际连接串等东西
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/SpringHibernateDemo</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>123456</value>
</property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" >
<property name="dataSource">
<ref bean="dataSource"/>
</property>
<property name="mappingResources">
<list>
<value>liaoo/springhibernatear/User.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
</props>
</property>
</bean>
<bean id="userDAO" class="liao.springhibernate.UserDAO">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
可以看到,这里对userDAO类的sessionFactory进行了注入,而参考到其中的bean-config.xml里sessionFactory里实现.可以看到,可以将datasource注入到LocalSessionFactoryBean中.要注意的是org.springframework.orm.hibernate3.LocalSessionFactoryBean是hibernate 3整合使用的,org.springframework.orm.hibernate.LocalSessionFactoryBean是hibernate 2中使用的.
最后是测试程序
public static void main(String[] args) {
ApplicationContext context =
new FileSystemXmlApplicationContext(
"beans-config.xml");
IUserDAO userDAO = (IUserDAO) context.getBean("userDAO");
User user = new User();
user.setName("jackyrong");
userDAO.insert(user);
}