作者:ssslinppp
1. 摘要
本文主要讲解如何在Spring4.0.4下整合Hibernate4.3.6;
主要介绍了如下内容:
- 项目结构的规划;
- Spring MVC的配置和使用;
- Spring下整合Hibernate的具体过程;
- 数据源的配置;
- jdbcTemplate和HibernateTemplate两种方式操作数据库;
2. 项目结构的规划
下面是整个项目的截图;
程序源代码分层设计,主要分为Dao层、service层和controller层,还有一个domain层(用于存放POJO对象),主要是数据库操作时的数据模型。
按接口编程,Dao层、service层按接口编程;
配置文件分类存放
使用的jar包主要如下所示
因为使用了C3P0数据源,所有需要引入相应的jar包。
使用mysql数据库,需要引入mysql驱动jar包;
前端界面分类存放,这里仅列举了jsp文件夹,如何需要引入其他js文件,如easyui、jquery等,可以在创建具体的分类文件夹;
3. web.xml配置文件
在web.xml配置文件中,需要配置如下内容:
- spring上下文文件(applicationContext-*.xml)加载路径;
- spring容器的监听器;
- 配置spring MVC;
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 从类路径下加载Spring配置文件,classpath关键字特指从类路径下加载 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/config/spring-config/applicationContext-*.xml</param-value>
</context-param>
<!-- 负责启动Spring容器的监听器 -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- 配置Spring MVC -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/config/spring-config/springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>3</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
4. 数据源配置
对应文件:applicationContext-datasource-mysql.xml和database.properties;
数据源属性以及Hibernate相关属性都保存在database.properties文件中。
database.properties文件内容如下:
#数据库相关配置
#hibernate.connection.url=jdbc\:oracle\:thin\:@127.0.0.1\:1521\:dbname
jdbc.connection.url=jdbc:mysql://localhost:3306/sampledb
#jdbc.connection.driver_class=oracle.jdbc.driver.OracleDriver
jdbc.connection.driver_class=com.mysql.jdbc.Driver
jdbc.connection.username=root
jdbc.connection.password=qaz
#Hibernate相关配置
#hibernate.dialect=org.hibernate.dialect.OracleDialect
#hibernate.dialect=org.hibernate.dialect.SQLServerDialect
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.hbm2dll.auto=update
hibernate.show_sql=true
数据源的配置,数据源的配置方式有多种,常见的是使用C3P0连接池,也可以使用BasicDataSource数据源;
主要完成以下工作:
- 制定database.properties文件的存放位置;
- 配置C3P0数据源;
- 为数据配置事务管理;
applicationContext-datasource-mysql.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!--方式1:指定配置文件存放位置 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:/config/database.properties</value>
</list>
</property>
</bean>
<!--方式2:指定配置文件存放位置 -->
<!-- <context:property-placeholder location="classpath:/config/database.properties" />
-->
<!-- 方式1:配置数据源,采用c3p0数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.connection.driver_class}" />
<property name="jdbcUrl" value="${jdbc.connection.url}" />
<property name="user" value="${jdbc.connection.username}" />
<property name="password" value="${jdbc.connection.password}" />
<property name="minPoolSize" value="2" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="1800" />
<property name="acquireIncrement" value="2" />
<property name="maxStatements" value="0" />
<property name="initialPoolSize" value="3" />
<property name="idleConnectionTestPeriod" value="1800" />
<property name="acquireRetryAttempts" value="4" />
<property name="breakAfterAcquireFailure" value="false" />
<property name="testConnectionOnCheckout" value="false" />
</bean>
<!-- 方式2:配置数据源,采用BasicDataSource数据源 -->
<!-- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${hibernate.connection.driver_class}"
p:url="${hibernate.connection.url}" p:username="${hibernate.connection.username}"
p:password="${hibernate.connection.password}" /> -->
<!-- jdbc事务管理器 -->
<bean id="txManagerJDBC"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource">
<ref local="dataSource" />
</property>
</bean>
<!--事务模板 -->
<bean id="transactionTemplate"
class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager">
<ref local="txManagerJDBC" />
</property>
</bean>
</beans>
5. Hibernate整合
对应文件:applicationContext-hibernate-mysql.xml;
Hibernate的整合主要是配置sessionFactory,而sessionFactory的配置主要涉及3个方面的配置,
- 数据源配置;
- Hibernate属性配置;
- 关联orm映射文件;
此外,一般还需要配置Hibernate事务管理器,配置Hibernate异常,以及面向切面的AOP配置;
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.hbm2dll.auto">${hibernate.hbm2dll.auto}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
<!-- 配置实体类 即相当于配置了 映射文件 -->
<!-- <property name="annotatedClasses"> <list> <value>com.ll.spring.orm.Cat</value>
</list> </property> -->
<!-- ORM映射文件存储位置 -->
<property name="mappingDirectoryLocations">
<list>
<value>classpath:/config/hibernate-config</value>
</list>
</property>
</bean>
<!-- 配置Hibernate事务管理器 -->
<bean id="txManager_Hibernate"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager_Hibernate"/>
<!-- 配置事务异常封装 -->
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<!-- 声明式容器事务管理 ,transaction-manager指定事务管理器为transactionManager -->
<tx:advice id="txAdvice" transaction-manager="txManager_Hibernate">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="read*" read-only="true" />
<tx:method name="list*" read-only="true" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="modify*" propagation="REQUIRED" />
<tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<!-- aop配置 -->
<aop:config >
<aop:pointcut id="txPointcut" expression="execution(* com.ll.service..*.*(..))" />
<aop:advisor pointcut-ref="txPointcut" advice-ref="txAdvice" />
</aop:config>
</beans>
6. 配置spring mvc
对应文件:springmvc-servlet.xml;
需要配置:
- 扫描组件的配置,扫描控制层所有标注@Controller的类;
- 配置视图解析器;
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- 扫描web包,应用Spring的注解 -->
<context:component-scan base-package="com.ll.web" />
<!-- 配置视图解析器,将ModelAndView及字符串解析为具体的页面 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:viewClass="org.springframework.web.servlet.view.JstlView" p:prefix="/jsp/"
p:suffix=".jsp" />
</beans>
7. 配置常规的bean
对应文件:applicationContext-Login.xml;
说明,随着业务的增多,bean的数量会增多,为了分类存放bean,bean的配置文件可以有若干个。
主要配置如下:
- 扫描组件的配置,扫描业务层、持久层分别标注了@Service 和
@Repository的类;
- 配置
HibernateTemplate和JdbcTemplate;
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- 扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入 -->
<context:component-scan base-package="com.ll.dao" />
<context:component-scan base-package="com.ll.service" />
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate"
p:sessionFactory-ref="sessionFactory" />
<!-- 配置Jdbc模板 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
p:dataSource-ref="dataSource" />
</beans>
8. 配置ORM映射文件
对应文件:User.hbm.xml和User.java;
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.ll.domain.User" table="t_user">
<id name="userId" type="java.lang.Integer">
<column name="user_id" />
<generator class="increment" />
</id>
<property name="userName" type="java.lang.String">
<column name="user_name" length="60"/>
</property>
<property name="password" type="java.lang.String">
<column name="password" length="60"/>
</property>
<property name="credits" type="java.lang.Integer">
<column name="credits"/>
</property>
<property name="lastIp" type="java.lang.String">
<column name="last_ip" length="32" />
</property>
<property name="lastVisit" type="java.util.Date">
<column name="last_visit" length="23" />
</property>
</class>
</hibernate-mapping>
package com.ll.domain;
import java.io.Serializable;
import java.util.Date;
@SuppressWarnings("serial")
public class User implements Serializable {
private int userId;
private String userName;
private String password;
private int credits;
private String lastIp;
private Date lastVisit;
public String getLastIp() {
return lastIp;
}
public void setLastIp(String lastIp) {
this.lastIp = lastIp;
}
public Date getLastVisit() {
return lastVisit;
}
public void setLastVisit(Date lastVisit) {
this.lastVisit = lastVisit;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getCredits() {
return credits;
}
public void setCredits(int credits) {
this.credits = credits;
}
}
9. 程序执行过程和结果
当在浏览器中输入:http://localhost:8080/HibernateQs/index.action ,就会跳转到login.jsp界面;
下面是:login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>论坛登录</title>
</head>
<body>
<c:if test="${!empty error}">
<font color="red"><c:out value="${error}" /></font>
</c:if>
<form action="<c:url value="test.action"/>" method="post">
用户名:
<input type="text" name="userName">
<br>
密 码:
<input type="password" name="password">
<br>
<input type="submit" value="登录" />
<input type="reset" value="重置" />
</form>
</body>
</html>
点击登录按键,就会跳转到:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>宝宝淘论坛</title>
</head>
<body>
${user.userName},欢迎您进入宝宝淘论坛,您当前积分为${user.credits};
</body>
</html>
下面看看后台执行的操作:
控制层:
业务层:
持久层:
看看执行结果:
10. 可能遇到的报错
1. 报错信息:
Turn your Session into FlushMode.COMMIT/AUTO or remove ‘readOnly‘ marker from transaction
2.解决方案:http://blog.csdn.net/intlgj/article/details/7344373
这个异常产生的主要原因是DAO采用了Spring容器的事务管理策略,如果操作方法的名称和事务策略中指定的被管理的名称不能够匹配上,spring 就会采取默认的事务管理策略(PROPAGATION_REQUIRED,read only).如果是插入和修改操作,就不被允许的,
所以我们需要在spring配置文件中加上对事物的控制的配置:
11. 完整程序
LoginController.java
package com.ll.web;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.ll.domain.User;
import com.ll.service.IUserService;
import com.ll.service.UserService;
@Controller
public class LoginController {
@Autowired
private IUserService userService;
@RequestMapping(value = "/index.action")
public String loginPage() {
return "login";
}
@RequestMapping(value = "/test.action")
public String test(HttpServletRequest request, LoginCommand loginCommand) {
System.out.println("用户名:" + loginCommand.getUserName() + "--密码:"
+ loginCommand.getPassword());
User user = new User();
user.setUserName(loginCommand.getUserName());
user.setPassword(loginCommand.getPassword());
userService.save(user);
request.getSession().setAttribute("user", user);
return "main";
}
}
LoginCommand.java
package com.ll.web;
public class LoginCommand {
private String userName;
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
UserService.java
package com.ll.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ll.dao.IUserDao;
import com.ll.dao.UserDao;
import com.ll.domain.User;
@Service
public class UserService implements IUserService{
@Autowired
private IUserDao userDao;
public void save(User user){
userDao.save(user);
}
}
IUserService.java
package com.ll.service;
import com.ll.domain.User;
public interface IUserService {
public void save(User user);
}
UserDao.java
package com.ll.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;
import com.ll.domain.User;
@Repository
public class UserDao implements IUserDao{
@Autowired
private HibernateTemplate hibernateTemplate;
@Autowired
private JdbcTemplate jdbcTemplate;
public void save(User user) {
// 测试jdbcTemplate操作
String sqlStr = " SELECT count(*) FROM t_user ";
int count = jdbcTemplate.queryForInt(sqlStr);
System.out.println("jdbcTemplate-用户个数:" + count);
//测试hibernateTemplate读写操作
try {
System.out.println("hibernateTemplate-用户个数: " + hibernateTemplate.find("from User").size());
hibernateTemplate.save(user);
} catch (Exception e) {
System.out.println("==》Hibernate保存数据错误...");
System.out.println(e.getMessage());
}
}
}
IUserDao.java
package com.ll.dao;
import com.ll.domain.User;
public interface IUserDao {
public void save(User user);
}
User.java
package com.ll.domain;
import java.io.Serializable;
import java.util.Date;
@SuppressWarnings("serial")
public class User implements Serializable {
private int userId;
private String userName;
private String password;
private int credits;
private String lastIp;
private Date lastVisit;
public String getLastIp() {
return lastIp;
}
public void setLastIp(String lastIp) {
this.lastIp = lastIp;
}
public Date getLastVisit() {
return lastVisit;
}
public void setLastVisit(Date lastVisit) {
this.lastVisit = lastVisit;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getCredits() {
return credits;
}
public void setCredits(int credits) {
this.credits = credits;
}
}