Spring MVC注解配置结合Hibernate的入门教程及其代码实例

阳光穿透心脏的1/2处 2022-08-22 00:11 341阅读 0赞

原文:Spring MVC注解配置结合Hibernate的入门教程及其代码实例

源代码下载地址:http://www.zuidaima.com/share/1787210045197312.htm

1、概述

本文旨在搭建Spring MVC+Hibernate开发框架,通过一个简单的demo讲解Spring MVC的相关配置文件,以及通过注解方式实现简单功能。

开发框架:Spring+Spring MVC+Hibernate(Spring所用的版本为3.0.5)。

数据库:MySQL(数据库名称test,demo工程所用的表名为user_info)。

2、开发框架搭建

2.1 创建工程

  1. EclipseJava EE版本或MyEclipse中创建一个Dynamic Web Project。并创建如下包:

(1)com.dao:系统的DAO;

(2)com.model:表的实体类(使用Hibernate),在该工程中不配置.hbm.xml映射文件,采取注解的方式;

(3)com.service:业务逻辑接口类和实现类;

(4)com.web:Spring MVC的Controllor类;

(5)com.config:Spring和Spring MVC的配置文件。

创建成功后包结构如下所示:
springmvctest
src
——com
——amigo
——dao
——model
——service
——web
——config
WebContent
——META-INF
——WEB-INF
——lib
——classes

2.2 引入相关包

  1. 需要将SpringSpring MVCHibernateMySQL驱动、log4jc3p0数据源等的相关包引入。lib目录下的jar包如下:
  2. antlr-2.7.6.jar
  3. aopalliance.jar
  4. asm-attrs.jar
  5. asm.jar
  6. c3p0-0.9.0.jar
  7. cglib-2.1.3.jar
  8. commons-beanutils-1.8.0.jar
  9. commons-beanutils-bean-collections-1.8.0.jar
  10. commons-betwixt-0.8.jar
  11. commons-collections-2.1.1.jar
  12. commons-digester-2.1.jar
  13. commons-discovery-0.2.jar
  14. commons-httpclient.jar
  15. commons-logging.jar
  16. dom4j-1.6.1.jar
  17. ehcache-1.2.3.jar
  18. ejb3-persistence.jar
  19. hibernate-annotations.jar
  20. hibernate-commons-annotations.jar
  21. hibernate-entitymanager.jar
  22. hibernate-validator.jar
  23. hibernate3.jar
  24. jaas.jar
  25. javassist.jar
  26. jaxen-1.1-beta-7.jar
  27. jaxrpc.jar
  28. jboss-archive-browsing.jar
  29. jdbc2\_0-stdext.jar
  30. jta.jar
  31. log4j-1.2.11.jar
  32. mysql-connector-java-5.0.4-bin.jar
  33. org.springframework.aop-3.0.5.RELEASE.jar
  34. org.springframework.asm-3.0.5.RELEASE.jar
  35. org.springframework.aspects-3.0.5.RELEASE.jar
  36. org.springframework.beans-3.0.5.RELEASE.jar
  37. org.springframework.context-3.0.5.RELEASE.jar
  38. org.springframework.context.support-3.0.5.RELEASE.jar
  39. org.springframework.core-3.0.5.RELEASE.jar
  40. org.springframework.expression-3.0.5.RELEASE.jar
  41. org.springframework.instrument-3.0.5.RELEASE.jar
  42. org.springframework.instrument.tomcat-3.0.5.RELEASE.jar
  43. org.springframework.jdbc-3.0.5.RELEASE.jar
  44. org.springframework.jms-3.0.5.RELEASE.jar
  45. org.springframework.orm-3.0.5.RELEASE.jar
  46. org.springframework.oxm-3.0.5.RELEASE.jar
  47. org.springframework.test-3.0.5.RELEASE.jar
  48. org.springframework.transaction-3.0.5.RELEASE.jar
  49. org.springframework.web-3.0.5.RELEASE.jar
  50. org.springframework.web.servlet-3.0.5.RELEASE.jar
  51. saaj.jar
  52. wsdl4j.jar
  53. xerces-2.6.2.jar
  54. xml-apis.jar

2.3 配置文件

2.3.1 配置web.xml

  1. web.xml中需要配置Spring的配置文件(applicationContext.xml)和Spring MVC配置文件(spring-mvc.xml),配置指定所有.do的请求都由SpringDispatcherServlet类进行处理。

web.xml文件的参考配置如下:

  1. <?xml version=" 1.0 " encoding=" UTF-8 " ?>
  2. <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/web-app_2_5.xsd " xsi:schemaLocation=" http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd " id=" WebApp_ID " version=" 2.5 ">
  3. <display - name> springmvctest </display - name>
  4. <welcome - file - list>
  5. <welcome - file> index.html </welcome - file>
  6. <welcome - file> index.htm </welcome - file>
  7. <welcome - file> index.jsp </welcome - file>
  8. </welcome - file - list>
  9. <context - param>
  10. <param - name> contextConfigLocation </param - name>
  11. <param - value> classpath:config / applicationContext.xml </param - value>
  12. </context - param>
  13. <listener>
  14. <listener - class> org.springframework.web.context.ContextLoaderListener
  15. </listener - class>
  16. </listener>
  17. <servlet>
  18. <servlet - name> spring - mvc </servlet - name>
  19. <servlet - class> org.springframework.web.servlet.DispatcherServlet </servlet - class>
  20. <init - param>
  21. <param - name> contextConfigLocation </param - name>
  22. <param - value> classpath:config / spring - mvc.xml </param - value>
  23. </init - param>
  24. <load - on - startup> </load - on - startup>
  25. </servlet>
  26. <servlet - mapping>
  27. <servlet - name> spring - mvc </servlet - name>
  28. <url - pattern>* . do </url - pattern>
  29. </servlet - mapping>
  30. <filter>
  31. <filter - name> encodingFilter </filter - name>
  32. <filter - class> org.springframework.web.filter.CharacterEncodingFilter </filter - class>
  33. <init - param>
  34. <param - name> encoding </param - name>
  35. <param - value> UTF - </param - value>
  36. </init - param>
  37. <init - param>
  38. <param - name> forceEncoding </param - name>
  39. <param - value> true </param - value>
  40. </init - param>
  41. </filter>
  42. <filter - mapping>
  43. <filter - name> encodingFilter </filter - name>
  44. <url - pattern> /**/ /*</url-pattern>
  45. </filter-mapping>
  46. </web-app>

2.3.2 配置 spring 的配置文件

Spring的配置文件applicationContext.xml文件中主要配置对Hibernate的事务的管理,该配置文件的参考配置如下:

  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:context=" http://www.springframework.org/schema/context "
  4. xmlns:aop=" http://www.springframework.org/schema/aop "
  5. xmlns:task=" http://www.springframework.org/schema/task "
  6. xsi:schemaLocation="
  7. http: // www.springframework.org/schema/beans
  8. http: // www.springframework.org/schema/beans/spring-beans-3.0.xsd
  9. http: // www.springframework.org/schema/context
  10. http: // www.springframework.org/schema/context/spring-context-3.0.xsd
  11. http: // www.springframework.org/schema/aop
  12. http: // www.springframework.org/schema/aop/spring-aop-3.0.xsd
  13. http: // www.springframework.org/schema/task
  14. http: // www.springframework.org/schema/task/spring-task-3.0.xsd">
  15. <context:annotation - config />
  16. <!-- 扫描annotation类,过滤Service,Repository -->
  17. <context:component - scan base - package=" com.amigo ">
  18. <context:include - filter type=" annotation " expression=" org.springframework.stereotype.Service " />
  19. <context:include - filter type=" annotation " expression=" org.springframework.stereotype.Repository " />
  20. </context:component - scan>
  21. <bean id=" dataSource " class=" com.mchange.v2.c3p0.ComboPooledDataSource " destroy - method=" close ">
  22. <property name=" driverClass ">
  23. <value> com.mysql.jdbc.Driver </value>
  24. </property>
  25. <property name=" jdbcUrl ">
  26. <value> jdbc:mysql: // localhost/test</value>
  27. </property>
  28. <property name=" user ">
  29. <value> root </value>
  30. </property>
  31. <property name=" password ">
  32. <value> 123456 </value>
  33. </property>
  34. <property name=" maxPoolSize ">
  35. <value> </value>
  36. </property>
  37. <property name=" minPoolSize ">
  38. <value> </value>
  39. </property>
  40. <property name=" initialPoolSize ">
  41. <value> </value>
  42. </property>
  43. <property name=" maxIdleTime ">
  44. <value> </value>
  45. </property>
  46. </bean>
  47. <bean id=" sessionFactory " class=" org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean ">
  48. <property name=" dataSource " ref=" dataSource " />
  49. <property name=" packagesToScan " value=" com.amigo.model* "></property>
  50. <property name=" hibernateProperties ">
  51. <props>
  52. <prop key=" hibernate.dialect "> org.hibernate.dialect.MySQLDialect </prop>
  53. <prop key=" show_sql "> true </prop>
  54. <prop key=" hibernate.jdbc.batch_size "> </prop>
  55. </props>
  56. </property>
  57. </bean>
  58. <!-- 不破坏数据库,注册SessionFactory -->
  59. <bean id=" transactionManager " class=" org.springframework.orm.hibernate3.HibernateTransactionManager ">
  60. <property name=" sessionFactory " ref=" sessionFactory "></property>
  61. </bean>
  62. <bean id=" transactionInterceptor "
  63. class=" org.springframework.transaction.interceptor.TransactionInterceptor ">
  64. <property name=" transactionManager " ref=" transactionManager "></property>
  65. <property name=" transactionAttributes ">
  66. <props>
  67. <prop key=" save* "> PROPAGATION_REQUIRED </prop>
  68. <prop key=" update* "> PROPAGATION_REQUIRED </prop>
  69. <prop key=" delete* "> PROPAGATION_REQUIRED </prop>
  70. <prop key=" find* "> PROPAGATION_REQUIRED </prop>
  71. <prop key=" get* "> PROPAGATION_REQUIRED </prop>
  72. <prop key=" execute* "> PROPAGATION_REQUIRED </prop>
  73. <prop key=" load* "> PROPAGATION_REQUIRED </prop>
  74. <prop key=" merge* "> PROPAGATION_REQUIRED </prop>
  75. <prop key=" add* "> PROPAGATION_REQUIRED </prop>
  76. </props>
  77. </property>
  78. </bean>
  79. <bean
  80. class=" org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator ">
  81. <property name=" beanNames ">
  82. <list>
  83. <value>* Service </value>
  84. </list>
  85. </property>
  86. <property name= " interceptorNames ">
  87. <list>
  88. <value> transactionInterceptor </value>
  89. </list>
  90. </property>
  91. </bean>
  92. </beans>

2.3.3 配置 Spring MVC 配置文件

Spring MVC的配置文件spring-mvc.xml中主要是Controller的配置信息,该文件的参考配置如下:

  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:mvc="http://www.springframework.org/schema/mvc"
  6. xsi:schemaLocation="
  7. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  8. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
  9. http://www.springframework.org/schema/mvc
  10. http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"
  11. default-lazy-init="true">
  12. <context:annotation-config />
  13. <!-- 使Spring支持自动检测组件,如注解的Controller -->
  14. <context:component-scan base-package="com.amigo.web"/>
  15. <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
  16. p:prefix="/WEB-INF"
  17. p:suffix=".jsp" />
  18. <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
  19. <!-- 启动 Spring MVC 的注解功能,完成请求和注解 POJO 的映射 -->
  20. <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  21. <property name="messageConverters">
  22. <list>
  23. <bean class="org.springframework.http.converter.StringHttpMessageConverter">
  24. </bean>
  25. </list>
  26. </property>
  27. </bean>
  28. </beans>

2.4 创建数据库和表

创建test数据库和user_info表的SQL语句如下(为了简便,user_info只有一个USER_NAME字段):

  1. CREATE DATABASE test;
  2. USER test;
  3. CREATE TABLE user_info (
  4. USER_NAME varchar ( 32 ) NOT NULL ,
  5. PRIMARY KEY ( USER_NAME )
  6. ) ENGINE=InnoDB DEFAULT CHARSET= utf8;

3、实例代码

3.1 DAO层

BaseHibernateDao类的代码如下所示:

  1. package com.amigo.dao;
  2. import javax.annotation.Resource;
  3. import org.hibernate.HibernateException;
  4. import org.hibernate.Session;
  5. import org.hibernate.SessionFactory;
  6. import org.springframework.dao.DataAccessException;
  7. import org.springframework.dao.DataAccessResourceFailureException;
  8. import org.springframework.dao.support.DaoSupport;
  9. import org.springframework.orm.hibernate3.HibernateTemplate;
  10. import org.springframework.orm.hibernate3.SessionFactoryUtils;
  11. public class BaseHibernateDao extends DaoSupport {
  12. private SessionFactory sessionFactory;
  13. private HibernateTemplate hibernateTemplate;
  14. public SessionFactory getSessionFactory() {
  15. return sessionFactory;
  16. }
  17. @Resource(name="sessionFactory")
  18. public void setSessionFactory(SessionFactory sessionFactory) {
  19. this.sessionFactory=sessionFactory;
  20. this.hibernateTemplate=createHibernateTemplate(sessionFactory);
  21. }
  22. public Session getSession() {
  23. if (this.sessionFactory==null) {
  24. throw new HibernateException("Session Create Fail,SessionFactory is null!");
  25. }
  26. return this.sessionFactory.getCurrentSession();
  27. }
  28. protected HibernateTemplate createHibernateTemplate(
  29. SessionFactory sessionFactory) {
  30. return new HibernateTemplate(sessionFactory);
  31. }
  32. @Override
  33. protected void checkDaoConfig() throws IllegalArgumentException {
  34. if (this.hibernateTemplate==null) {
  35. throw new IllegalArgumentException("'sessionFactory' or 'hibernateTemplate' is required");
  36. }
  37. }
  38. protected final Session getSession(boolean allowCreate)
  39. throws DataAccessResourceFailureException, IllegalStateException {
  40. return (!allowCreate ? SessionFactoryUtils.getSession(
  41. getSessionFactory(), false) : SessionFactoryUtils.getSession(
  42. getSessionFactory(),
  43. this.hibernateTemplate.getEntityInterceptor(), this.hibernateTemplate.getJdbcExceptionTranslator()));
  44. }
  45. protected final DataAccessException convertHibernateAccessException(
  46. HibernateException ex) {
  47. return this.hibernateTemplate.convertHibernateAccessException(ex);
  48. }
  49. protected final void releaseSession(Session session) {
  50. SessionFactoryUtils.releaseSession(session, getSessionFactory());
  51. if(null!=session)session=null;
  52. }
  53. public final void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
  54. this.hibernateTemplate=hibernateTemplate;
  55. }
  56. public final HibernateTemplate getHibernateTemplate() {
  57. return this.hibernateTemplate;
  58. }
  59. }

USER_INFO表的Dao类UserInfoDao类的代码如下所示:

  1. package com.amigo.dao;
  2. import org.springframework.stereotype.Repository;
  3. @Repository
  4. public class UserInfoDao extends BaseHibernateDao {
  5. }

3.2 业务逻辑层

接口类IHelloService的代码如下:

  1. package com.amigo.service;
  2. public interface IHelloService {
  3. public int addUser(String userName) throws Exception;;
  4. }

实现类HelloService类的代码如下:

  1. package com.amigo.service;
  2. import javax.annotation.Resource;
  3. import org.apache.commons.logging.Log;
  4. import org.apache.commons.logging.LogFactory;
  5. import org.springframework.stereotype.Repository;
  6. import org.springframework.stereotype.Service;
  7. import com.amigo.dao.UserInfoDao;
  8. import com.amigo.model.UserInfo;
  9. @Service( " helloService " )
  10. @Repository
  11. public class HelloService implements IHelloService ;
  12. }
  13. }

3.3 控制层

控制类HelloControllor类接收userName参数,并调用相应的Service类将用户名保存到USER_INFO表中,该类的代码如下:

  1. package com.amigo.web;
  2. import javax.annotation.Resource;
  3. import javax.servlet.http.HttpServletRequest;
  4. import javax.servlet.http.HttpServletResponse;
  5. import org.apache.commons.logging.Log;
  6. import org.apache.commons.logging.LogFactory;
  7. import org.springframework.stereotype.Controller;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.ResponseBody;
  10. import com.amigo.service.IHelloService;
  11. @Controller
  12. @RequestMapping( " /test " )
  13. public class HelloControllor {
  14. private static final Log log=LogFactory.getLog(HelloControllor.class);
  15. private IHelloService helloService;
  16. public IHelloService getHelloService() {
  17. return helloService;
  18. }
  19. @Resource
  20. public void setHelloService(IHelloService helloService) {
  21. this.helloService=helloService;
  22. }
  23. @RequestMapping("/hello.do")
  24. public @ResponseBody
  25. String sayHello(HttpServletRequest request, HttpServletResponse response) throws Exception {
  26. request.setCharacterEncoding("UTF-8");
  27. String userName=request.getParameter("userName");
  28. log.info("userName="+ userName);
  29. int resultCode=helloService.addUser(userName);
  30. String rspInfo="你好!" + userName + ",操作结果码="+ resultCode;
  31. response.setHeader("Content-type","text/html;charset=UTF-8");
  32. response.getOutputStream().write(rspInfo.getBytes("UTF-8"));
  33. return "";
  34. }
  35. }

@Controller注解标识一个控制器,@RequestMapping注解标记一个访问的路径;如果@RequestMapping注解在类级别上,则表示一相对路径,在方法级别上,则标记访问路径;

4、测试

测试时可以通过访问http://localhost:8080/springmvctest/test/hello.do?userName=amigo777,通过userName参数将用户名添加到USER_INFO表中。

从实例代码可以看出,POJO、DAO层、Service层和Controller层都是采用注解的方式将service、dao注入的,减少了配置量,方便了开发工作。

发表评论

表情:
评论列表 (有 0 条评论,341人围观)

还没有评论,来说两句吧...

相关阅读