首页 > 编程语言 > 详细

【Spring实战-2】Spring4.0.4整合Hibernate4.3.6

时间:2015-05-29 13:26:25      阅读:371      评论:0      收藏:0      [点我收藏+]

标签:des   事务   class   style   log   com   代码   使用   http   

作者:ssslinppp      

1. 摘要

本文主要讲解如何在Spring4.0.4下整合Hibernate4.3.6;
主要介绍了如下内容:
  1. 项目结构的规划;
  2. Spring MVC的配置和使用;
  3. Spring下整合Hibernate的具体过程;
  4. 数据源的配置;
  5. 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配置文件中,需要配置如下内容:
  1. spring上下文文件(applicationContext-*.xml)加载路径;
  2. spring容器的监听器;
  3. 配置spring MVC;
技术分享
技术分享

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="2.5"
  3. xmlns="http://java.sun.com/xml/ns/javaee"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  6. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  7. <!-- 从类路径下加载Spring配置文件,classpath关键字特指从类路径下加载 -->
  8. <context-param>
  9. <param-name>contextConfigLocation</param-name>
  10. <param-value>classpath:/config/spring-config/applicationContext-*.xml</param-value>
  11. </context-param>
  12. <!-- 负责启动Spring容器的监听器 -->
  13. <listener>
  14. <listener-class>
  15. org.springframework.web.context.ContextLoaderListener
  16. </listener-class>
  17. </listener>
  18. <!-- 配置Spring MVC -->
  19. <servlet>
  20. <servlet-name>springMVC</servlet-name>
  21. <servlet-class>
  22. org.springframework.web.servlet.DispatcherServlet
  23. </servlet-class>
  24. <init-param>
  25. <param-name>contextConfigLocation</param-name>
  26. <param-value>classpath*:/config/spring-config/springmvc-servlet.xml</param-value>
  27. </init-param>
  28. <load-on-startup>3</load-on-startup>
  29. </servlet>
  30. <servlet-mapping>
  31. <servlet-name>springMVC</servlet-name>
  32. <url-pattern>*.action</url-pattern>
  33. </servlet-mapping>
  34. </web-app>


4. 数据源配置

对应文件:applicationContext-datasource-mysql.xml和database.properties;
数据源属性以及Hibernate相关属性都保存在database.properties文件中。
database.properties文件内容如下:
技术分享
  1. #数据库相关配置
  2. #hibernate.connection.url=jdbc\:oracle\:thin\:@127.0.0.1\:1521\:dbname
  3. jdbc.connection.url=jdbc:mysql://localhost:3306/sampledb
  4. #jdbc.connection.driver_class=oracle.jdbc.driver.OracleDriver
  5. jdbc.connection.driver_class=com.mysql.jdbc.Driver
  6. jdbc.connection.username=root
  7. jdbc.connection.password=qaz
  8. #Hibernate相关配置
  9. #hibernate.dialect=org.hibernate.dialect.OracleDialect
  10. #hibernate.dialect=org.hibernate.dialect.SQLServerDialect
  11. hibernate.dialect=org.hibernate.dialect.MySQLDialect
  12. hibernate.hbm2dll.auto=update
  13. hibernate.show_sql=true

数据源的配置,数据源的配置方式有多种,常见的是使用C3P0连接池,也可以使用BasicDataSource数据源;
主要完成以下工作:
  1. 制定database.properties文件的存放位置;
  2. 配置C3P0数据源;
  3. 为数据配置事务管理;

applicationContext-datasource-mysql.xml

技术分享技术分享技术分享技术分享

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:p="http://www.springframework.org/schema/p"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
  7. <!--方式1:指定配置文件存放位置 -->
  8. <bean id="propertyConfigurer"
  9. class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  10. <property name="locations">
  11. <list>
  12. <value>classpath:/config/database.properties</value>
  13. </list>
  14. </property>
  15. </bean>
  16. <!--方式2:指定配置文件存放位置 -->
  17. <!-- <context:property-placeholder location="classpath:/config/database.properties" />
  18. -->
  19. <!-- 方式1:配置数据源,采用c3p0数据源 -->
  20. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
  21. destroy-method="close">
  22. <property name="driverClass" value="${jdbc.connection.driver_class}" />
  23. <property name="jdbcUrl" value="${jdbc.connection.url}" />
  24. <property name="user" value="${jdbc.connection.username}" />
  25. <property name="password" value="${jdbc.connection.password}" />
  26. <property name="minPoolSize" value="2" />
  27. <property name="maxPoolSize" value="20" />
  28. <property name="maxIdleTime" value="1800" />
  29. <property name="acquireIncrement" value="2" />
  30. <property name="maxStatements" value="0" />
  31. <property name="initialPoolSize" value="3" />
  32. <property name="idleConnectionTestPeriod" value="1800" />
  33. <property name="acquireRetryAttempts" value="4" />
  34. <property name="breakAfterAcquireFailure" value="false" />
  35. <property name="testConnectionOnCheckout" value="false" />
  36. </bean>
  37. <!-- 方式2:配置数据源,采用BasicDataSource数据源 -->
  38. <!-- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
  39. destroy-method="close" p:driverClassName="${hibernate.connection.driver_class}"
  40. p:url="${hibernate.connection.url}" p:username="${hibernate.connection.username}"
  41. p:password="${hibernate.connection.password}" /> -->
  42. <!-- jdbc事务管理器 -->
  43. <bean id="txManagerJDBC"
  44. class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  45. <property name="dataSource">
  46. <ref local="dataSource" />
  47. </property>
  48. </bean>
  49. <!--事务模板 -->
  50. <bean id="transactionTemplate"
  51. class="org.springframework.transaction.support.TransactionTemplate">
  52. <property name="transactionManager">
  53. <ref local="txManagerJDBC" />
  54. </property>
  55. </bean>
  56. </beans>



5. Hibernate整合

对应文件:applicationContext-hibernate-mysql.xml;
Hibernate的整合主要是配置sessionFactory,而sessionFactory的配置主要涉及3个方面的配置,
  1. 数据源配置;
  2. Hibernate属性配置;
  3.  关联orm映射文件;
此外,一般还需要配置Hibernate事务管理器配置Hibernate异常,以及面向切面的AOP配置

技术分享技术分享技术分享技术分享
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context-3.0.xsd
  10. http://www.springframework.org/schema/tx
  11. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  12. http://www.springframework.org/schema/aop
  13. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
  14. <bean id="sessionFactory"
  15. class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
  16. <property name="dataSource">
  17. <ref bean="dataSource" />
  18. </property>
  19. <property name="hibernateProperties">
  20. <props>
  21. <prop key="hibernate.dialect">${hibernate.dialect}</prop>
  22. <prop key="hibernate.hbm2dll.auto">${hibernate.hbm2dll.auto}</prop>
  23. <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
  24. </props>
  25. </property>
  26. <!-- 配置实体类 即相当于配置了 映射文件 -->
  27. <!-- <property name="annotatedClasses"> <list> <value>com.ll.spring.orm.Cat</value>
  28. </list> </property> -->
  29. <!-- ORM映射文件存储位置 -->
  30. <property name="mappingDirectoryLocations">
  31. <list>
  32. <value>classpath:/config/hibernate-config</value>
  33. </list>
  34. </property>
  35. </bean>
  36. <!-- 配置Hibernate事务管理器 -->
  37. <bean id="txManager_Hibernate"
  38. class="org.springframework.orm.hibernate4.HibernateTransactionManager">
  39. <property name="sessionFactory" ref="sessionFactory" />
  40. </bean>
  41. <tx:annotation-driven transaction-manager="txManager_Hibernate"/>
  42. <!-- 配置事务异常封装 -->
  43. <bean id="persistenceExceptionTranslationPostProcessor"
  44. class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
  45. <!-- 声明式容器事务管理 ,transaction-manager指定事务管理器为transactionManager -->
  46. <tx:advice id="txAdvice" transaction-manager="txManager_Hibernate">
  47. <tx:attributes>
  48. <tx:method name="save*" propagation="REQUIRED" />
  49. <tx:method name="read*" read-only="true" />
  50. <tx:method name="list*" read-only="true" />
  51. <tx:method name="delete*" propagation="REQUIRED" />
  52. <tx:method name="modify*" propagation="REQUIRED" />
  53. <tx:method name="*" propagation="REQUIRED" />
  54. </tx:attributes>
  55. </tx:advice>
  56. <!-- aop配置 -->
  57. <aop:config >
  58. <aop:pointcut id="txPointcut" expression="execution(* com.ll.service..*.*(..))" />
  59. <aop:advisor pointcut-ref="txPointcut" advice-ref="txAdvice" />
  60. </aop:config>
  61. </beans>


6. 配置spring mvc

对应文件:springmvc-servlet.xml;
需要配置:
  1. 扫描组件的配置,扫描控制层所有标注@Controller的类;
  2. 配置视图解析器;
技术分享
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  7. http://www.springframework.org/schema/context
  8. http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  9. <!-- 扫描web包,应用Spring的注解 -->
  10. <context:component-scan base-package="com.ll.web" />
  11. <!-- 配置视图解析器,将ModelAndView及字符串解析为具体的页面 -->
  12. <bean
  13. class="org.springframework.web.servlet.view.InternalResourceViewResolver"
  14. p:viewClass="org.springframework.web.servlet.view.JstlView" p:prefix="/jsp/"
  15. p:suffix=".jsp" />
  16. </beans>


7. 配置常规的bean

对应文件:applicationContext-Login.xml;
说明,随着业务的增多,bean的数量会增多,为了分类存放bean,bean的配置文件可以有若干个。
主要配置如下:
  1. 扫描组件的配置,扫描业务层、持久层分别标注了@Service 和 @Repository的类;
  2. 配置 HibernateTemplate和JdbcTemplate;
技术分享
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context-3.0.xsd
  10. http://www.springframework.org/schema/tx
  11. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  12. http://www.springframework.org/schema/aop
  13. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
  14. <!-- 扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入 -->
  15. <context:component-scan base-package="com.ll.dao" />
  16. <context:component-scan base-package="com.ll.service" />
  17. <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate"
  18. p:sessionFactory-ref="sessionFactory" />
  19. <!-- 配置Jdbc模板 -->
  20. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
  21. p:dataSource-ref="dataSource" />
  22. </beans>


8. 配置ORM映射文件

对应文件:User.hbm.xml和User.java;
技术分享技术分享
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  4. <hibernate-mapping>
  5. <class name="com.ll.domain.User" table="t_user">
  6. <id name="userId" type="java.lang.Integer">
  7. <column name="user_id" />
  8. <generator class="increment" />
  9. </id>
  10. <property name="userName" type="java.lang.String">
  11. <column name="user_name" length="60"/>
  12. </property>
  13. <property name="password" type="java.lang.String">
  14. <column name="password" length="60"/>
  15. </property>
  16. <property name="credits" type="java.lang.Integer">
  17. <column name="credits"/>
  18. </property>
  19. <property name="lastIp" type="java.lang.String">
  20. <column name="last_ip" length="32" />
  21. </property>
  22. <property name="lastVisit" type="java.util.Date">
  23. <column name="last_visit" length="23" />
  24. </property>
  25. </class>
  26. </hibernate-mapping>

技术分享
  1. package com.ll.domain;
  2. import java.io.Serializable;
  3. import java.util.Date;
  4. @SuppressWarnings("serial")
  5. public class User implements Serializable {
  6. private int userId;
  7. private String userName;
  8. private String password;
  9. private int credits;
  10. private String lastIp;
  11. private Date lastVisit;
  12. public String getLastIp() {
  13. return lastIp;
  14. }
  15. public void setLastIp(String lastIp) {
  16. this.lastIp = lastIp;
  17. }
  18. public Date getLastVisit() {
  19. return lastVisit;
  20. }
  21. public void setLastVisit(Date lastVisit) {
  22. this.lastVisit = lastVisit;
  23. }
  24. public int getUserId() {
  25. return userId;
  26. }
  27. public void setUserId(int userId) {
  28. this.userId = userId;
  29. }
  30. public String getUserName() {
  31. return userName;
  32. }
  33. public void setUserName(String userName) {
  34. this.userName = userName;
  35. }
  36. public String getPassword() {
  37. return password;
  38. }
  39. public void setPassword(String password) {
  40. this.password = password;
  41. }
  42. public int getCredits() {
  43. return credits;
  44. }
  45. public void setCredits(int credits) {
  46. this.credits = credits;
  47. }
  48. }

技术分享



9. 程序执行过程和结果

当在浏览器中输入:http://localhost:8080/HibernateQs/index.action ,就会跳转到login.jsp界面;
技术分享
下面是:login.jsp
技术分享
技术分享

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
  4. <html>
  5. <head>
  6. <title>论坛登录</title>
  7. </head>
  8. <body>
  9. <c:if test="${!empty error}">
  10. <font color="red"><c:out value="${error}" /></font>
  11. </c:if>
  12. <form action="<c:url value="test.action"/>" method="post">
  13. 用户名:
  14. <input type="text" name="userName">
  15. <br>
  16. 密 码:
  17. <input type="password" name="password">
  18. <br>
  19. <input type="submit" value="登录" />
  20. <input type="reset" value="重置" />
  21. </form>
  22. </body>
  23. </html>

点击登录按键,就会跳转到:
技术分享
技术分享
技术分享
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  4. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  5. <html>
  6. <head>
  7. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  8. <title>宝宝淘论坛</title>
  9. </head>
  10. <body>
  11. ${user.userName},欢迎您进入宝宝淘论坛,您当前积分为${user.credits};
  12. </body>
  13. </html>


下面看看后台执行的操作:

控制层:
技术分享
业务层:
技术分享
持久层:
技术分享
看看执行结果:
技术分享技术分享

10. 可能遇到的报错

1. 报错信息:
Turn your Session into FlushMode.COMMIT/AUTO or remove ‘readOnly‘ marker from transaction
这个异常产生的主要原因是DAO采用了Spring容器的事务管理策略,如果操作方法的名称和事务策略中指定的被管理的名称不能够匹配上,spring 就会采取默认的事务管理策略(PROPAGATION_REQUIRED,read only).如果是插入和修改操作,就不被允许的,
所以我们需要在spring配置文件中加上对事物的控制的配置:
技术分享



11. 完整程序

LoginController.java
  1. package com.ll.web;
  2. import javax.servlet.http.HttpServletRequest;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Controller;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import com.ll.domain.User;
  7. import com.ll.service.IUserService;
  8. import com.ll.service.UserService;
  9. @Controller
  10. public class LoginController {
  11. @Autowired
  12. private IUserService userService;
  13. @RequestMapping(value = "/index.action")
  14. public String loginPage() {
  15. return "login";
  16. }
  17. @RequestMapping(value = "/test.action")
  18. public String test(HttpServletRequest request, LoginCommand loginCommand) {
  19. System.out.println("用户名:" + loginCommand.getUserName() + "--密码:"
  20. + loginCommand.getPassword());
  21. User user = new User();
  22. user.setUserName(loginCommand.getUserName());
  23. user.setPassword(loginCommand.getPassword());
  24. userService.save(user);
  25. request.getSession().setAttribute("user", user);
  26. return "main";
  27. }
  28. }



LoginCommand.java

  1. package com.ll.web;
  2. public class LoginCommand {
  3. private String userName;
  4. private String password;
  5. public String getPassword() {
  6. return password;
  7. }
  8. public void setPassword(String password) {
  9. this.password = password;
  10. }
  11. public String getUserName() {
  12. return userName;
  13. }
  14. public void setUserName(String userName) {
  15. this.userName = userName;
  16. }
  17. }


UserService.java

  1. package com.ll.service;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.stereotype.Service;
  4. import com.ll.dao.IUserDao;
  5. import com.ll.dao.UserDao;
  6. import com.ll.domain.User;
  7. @Service
  8. public class UserService implements IUserService{
  9. @Autowired
  10. private IUserDao userDao;
  11. public void save(User user){
  12. userDao.save(user);
  13. }
  14. }


IUserService.java

  1. package com.ll.service;
  2. import com.ll.domain.User;
  3. public interface IUserService {
  4. public void save(User user);
  5. }


UserDao.java

  1. package com.ll.dao;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.jdbc.core.JdbcTemplate;
  4. import org.springframework.orm.hibernate4.HibernateTemplate;
  5. import org.springframework.stereotype.Repository;
  6. import com.ll.domain.User;
  7. @Repository
  8. public class UserDao implements IUserDao{
  9. @Autowired
  10. private HibernateTemplate hibernateTemplate;
  11. @Autowired
  12. private JdbcTemplate jdbcTemplate;
  13. public void save(User user) {
  14. // 测试jdbcTemplate操作
  15. String sqlStr = " SELECT count(*) FROM t_user ";
  16. int count = jdbcTemplate.queryForInt(sqlStr);
  17. System.out.println("jdbcTemplate-用户个数:" + count);
  18. //测试hibernateTemplate读写操作
  19. try {
  20. System.out.println("hibernateTemplate-用户个数: " + hibernateTemplate.find("from User").size());
  21. hibernateTemplate.save(user);
  22. } catch (Exception e) {
  23. System.out.println("==》Hibernate保存数据错误...");
  24. System.out.println(e.getMessage());
  25. }
  26. }
  27. }



IUserDao.java

  1. package com.ll.dao;
  2. import com.ll.domain.User;
  3. public interface IUserDao {
  4. public void save(User user);
  5. }


User.java

  1. package com.ll.domain;
  2. import java.io.Serializable;
  3. import java.util.Date;
  4. @SuppressWarnings("serial")
  5. public class User implements Serializable {
  6. private int userId;
  7. private String userName;
  8. private String password;
  9. private int credits;
  10. private String lastIp;
  11. private Date lastVisit;
  12. public String getLastIp() {
  13. return lastIp;
  14. }
  15. public void setLastIp(String lastIp) {
  16. this.lastIp = lastIp;
  17. }
  18. public Date getLastVisit() {
  19. return lastVisit;
  20. }
  21. public void setLastVisit(Date lastVisit) {
  22. this.lastVisit = lastVisit;
  23. }
  24. public int getUserId() {
  25. return userId;
  26. }
  27. public void setUserId(int userId) {
  28. this.userId = userId;
  29. }
  30. public String getUserName() {
  31. return userName;
  32. }
  33. public void setUserName(String userName) {
  34. this.userName = userName;
  35. }
  36. public String getPassword() {
  37. return password;
  38. }
  39. public void setPassword(String password) {
  40. this.password = password;
  41. }
  42. public int getCredits() {
  43. return credits;
  44. }
  45. public void setCredits(int credits) {
  46. this.credits = credits;
  47. }
  48. }






【Spring实战-2】Spring4.0.4整合Hibernate4.3.6

标签:des   事务   class   style   log   com   代码   使用   http   

原文:http://www.cnblogs.com/ssslinppp/p/4538035.html

(0)
(0)
   
举报
评论 一句话评论(0
0条  
登录后才能评论!
© 2014 bubuko.com 版权所有 鲁ICP备09046678号-4
打开技术之扣,分享程序人生!
             

鲁公网安备 37021202000002号