Spring4 MVC Hibernate4集成
一、 本文所用环境
Spring4.0.3.RELEASE
Hibernate4.3.5.Final
Mysql
二、 工程目录
三、 Maven添加依赖
用Maven创建项目,pom.xml如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.lei.demo</groupId> <artifactId>spring3-mvc-hibernate</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>spring3-mvc-hibernate Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>4.0.3.RELEASE</version> </dependency> <!-- AspectJ --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.7.4</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.7.4</version> </dependency> <!-- Mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.29</version> </dependency> <!-- Hibernate4 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.5.Final</version> </dependency> <!-- for JPA, use hibernate-entitymanager instead of hibernate-core --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.3.5.Final</version> </dependency> <!-- 以下可选 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-envers</artifactId> <version>4.3.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-c3p0</artifactId> <version>4.3.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-proxool</artifactId> <version>4.3.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-infinispan</artifactId> <version>4.3.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>4.3.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-commons-annotations</artifactId> <version>4.0.4.Final</version> </dependency> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.1-api</artifactId> <version>1.0.0.Final</version> </dependency> <dependency> <groupId>org.jboss</groupId> <artifactId>jandex</artifactId> <version>1.1.0.Final</version> </dependency> <!-- 为了让Hibernate使用代理模式,需要javassist --> <dependency> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> <version>3.18.1-GA</version> </dependency> <dependency> <groupId>org.jboss.logging</groupId> <artifactId>jboss-logging</artifactId> <version>3.1.3.GA</version> </dependency> <dependency> <groupId>org.jboss.spec.javax.annotation</groupId> <artifactId>jboss-annotations-api_1.2_spec</artifactId> <version>1.0.0.Final</version> </dependency> <dependency> <groupId>antlr</groupId> <artifactId>antlr</artifactId> <version>2.7.7</version> </dependency> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>javax.transaction</groupId> <artifactId>jta</artifactId> <version>1.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.0-api</artifactId> <version>1.0.0.Final</version> </dependency> <!-- tomcat7.0.35 数据库连接池 --> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-dbcp</artifactId> <version>7.0.35</version> </dependency> </dependencies> <build> <finalName>spring3-mvc-hibernate</finalName> </build> </project>
四、 新建数据库表
数据库采用Mysql,新建users表,我们演示操作此表
CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `age` int(11) DEFAULT NULL, `nice_name` varchar(32) DEFAULT NULL, `user_name` varchar(32) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
创建Entity类Users.java见下
package com.lei.demo.entity; import javax.persistence.*; @Entity(name="users") public class Users { public Users(){ super(); } @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="id") private Integer id; @Column(name="user_name",length=32) private String user_name; @Column(name="age") private Integer age; @Column(name="nice_name",length=32) private String nice_name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUser_name() { return user_name; } public void setUser_name(String user_name) { this.user_name = user_name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getNice_name() { return nice_name; } public void setNice_name(String nice_name) { this.nice_name = nice_name; } }
五、 配置文件
1. 首先看一下Web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Archetype Created Web Application</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/spring-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 定义DispatcherServlet --> <servlet> <servlet-name>lei-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <!-- 默认/WEB-INF/[servlet名字]-servlet.xml加载上下文, 如果配置了contextConfigLocation参数, 将使用classpath:/lei-dispatcher-servlet.xml加载上下文 --> <param-name>contextConfigLocation</param-name> <param-value>classpath:/lei-dispatcher-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- 拦截匹配的请求,这里所有请求采用名字为lei-dispatcher的DispatcherServlet处理 --> <servlet-mapping> <servlet-name>lei-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
2. lei-dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd "> <!-- 启动自动扫描该包下所有的Bean(例如@Controller) --> <context:component-scan base-package="com.lei.demo" /> <!-- 定义视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/user/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
3. Spring-hibernate的整合
spring-hibernate.xml文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd "> <!-- Hibernate4 --> <!-- 加载资源文件 其中包含变量信息,必须在Spring配置文件的最前面加载,即第一个加载--> <context:property-placeholder location="classpath:persistence-mysql.properties" /> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan"> <list> <!-- 可以加多个包 --> <value>com.lei.demo.entity</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <!-- <prop key="hibernate.current_session_context_class">thread</prop> --> </props> </property> </bean> <!-- 数据库映射 --> <!-- class="org.apache.tomcat.dbcp.dbcp.BasicDataSource" --> <!-- class="org.springframework.jdbc.datasource.DriverManagerDataSource" --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.user}" /> <property name="password" value="${jdbc.pass}" /> </bean> <!-- 配置Hibernate事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 配置事务异常封装 --> <bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" /> <!-- 声明式容器事务管理 ,transaction-manager指定事务管理器为transactionManager --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="get*" propagation="REQUIRED" /> <tx:method name="*" read-only="true" /> </tx:attributes> </tx:advice> <aop:config expose-proxy="true"> <!-- 只对业务逻辑层实施事务 --> <aop:pointcut id="txPointcut" expression="execution(* com.lei.demo.service..*.*(..))" /> <!-- Advisor定义,切入点和通知分别为txPointcut、txAdvice --> <aop:advisor pointcut-ref="txPointcut" advice-ref="txAdvice"/> </aop:config> </beans>
事务采用tx:advice和aop:config的xml配置方式实现。事务的其他实现方式见《Spring MVC事务配置》
资源文件persistence-mysql.properties如下:
# jdbc.X
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://yourServerIP:3306/yourDatabase?createDatabaseIfNotExist=true
jdbc.user=user
jdbc.pass=password
# hibernate.X
hibernate.connection.driverClass=org.gjt.mm.mysql.Driver
hibernate.connection.url=jdbc:mysql:// yourServerIP:3306/yourDatabase
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.connection.username=user
hibernate.connection.password=password
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
六、 DAO、Service
UsersDAO.java如下:
package com.lei.demo.dao; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.lei.demo.entity.Users; public class UsersDAO { private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public SessionFactory getSessionFactory() { return sessionFactory; } public List<Users> getAllUser(){ String hsql="from users"; Session session = sessionFactory.getCurrentSession(); Query query = session.createQuery(hsql); return query.list(); } }
UserService.java如下:
package com.lei.demo.service; import com.lei.demo.dao.*; public class UserService { private UsersDAO userDao; public int userCount(){ return userDao.getAllUser().size(); } public UsersDAO getUserDao() { return userDao; } public void setUserDao(UsersDAO userDao) { this.userDao = userDao; } }
七、 加载Bean配置文件
这里主要是加载上边的dao、service
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> <bean id="usersDAO" class="com.lei.demo.dao.UsersDAO"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <bean id="userService" class="com.lei.demo.service.UserService"> <property name="userDao" ref="usersDAO"></property> </bean> </beans>
当然你也可以不采用xml配置bean,采用注释加载bean,见《Spring3系列7- 自动扫描组件或Bean》、《Spring 开启Annotation <context:annotation-config> 和 <context:component-scan>诠释及区别》
八、 JSP页面和Controller
WEB-INF/user/users.jsp如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h1>Message : ${message}</h1> </body> </html>
写Controller访问上边的jsp
package com.lei.demo.controller; import javax.annotation.Resource; import com.lei.demo.service.*; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/user") public class UserController { @Resource(name="userService") private UserService service; @RequestMapping(value="/manager",method=RequestMethod.GET) public ModelAndView hello2(){ ModelAndView mv = new ModelAndView(); mv.addObject("message", "HelloMVC"); mv.setViewName("users"); return mv; } @RequestMapping(value="/count",method=RequestMethod.GET) public ModelAndView count(){ int c = service.userCount(); ModelAndView mv = new ModelAndView(); mv.addObject("message", c); mv.setViewName("users"); return mv; } }
上边的controller定义了两个路径
http://localhost:8080/spring4-mvc-hibernate4/user/manager
http://localhost:8080/spring4-mvc-hibernate4/user/count
以上两个路径都调用WEB-INF/user/users.jsp
参考资料《Spring3系列13-Controller和@RequestMapping》
九、 运行结果
相关推荐
Spring4 MVC Hibernate4集成,使用Annotation,封装dao层和service层。 环境: spring 4.0.3.RELEASE hibernate 4.3.5.Final mysql 5.1.29
在本实例中,"spring4MVC+Hibernate4实例(增删改查)"是一个基于Maven构建的Java Web项目,旨在演示如何整合Spring MVC和Hibernate框架来实现数据的CRUD(创建、读取、更新和删除)操作。Spring MVC是Spring框架的...
Spring4.0.3,Hibernate4.3.5,mysql。 需要创建users表 DROP TABLE IF EXISTS `users`; CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `age` int(11) DEFAULT NULL, `nice_name` varchar(32) ...
在IT领域,Spring、Spring MVC和Hibernate是三个非常重要的开源框架,它们分别在不同层面上为Java应用程序提供了强大的支持。本整合案例将详细介绍如何将这三个框架整合在一起,以实现一个完整的Web应用程序,涵盖...
在实际项目中,将Spring MVC与Hibernate集成,可以创建出高效、可维护的Web应用。下面我们将详细讨论如何配置Spring MVC和Hibernate。 1. **Spring MVC框架介绍** Spring MVC是Spring框架的一个模块,提供了一个...
《Spring4MVC与Hibernate4入门实战指南...学习并掌握Spring4MVC和Hibernate4的集成,不仅可以提高开发效率,还能增强系统的稳定性和可维护性。在实际开发过程中,不断探索和实践,才能更好地发挥这两个框架的强大功能。
在本项目"SSH - SpringMVC4 + Spring4 + Hibernate4 + c3p0 + Mysql.zip"中,开发者使用了SpringMVC4作为表现层,Spring4作为控制层和服务层,Hibernate4作为持久层,c3p0作为数据库连接池,以及MySQL作为数据库。...
在本文中,我们将深入探讨如何将Spring MVC、Spring和Hibernate这三大流行框架整合在一起,以构建一个完整的登录实例。这个实例旨在提供一个清晰、简洁且易于理解的代码结构,帮助初学者快速上手。 首先,Spring ...
4. Hibernate的配置和实体类的注解,以及如何在Spring中配置SessionFactory和TransactionManager。 5. 整合Spring MVC、Spring和Hibernate,实现数据库操作的自动化。 6. 使用Spring测试框架进行单元测试和集成测试...
3. **集成过程**:将Spring MVC与Hibernate集成,通常需要配置Spring的DataSource、SessionFactory、HibernateTemplate或HibernateDaoSupport,以及事务管理器。这些配置通常在Spring的XML配置文件中完成。 4. **...
例如,Spring如何通过AOP实现事务管理,Spring MVC如何与Spring核心集成以处理HTTP请求,以及Hibernate如何通过ORM将Java对象映射到数据库表。熟悉这些知识后,开发者就能灵活地利用这三个框架构建出高效、稳定的...
Spring,Spring MVC,Hibernate,以及Ehcache是Java开发中常用的四大框架,它们共同构建了高效、稳定的后台应用体系。 Spring框架是Java企业级应用的事实标准,它提供了一个全面的编程和配置模型,用于简化企业级...
在Spring MVC中,我们可以利用Spring的Hibernate支持,将SessionFactory和Transaction管理集成进Spring容器,实现声明式事务管理。 C3P0 是一个开源的JDBC连接池,它实现了数据源和JNDI绑定,提供了一套完善的...
在IT行业中,构建大型、模块化的Java应用时,通常会采用一些成熟的框架组合,例如Spring、Spring MVC和Hibernate。这些框架协同工作,可以提供强大的后端功能,包括依赖注入、模型-视图-控制器(MVC)架构以及对象...
这是一个基于Java技术栈开发的企业级项目,主要使用了Spring MVC、Spring、Hibernate、Bootstrap和Maven等关键组件。下面将详细解析这些技术及其在项目中的作用。 **Spring MVC**: Spring MVC是Spring框架的一个...
标题 "Extjs + Spring MVC + hibernate + mysql" 涉及的是一个综合性的Web应用程序开发框架,结合了前端UI库、后端MVC框架、ORM工具和关系型数据库。让我们详细了解一下这些技术及其在实际项目中的应用。 1. ExtJS...
其次,Spring4是企业级应用的核心框架,它不仅提供了依赖注入(DI)和面向切面编程(AOP),还支持事务管理、数据访问集成、Web应用开发等多个方面。在电子商务系统中,Spring4可以帮助管理对象之间的依赖关系,降低...
通过学习这个项目,你可以了解如何设置IDE、配置项目结构、使用Maven管理依赖、编写Spring配置、设计Spring MVC控制器、集成Hibernate进行数据库操作等。在实际操作中,你可能还会接触到JDBC、模板引擎(如Thymeleaf...
8. **测试**:编写单元测试和集成测试以确保Spring MVC和Hibernate的整合正常工作,可以使用JUnit和Mockito等工具进行测试。 这个"Spring4MVC整合Hibernate5"的示例源码提供了实际的应用场景,帮助开发者理解如何在...
压缩包中的"SpringMVC4.3_Spring4_Hibernate5.1.3配置文件"应该包含了所有必要的配置文件,如Spring的bean定义XML文件、Hibernate的配置文件、Web应用的部署描述符(web.xml)等,以及可能的示例代码和测试用例。...