spring整合hibernate需要加入的jar包:看图片
beans.xml示例代码:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>com/mxf/model/User.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
<!-- 这里可以加入 hibernate的一些控制语句-->
hibernate.dialect=org.hibernate.dialect.HSQLDialect
hibernate.show_sql=true
</value>
</property>
</bean>
Java代码:
package com.mxf.dao;
import java.sql.SQLException;
import javax.annotation.Resource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Component;
import com.mxf.model.User;
@Component("userDAO")
public class UserDAO {
//将sessionFactory注入
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
@Resource(name = "sessionFactory")
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void save(User user) throws SQLException {
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.save(user);
tx.commit();
}
}
另一种在beans.xml文件中整合:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses"><!-- 源码里面有该属性annotatedClasses 所以可以注入-->
<list>
<value>com.mxf.model.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
两者区别在于XML中的配置,Java类调用sessionFactory不变。