我们在上篇Spring框架的基础上进行Hibernate整合
详情见:Spring框架搭建
下面是本文Spring4+Hibernate4整合完毕之后的结构图
第一步:
①导入Hibernate的核心Jar,将此目录下的Jar全部导入
\hibernate-release-4.2.4.Final\lib\required
②导入Hibernate里的C3P0(由于本文中使用的是druid-1.0.11.jar,所以C3P0的Jar可以不导入)
\hibernate-release-4.2.4.Final\lib\optional\c3p0\c3p0-0.9.2.1.jar
③导入mysql驱动mysql-connector-java-5.0.8-bin.jar
第二步:在spring-hibernate.xml中配置数据源
<!-- 配置数据源 -->
<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="url" value="${jdbc_url}" />
<property name="username" value="${jdbc_user}" />
<property name="password" value="${jdbc_password}" />
<!-- 配置连接池 -->
<!-- 初始化连接大小 -->
<property name="initialSize" value="0" />
<!-- 连接池最大使用连接数量 -->
<property name="maxActive" value="20" />
<!-- 连接池最大空闲时间 -->
<property name="maxIdle" value="20" />
<!-- 连接池最小空闲时间 -->
<property name="minIdle" value="0" />
<!-- 获取链接最大等待时间 -->
<property name="maxWait" value="60000" />
<property name="validationQuery" value="${validationQuery}" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="testWhileIdle" value="true" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="25200000" />
<!-- 打开removeAbandoned功能 -->
<property name="removeAbandoned" value="true" />
<!-- 1800秒,也就是30分钟 -->
<property name="removeAbandonedTimeout" value="1800" />
<!-- 关闭abanded连接时输出错误日志 -->
<property name="logAbandoned" value="true" />
<!-- 监控数据库 -->
<!-- <property name="filters" value="stat" /> -->
<!-- <property name="filters" value="mergeStat" /> -->
<!-- 开启监控 -->
<property name="filters" value="stat" />
</bean>
第三步:在spring-hibernate.xml配置SessionFactory
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<!-- 指定自动生成数据表的策略 -->
<prop key="hibernate.hbm2ddl.auto">update</prop>
<!-- 执行操作时是否在控制台打印SQL -->
<prop key="hibernate.show_sql">true</prop>
<!-- 是否对SQL进行格式化 -->
<prop key="hibernate.format_sql">false</prop>
</props>
</property>
<!-- 扫描此包下的所有Entity,进行ORM映射 -->
<property name="packagesToScan">
<list>
<value>test.jia.com.*</value>
</list>
</property>
</bean>
第四步:在spring-hibernate.xml配置事物管理
<!-- 配置一个事务管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 使用annotation定义事务 -->
<tx:annotation-driven transaction-manager="transactionManager"
proxy-target-class="true" />
第五步:在web.xml中配置OpenSessionInViewFilter
<!--
Spring与Hibernate整合出现错误:
org.hibernate.HibernateException:
Could not obtain transaction-synchronized Session for current thread
解决:
加入下面配置
注:如果框架中整合了struts2,此监听器应该在struts2的监听器前面
-->
<!--
OpenSessionInViewFilter的作用:
在hibernate中使用load方法时,并未把数据真正获取时就关闭了session,
当我们真正想获取数据时会迫使load加载数据,而此时 session已关闭,所以就会出现异常。
比较典型的是在MVC模式中,我们在M层调用持久层获取数据时(持久层用的是load方法加载数据),
当这一调用结束时,session随之关闭,而我们 希望在V层使用这些数据,
这时才会迫使load加载数据,我们就希望这时的session是open着得,
这就是所谓的Open Session In view 。
-->
<filter>
<filter-name>openSession</filter-name>
<filter-class>
org.springframework.orm.hibernate4.support.OpenSessionInViewFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>openSession</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
第六步(可选):配置阿里巴巴数据源监控
<!-- 阿里巴巴数据源 -->
<servlet>
<servlet-name>DruidStatView</servlet-name>
<servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
</servlet>
<!-- 数据源监控访问页面 -->
<servlet-mapping>
<servlet-name>DruidStatView</servlet-name>
<url-pattern>/druid/*</url-pattern>
</servlet-mapping>
第七步:在web.xml修改Spring的contextConfigLocation的param-value,
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- 修改此路径,让Spring读取springmvc-context.xml与spring-hibernate.xml -->
<param-value>classpath:spring*.xml</param-value>
</context-param>
<!-- Spring 监听器 -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
至此,Spring与Hibernate整合完毕。
下面进行测试
Dao
@Service
public class BaseHibernateDao {
public BaseHibernateDao (){
}
@Autowired
private SessionFactory sessionFactory;
public Serializable save(Object entity) throws Exception {
return sessionFactory.getCurrentSession().save(entity);
}
}
Service
public interface BaseService{
/**
* 保存实体对象
* @param entity
* @return
*/
Serializable save(Object entity)throws Exception;
}
ServiceImpl
@Service
public class BaseServiceImpl implements BaseService {
public BaseServiceImpl () {
}
@Autowired
private BaseHibernateDao baseHibernateDao;
@Override
@Transactional
public Serializable save(Object entity) throws Exception {
return baseHibernateDao.save(entity);
}
}
Entity
@Entity
@Table(name="login_user")
public class LoginUser {
@Id
@Column
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column
private String username;
@Column
private String password;
@Column
private int age;
@Column
private Date birthday;
//set get ...
}
Controller
@Controller
@RequestMapping("LoginController")
public class LoginController {
@Autowired
public BaseService baseService;
@RequestMapping("login")
public String login(HttpServletRequest request , HttpServletResponse response){
System.out.println(" welcome ! ");
try {
baseService.save(new LoginUser("李四"));
} catch (Exception e) {
e.printStackTrace();
}
return "login";
}
}