通过注解的方式集成Spring 4 MVC+Hibernate 4+MySQL+Maven,开发项目样例

原文网址

在这个指导中,我们将用基于Spring 的注解的配置来集成Hibernate。我们将开发一个简单的网页,这个网页包含一个表单,接收用户的输入。以实现简单的增删改查。使用hibernate将数据保存到mysql数据库当中。在spring的事务的管理下从数据库当中获取数据并且更新或者删除这些数据。这些功能都是通过注解配置实现的。

 

 测试部分的详情将在下一部分涉及到。我们使用TestNG,mockitospring-testDBUnit & H2 database.进行单元/集成测试。如果你想对TestNG有更多的了解。你可以参考TestNG指南

 接下来将用到这些技术:

 

  • Spring 4.0.6.RELEASE
  • Hibernate Core 4.3.6.Final
  • validation-api 1.1.0.Final
  • hibernate-validator 5.1.3.Final
  • MySQL Server 5.6
  • Maven 3
  • JDK 1.7
  • Tomcat 8.0.21
  • Eclipse JUNO Service Release 2
  • TestNG 6.9.4
  • Mockito 1.10.19
  • DBUnit 2.2
  • H2 Database 1.4.187

开始弄吧!

 

第一步,创建目录框架

一步一步跟着做,最后会形成这样的目录

SpringHibernate_img1

 

让我们现在开始添加上面目录架构中所提到的文本,并且详细说明他们

第二步:更改pom.xml 文件以包含需要的依赖jar包

 

[html] view plain copy
 
  1. <?xml version="1.0"?>  
  2. <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"  
  3.     xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">  
  4.    
  5.     <modelVersion>4.0.0</modelVersion>  
  6.     <groupId>com.websystique.springmvc</groupId>  
  7.     <artifactId>SpringHibernateExample</artifactId>  
  8.     <packaging>war</packaging>  
  9.     <version>1.0.0</version>  
  10.     <name>SpringHibernateExample</name>  
  11.    
  12.     <properties>  
  13.         <springframework.version>4.0.6.RELEASE</springframework.version>  
  14.         <hibernate.version>4.3.6.Final</hibernate.version>  
  15.         <mysql.connector.version>5.1.31</mysql.connector.version>  
  16.         <joda-time.version>2.3</joda-time.version>  
  17.         <testng.version>6.9.4</testng.version>  
  18.         <mockito.version>1.10.19</mockito.version>  
  19.         <h2.version>1.4.187</h2.version>  
  20.         <dbunit.version>2.2</dbunit.version>  
  21.     </properties>  
  22.    
  23.     <dependencies>  
  24.         <!-- Spring -->  
  25.         <dependency>  
  26.             <groupId>org.springframework</groupId>  
  27.             <artifactId>spring-core</artifactId>  
  28.             <version>${springframework.version}</version>  
  29.         </dependency>  
  30.         <dependency>  
  31.             <groupId>org.springframework</groupId>  
  32.             <artifactId>spring-web</artifactId>  
  33.             <version>${springframework.version}</version>  
  34.         </dependency>  
  35.         <dependency>  
  36.             <groupId>org.springframework</groupId>  
  37.             <artifactId>spring-webmvc</artifactId>  
  38.             <version>${springframework.version}</version>  
  39.         </dependency>  
  40.         <dependency>  
  41.             <groupId>org.springframework</groupId>  
  42.             <artifactId>spring-tx</artifactId>  
  43.             <version>${springframework.version}</version>  
  44.         </dependency>  
  45.         <dependency>  
  46.             <groupId>org.springframework</groupId>  
  47.             <artifactId>spring-orm</artifactId>  
  48.             <version>${springframework.version}</version>  
  49.         </dependency>  
  50.    
  51.         <!-- Hibernate -->  
  52.         <dependency>  
  53.             <groupId>org.hibernate</groupId>  
  54.             <artifactId>hibernate-core</artifactId>  
  55.             <version>${hibernate.version}</version>  
  56.         </dependency>  
  57.    
  58.         <!-- jsr303 validation -->  
  59.         <dependency>  
  60.             <groupId>javax.validation</groupId>  
  61.             <artifactId>validation-api</artifactId>  
  62.             <version>1.1.0.Final</version>  
  63.         </dependency>  
  64.         <dependency>  
  65.             <groupId>org.hibernate</groupId>  
  66.             <artifactId>hibernate-validator</artifactId>  
  67.             <version>5.1.3.Final</version>  
  68.         </dependency>  
  69.    
  70.         <!-- MySQL -->  
  71.         <dependency>  
  72.             <groupId>mysql</groupId>  
  73.             <artifactId>mysql-connector-java</artifactId>  
  74.             <version>${mysql.connector.version}</version>  
  75.         </dependency>  
  76.    
  77.         <!-- Joda-Time -->         
  78.         <dependency>  
  79.             <groupId>joda-time</groupId>  
  80.             <artifactId>joda-time</artifactId>  
  81.             <version>${joda-time.version}</version>  
  82.         </dependency>  
  83.            
  84.         <!-- To map JodaTime with database type -->        
  85.         <dependency>  
  86.             <groupId>org.jadira.usertype</groupId>  
  87.             <artifactId>usertype.core</artifactId>  
  88.             <version>3.0.0.CR1</version>  
  89.         </dependency>  
  90.    
  91.         <!-- Servlet+JSP+JSTL -->  
  92.         <dependency>  
  93.             <groupId>javax.servlet</groupId>  
  94.             <artifactId>javax.servlet-api</artifactId>  
  95.             <version>3.1.0</version>  
  96.         </dependency>  
  97.         <dependency>  
  98.             <groupId>javax.servlet.jsp</groupId>  
  99.             <artifactId>javax.servlet.jsp-api</artifactId>  
  100.             <version>2.3.1</version>  
  101.         </dependency>  
  102.         <dependency>  
  103.             <groupId>javax.servlet</groupId>  
  104.             <artifactId>jstl</artifactId>  
  105.             <version>1.2</version>  
  106.         </dependency>  
  107.            
  108.            
  109.         <!-- Testing dependencies -->  
  110.         <dependency>  
  111.             <groupId>org.springframework</groupId>  
  112.             <artifactId>spring-test</artifactId>  
  113.             <version>${springframework.version}</version>  
  114.             <scope>test</scope>  
  115.         </dependency>  
  116.         <dependency>  
  117.             <groupId>org.testng</groupId>  
  118.             <artifactId>testng</artifactId>  
  119.             <version>${testng.version}</version>  
  120.             <scope>test</scope>  
  121.         </dependency>  
  122.         <dependency>  
  123.             <groupId>org.mockito</groupId>  
  124.             <artifactId>mockito-all</artifactId>  
  125.             <version>${mockito.version}</version>  
  126.             <scope>test</scope>  
  127.         </dependency>  
  128.         <dependency>  
  129.             <groupId>com.h2database</groupId>  
  130.             <artifactId>h2</artifactId>  
  131.             <version>${h2.version}</version>  
  132.             <scope>test</scope>  
  133.         </dependency>  
  134.         <dependency>  
  135.             <groupId>dbunit</groupId>  
  136.             <artifactId>dbunit</artifactId>  
  137.             <version>${dbunit.version}</version>  
  138.             <scope>test</scope>  
  139.         </dependency>  
  140.            
  141.     </dependencies>  
  142.    
  143.     <build>  
  144.         <pluginManagement>  
  145.             <plugins>  
  146.                 <plugin>  
  147.                     <groupId>org.apache.maven.plugins</groupId>  
  148.                     <artifactId>maven-war-plugin</artifactId>  
  149.                     <version>2.4</version>  
  150.                     <configuration>  
  151.                         <warSourceDirectory>src/main/webapp</warSourceDirectory>  
  152.                         <warName>SpringHibernateExample</warName>  
  153.                         <failOnMissingWebXml>false</failOnMissingWebXml>  
  154.                     </configuration>  
  155.                 </plugin>  
  156.             </plugins>  
  157.         </pluginManagement>  
  158.         <finalName>SpringHibernateExample</finalName>  
  159.     </build>  
  160. </project>  


第一个要注意的地方是maven的war包插件(maven-war-plugin)的声明,由于我们使用全注解方式进行配置。甚至在我们的工程当中没有包含web.xml文件。所以我们要配置这个插件,以避免maven在构建war包的时候失败。在这个样例工程中,由于使用表单接受用户的输入。所以需要验证用户的输入。这里将选择JSR303 进行验证。所以我们要引入验证接口(validation-api)来说明这种规范。hibernate验证(hibernate-validator)正好是这种规范的一种实现。hibernate验证(hibernate-validator)同时也通过了他特有的注解校验(@Email, @NotEmpty等),这些并不是规范所囊括的。

 

 除这些以外。我们也包含了(JSP/Servlet/Jstl)依赖。在我们代码中使用servelet api和jstl视图的时候需要。总而验证,容器需要包含这些jar包。所以我们在pom.xml文件当中去设置,这样maven才能下载他们。

 

 我们同时也需要测试依赖。测试部分将在下面的章节中讨论。

 剩下的部分是Spring,hibernate和Joda-Time等的依赖了。

第三步:配置hibernate

 com.websystique.springmvc.configuration.HibernateConfiguration

[java] view plain copy
 
  1. package com.websystique.springmvc.configuration;  
  2.    
  3. import java.util.Properties;  
  4.    
  5. import javax.sql.DataSource;  
  6.    
  7. import org.hibernate.SessionFactory;  
  8. import org.springframework.beans.factory.annotation.Autowired;  
  9. import org.springframework.context.annotation.Bean;  
  10. import org.springframework.context.annotation.ComponentScan;  
  11. import org.springframework.context.annotation.Configuration;  
  12. import org.springframework.context.annotation.PropertySource;  
  13. import org.springframework.core.env.Environment;  
  14. import org.springframework.jdbc.datasource.DriverManagerDataSource;  
  15. import org.springframework.orm.hibernate4.HibernateTransactionManager;  
  16. import org.springframework.orm.hibernate4.LocalSessionFactoryBean;  
  17. import org.springframework.transaction.annotation.EnableTransactionManagement;  
  18.    
  19. @Configuration  
  20. @EnableTransactionManagement  
  21. @ComponentScan({ "com.websystique.springmvc.configuration" })  
  22. @PropertySource(value = { "classpath:application.properties" })  
  23. public class HibernateConfiguration {  
  24.    
  25.     @Autowired  
  26.     private Environment environment;  
  27.    
  28.     @Bean  
  29.     public LocalSessionFactoryBean sessionFactory() {  
  30.         LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();  
  31.         sessionFactory.setDataSource(dataSource());  
  32.         sessionFactory.setPackagesToScan(new String[] { "com.websystique.springmvc.model" });  
  33.         sessionFactory.setHibernateProperties(hibernateProperties());  
  34.         return sessionFactory;  
  35.      }  
  36.        
  37.     @Bean  
  38.     public DataSource dataSource() {  
  39.         DriverManagerDataSource dataSource = new DriverManagerDataSource();  
  40.         dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));  
  41.         dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));  
  42.         dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));  
  43.         dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));  
  44.         return dataSource;  
  45.     }  
  46.        
  47.     private Properties hibernateProperties() {  
  48.         Properties properties = new Properties();  
  49.         properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));  
  50.         properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));  
  51.         properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));  
  52.         return properties;          
  53.     }  
  54.        
  55.     @Bean  
  56.     @Autowired  
  57.     public HibernateTransactionManager transactionManager(SessionFactory s) {  
  58.        HibernateTransactionManager txManager = new HibernateTransactionManager();  
  59.        txManager.setSessionFactory(s);  
  60.        return txManager;  
  61.     }  
  62. }  
@Configuration 注解表示这个类包含一个或多个使用了 @Bean 注解了的方法。将被spring容器所管理以产生beans。在这里。这个类代表
hibernate配置。
@ComponentScan 注解等同于XML配置文件中的context:component-scan base-package="..." 声明。用它来表示去哪里查找spring管理的beans/classes
@EnableTransactionManagement  注解等同于SpringXMl中的tx:*命名空间声明。它将启用Spring注解驱动的事务管理功能。
@PropertySource注解用于声明一组属性(在程序的classpath路径下的properties文件中定义),在spring运行环境下。通过他可以在不同运行环境下进行变更以提供不同的值。
方法sessionFactory() 将创建LocalSessionFactoryBean。以映射其他的配置:我们需要数据源和hibernate属性文件配置(就像hibernate.properties文件)。由于@PropertySource注解提供的便利。我们可以在properties文件中提供具体的值。通过spring运行环境来提取这些值以替换那些占位的变量。一旦SessionFactory创建。他将被注入事务管理(transactionManager)的bean方法中。最终可能对sessionFactory所创建的sesstions提供事务支持。
 
接下来是上面要用到的属性文件
/src/main/resources/application.properties
[javascript] view plain copy
 
  1. jdbc.driverClassName = com.mysql.jdbc.Driver  
  2. jdbc.url = jdbc:mysql://localhost:3306/websystique  
  3. jdbc.username = myuser  
  4. jdbc.password = mypassword  
  5. hibernate.dialect = org.hibernate.dialect.MySQLDialect  
  6. hibernate.show_sql = true  
  7. hibernate.format_sql = true  


第4步:配置Spring MVC

 

com.websystique.springmvc.configuration.AppConfig

 

[java] view plain copy
 
  1. package com.websystique.springmvc.configuration;  
  2.    
  3. import org.springframework.context.MessageSource;  
  4. import org.springframework.context.annotation.Bean;  
  5. import org.springframework.context.annotation.ComponentScan;  
  6. import org.springframework.context.annotation.Configuration;  
  7. import org.springframework.context.support.ResourceBundleMessageSource;  
  8. import org.springframework.web.servlet.ViewResolver;  
  9. import org.springframework.web.servlet.config.annotation.EnableWebMvc;  
  10. import org.springframework.web.servlet.view.InternalResourceViewResolver;  
  11. import org.springframework.web.servlet.view.JstlView;  
  12.    
  13. @Configuration  
  14. @EnableWebMvc  
  15. @ComponentScan(basePackages = "com.websystique.springmvc")  
  16. public class AppConfig {  
  17.        
  18.     @Bean  
  19.     public ViewResolver viewResolver() {  
  20.         InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();  
  21.         viewResolver.setViewClass(JstlView.class);  
  22.         viewResolver.setPrefix("/WEB-INF/views/");  
  23.         viewResolver.setSuffix(".jsp");  
  24.         return viewResolver;  
  25.     }  
  26.        
  27.     @Bean  
  28.     public MessageSource messageSource() {  
  29.         ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();  
  30.         messageSource.setBasename("messages");  
  31.         return messageSource;  
  32.     }  
  33. }  

 

 

再次强调,@Configuration注解标示着这个类被配置后的作用,就像上面提到的那样(表示这个类包含一个或多个使用了 @Bean 注解了的方法。将被spring容器所管理以产生beans。),同时@ComponentScan注解指出了可以在这些包路径下找到相关联的beans类。

@EnableWebMvc注解相当于XML文件中的mvc:annotation-driven(启用web的MVC控制)。方法viewResolver配置了一个视图解析器。以定位到具体的视图页面。

在这篇文章中,我们使用表单进行提交,通过JSR303规范验证用户的输入。在验证失败的情况下,默认的错误信息将显示。你可以通过国际化的方式在其他消息绑定文件(以.properties结尾的文件)中定义适用于你语言环境的消息。在basename方法中。spring会程序运行的class路径中检索一个叫messages.properties的文件。让我们添加这个文件吧:

/src/main/resources/messages.properties

 

[html] view plain copy
 
  1. Size.employee.name=Name must be between {2} and {1} characters long  
  2. NotNull.employee.joiningDate=Joining Date can not be blank  
  3. NotNull.employee.salary=Salary can not be blank  
  4. Digits.employee.salary=Only numeric data with max 8 digits and with max 2 precision is allowed  
  5. NotEmpty.employee.ssn=SSN can not be blank  
  6. typeMismatch=Invalid format  
  7. non.unique.ssn=SSN {0} already exist. Please fill in different value.  

 

 

请注意上面的消息采用了下面的规范格式

 

{ValidationAnnotationClass}.{modelObject}.{fieldName}

{验证注解类名}.{模块对象名}.{字段名}

 

此外,基于特定的注解(例如@Size)你甚至可以通过使用{0},{1},..{i}占位索引的方式来传递参数。

 第五步:配置初始化类

com.websystique.springmvc.configuration.AppInitializer

 

[java] view plain copy
 
  1. package com.websystique.springmvc.configuration;  
  2.    
  3. import javax.servlet.ServletContext;  
  4. import javax.servlet.ServletException;  
  5. import javax.servlet.ServletRegistration;  
  6.    
  7. import org.springframework.web.WebApplicationInitializer;  
  8. import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;  
  9. import org.springframework.web.servlet.DispatcherServlet;  
  10.    
  11. public class AppInitializer implements WebApplicationInitializer {  
  12.    
  13.     public void onStartup(ServletContext container) throws ServletException {  
  14.    
  15.         AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();  
  16.         ctx.register(AppConfig.class);  
  17.         ctx.setServletContext(container);  
  18.    
  19.         ServletRegistration.Dynamic servlet = container.addServlet(  
  20.                 "dispatcher", new DispatcherServlet(ctx));  
  21.    
  22.         servlet.setLoadOnStartup(1);  
  23.         servlet.addMapping("/");  
  24.     }  
  25.    
  26. }  



 

上面的代码类似于web.xml文件的内容。由于我们使用了前端控制器(DispatherServler),分配这些映射(就像xml文件中的url-pattern那样)。通过上面的方法,我们就不用在spring-servlet.xml文件中去配置路径了。这里我们注册了这个配置类。

 

更新:注意上面的类可以写得更简洁(而且是更好的方式)。通过继承AbstractAnnotationConfigDispatcherServletInitializer这个父类。就像下面这样:

 

[java] view plain copy
 
  1. package com.websystique.springmvc.configuration;  
  2.    
  3. import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;  
  4.    
  5. public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {  
  6.    
  7.     @Override  
  8.     protected Class<?>[] getRootConfigClasses() {  
  9.         return new Class[] { AppConfig.class };  
  10.     }  
  11.     
  12.     @Override  
  13.     protected Class<?>[] getServletConfigClasses() {  
  14.         return null;  
  15.     }  
  16.     
  17.     @Override  
  18.     protected String[] getServletMappings() {  
  19.         return new String[] { "/" };  
  20.     }  
  21.    
  22. }  

 

 

第六步:添加控制器以处理请求

添加这个控制器,可以对get和post请求提供服务。

com.websystique.springmvc.controller.AppController

 

[java] view plain copy
 
  1. package com.websystique.springmvc.controller;  
  2.    
  3. import java.util.List;  
  4. import java.util.Locale;  
  5.    
  6. import javax.validation.Valid;  
  7.    
  8. import org.springframework.beans.factory.annotation.Autowired;  
  9. import org.springframework.context.MessageSource;  
  10. import org.springframework.stereotype.Controller;  
  11. import org.springframework.ui.ModelMap;  
  12. import org.springframework.validation.BindingResult;  
  13. import org.springframework.validation.FieldError;  
  14. import org.springframework.web.bind.annotation.PathVariable;  
  15. import org.springframework.web.bind.annotation.RequestMapping;  
  16. import org.springframework.web.bind.annotation.RequestMethod;  
  17.    
  18. import com.websystique.springmvc.model.Employee;  
  19. import com.websystique.springmvc.service.EmployeeService;  
  20.    
  21. @Controller  
  22. @RequestMapping("/")  
  23. public class AppController {  
  24.    
  25.     @Autowired  
  26.     EmployeeService service;  
  27.        
  28.     @Autowired  
  29.     MessageSource messageSource;  
  30.    
  31.     /* 
  32.      * This method will list all existing employees. 
  33.      */  
  34.     @RequestMapping(value = { "/", "/list" }, method = RequestMethod.GET)  
  35.     public String listEmployees(ModelMap model) {  
  36.    
  37.         List<Employee> employees = service.findAllEmployees();  
  38.         model.addAttribute("employees", employees);  
  39.         return "allemployees";  
  40.     }  
  41.    
  42.     /* 
  43.      * This method will provide the medium to add a new employee. 
  44.      */  
  45.     @RequestMapping(value = { "/new" }, method = RequestMethod.GET)  
  46.     public String newEmployee(ModelMap model) {  
  47.         Employee employee = new Employee();  
  48.         model.addAttribute("employee", employee);  
  49.         model.addAttribute("edit", false);  
  50.         return "registration";  
  51.     }  
  52.    
  53.     /* 
  54.      * This method will be called on form submission, handling POST request for 
  55.      * saving employee in database. It also validates the user input 
  56.      */  
  57.     @RequestMapping(value = { "/new" }, method = RequestMethod.POST)  
  58.     public String saveEmployee(@Valid Employee employee, BindingResult result,  
  59.             ModelMap model) {  
  60.    
  61.         if (result.hasErrors()) {  
  62.             return "registration";  
  63.         }  
  64.    
  65.         /* 
  66.          * Preferred way to achieve uniqueness of field [ssn] should be implementing custom @Unique annotation  
  67.          * and applying it on field [ssn] of Model class [Employee]. 
  68.          *  
  69.          * Below mentioned peace of code [if block] is to demonstrate that you can fill custom errors outside the validation 
  70.          * framework as well while still using internationalized messages. 
  71.          *  
  72.          */  
  73.         if(!service.isEmployeeSsnUnique(employee.getId(), employee.getSsn())){  
  74.             FieldError ssnError =new FieldError("employee","ssn",messageSource.getMessage("non.unique.ssn", new String[]{employee.getSsn()}, Locale.getDefault()));  
  75.             result.addError(ssnError);  
  76.             return "registration";  
  77.         }  
  78.            
  79.         service.saveEmployee(employee);  
  80.    
  81.         model.addAttribute("success", "Employee " + employee.getName() + " registered successfully");  
  82.         return "success";  
  83.     }  
  84.    
  85.    
  86.     /* 
  87.      * This method will provide the medium to update an existing employee. 
  88.      */  
  89.     @RequestMapping(value = { "/edit-{ssn}-employee" }, method = RequestMethod.GET)  
  90.     public String editEmployee(@PathVariable String ssn, ModelMap model) {  
  91.         Employee employee = service.findEmployeeBySsn(ssn);  
  92.         model.addAttribute("employee", employee);  
  93.         model.addAttribute("edit", true);  
  94.         return "registration";  
  95.     }  
  96.        
  97.     /* 
  98.      * This method will be called on form submission, handling POST request for 
  99.      * updating employee in database. It also validates the user input 
  100.      */  
  101.     @RequestMapping(value = { "/edit-{ssn}-employee" }, method = RequestMethod.POST)  
  102.     public String updateEmployee(@Valid Employee employee, BindingResult result,  
  103.             ModelMap model, @PathVariable String ssn) {  
  104.    
  105.         if (result.hasErrors()) {  
  106.             return "registration";  
  107.         }  
  108.    
  109.         if(!service.isEmployeeSsnUnique(employee.getId(), employee.getSsn())){  
  110.             FieldError ssnError =new FieldError("employee","ssn",messageSource.getMessage("non.unique.ssn", new String[]{employee.getSsn()}, Locale.getDefault()));  
  111.             result.addError(ssnError);  
  112.             return "registration";  
  113.         }  
  114.    
  115.         service.updateEmployee(employee);  
  116.    
  117.         model.addAttribute("success", "Employee " + employee.getName()  + " updated successfully");  
  118.         return "success";  
  119.     }  
  120.    
  121.        
  122.     /* 
  123.      * This method will delete an employee by it's SSN value. 
  124.      */  
  125.     @RequestMapping(value = { "/delete-{ssn}-employee" }, method = RequestMethod.GET)  
  126.     public String deleteEmployee(@PathVariable String ssn) {  
  127.         service.deleteEmployeeBySsn(ssn);  
  128.         return "redirect:/list";  
  129.     }  
  130.    
  131. }  

 

 

Spring 有一个非常漂亮和直接的控制注解:@Controller。这个注解表明这个类是用来处理请求的控制类。通过注解@RequestMapping提供将要处理的请求URL路径。这里我们配置的是根目录'/'。它将作为默认的控制器。

方法listEmployees,被@RequestMethod.GET所注解。将处理来自'/'和'/list'的请求。它接管了程序初始化页面的处理,并响应所有存在的员工列表。

 

 方法newEmployee 处理来着新员工注册页面的请求。显示页面由一个Employee对象模型。

 方法saveEmployee 被@RequestMethod.POST所注解。它将处理表单提交的post请求(在进行新员工注册的时候,提交请求道url路径:/new)。注意这个方法的参数和这些参数在方法中的顺序。@Valid 注解将要求spring去验证这些关联的对象(Employee)。参数 BindingResult包含了这个验证的结果和任何在验证过程中报出的错误信息。请注意这个参数 BindingResult 必须紧跟在被验证的对象之后。否则spring无法进行验证并且有异常被抛出。在验证出错的情况下。响应的错误消息将会显示(我们在第4步配置的那些消息)。

 我们同时也包含了对SSN唯一性进行核对的校验。因为他在数据库中被声明为唯一的。在保存和更新一个员工之前。我们要核对这个SSN是否是唯一的。如果不是。我们将生成校验错误的信息并且重定向到注册页面。这段代码演示了在校验框架之外填写客户错误信息的情况,不过还是用message.properties文件中配置的信息(你可以通过国际化的方式进行定制)。

 方法editEmployee 将定位到注册页面,并把员工的详细信息填充 到页面的控件当中。在你点击页面的更新按钮进行更新而出发的更新员工资料请求的时候。

 方法deleteEmployee 处理根据员工SSN值删除员工数据的请求。注意@PathVariable注解,他表示这个参数将被在uri模板中绑定(我们这里就是SSN的值)

 随着基于注释的配置,这是我们需要做的。为了进一步完善程序。我们添加服务层,dao层。视图层。领域对象层和一个简单的数据库模式。最后运行这个程序吧。

 第7步:添加DAO层

 com.websystique.springmvc.dao.AbstractDao

 
[java] view plain copy
 
  1. package com.websystique.springmvc.dao;  
  2.    
  3. import java.io.Serializable;  
  4.    
  5. import java.lang.reflect.ParameterizedType;  
  6.    
  7. import org.hibernate.Criteria;  
  8. import org.hibernate.Session;  
  9. import org.hibernate.SessionFactory;  
  10. import org.springframework.beans.factory.annotation.Autowired;  
  11.    
  12. public abstract class AbstractDao<PK extends Serializable, T> {  
  13.        
  14.     private final Class<T> persistentClass;  
  15.        
  16.     @SuppressWarnings("unchecked")  
  17.     public AbstractDao(){  
  18.         this.persistentClass =(Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1];  
  19.     }  
  20.        
  21.     @Autowired  
  22.     private SessionFactory sessionFactory;  
  23.    
  24.     protected Session getSession(){  
  25.         return sessionFactory.getCurrentSession();  
  26.     }  
  27.    
  28.     @SuppressWarnings("unchecked")  
  29.     public T getByKey(PK key) {  
  30.         return (T) getSession().get(persistentClass, key);  
  31.     }  
  32.    
  33.     public void persist(T entity) {  
  34.         getSession().persist(entity);  
  35.     }  
  36.    
  37.     public void delete(T entity) {  
  38.         getSession().delete(entity);  
  39.     }  
  40.        
  41.     protected Criteria createEntityCriteria(){  
  42.         return getSession().createCriteria(persistentClass);  
  43.     }  
  44.    
  45. }  

这个泛型抽象类是所有DAO实现类的父类。它提供了所有hibernate操作的通用方法。请注意上面。我们在第3步创建的SessionFactory对象将会被Spring容器自动装载。

 

 com.websystique.springmvc.dao.EmployeeDao
[java] view plain copy
 
  1. package com.websystique.springmvc.dao;  
  2.    
  3. import java.util.List;  
  4.    
  5. import com.websystique.springmvc.model.Employee;  
  6.    
  7. public interface EmployeeDao {  
  8.    
  9.     Employee findById(int id);  
  10.    
  11.     void saveEmployee(Employee employee);  
  12.        
  13.     void deleteEmployeeBySsn(String ssn);  
  14.        
  15.     List<Employee> findAllEmployees();  
  16.    
  17.     Employee findEmployeeBySsn(String ssn);  
  18.    
  19. }  


com.websystique.springmvc.dao.EmployeeDaoImpl

 

[java] view plain copy
 
  1. package com.websystique.springmvc.dao;  
  2.    
  3. import java.util.List;  
  4.    
  5. import org.hibernate.Criteria;  
  6. import org.hibernate.Query;  
  7. import org.hibernate.criterion.Restrictions;  
  8. import org.springframework.stereotype.Repository;  
  9.    
  10. import com.websystique.springmvc.model.Employee;  
  11.    
  12. @Repository("employeeDao")  
  13. public class EmployeeDaoImpl extends AbstractDao<Integer, Employee> implements EmployeeDao {  
  14.    
  15.     public Employee findById(int id) {  
  16.         return getByKey(id);  
  17.     }  
  18.    
  19.     public void saveEmployee(Employee employee) {  
  20.         persist(employee);  
  21.     }  
  22.    
  23.     public void deleteEmployeeBySsn(String ssn) {  
  24.         Query query = getSession().createSQLQuery("delete from Employee where ssn = :ssn");  
  25.         query.setString("ssn", ssn);  
  26.         query.executeUpdate();  
  27.     }  
  28.    
  29.     @SuppressWarnings("unchecked")  
  30.     public List<Employee> findAllEmployees() {  
  31.         Criteria criteria = createEntityCriteria();  
  32.         return (List<Employee>) criteria.list();  
  33.     }  
  34.    
  35.     public Employee findEmployeeBySsn(String ssn) {  
  36.         Criteria criteria = createEntityCriteria();  
  37.         criteria.add(Restrictions.eq("ssn", ssn));  
  38.         return (Employee) criteria.uniqueResult();  
  39.     }  
  40. }  

第八步:添加服务层

 

com.websystique.springmvc.service.EmployeeService

 

[java] view plain copy
 
  1. package com.websystique.springmvc.service;  
  2.    
  3. import java.util.List;  
  4.    
  5. import com.websystique.springmvc.model.Employee;  
  6.    
  7. public interface EmployeeService {  
  8.    
  9.     Employee findById(int id);  
  10.        
  11.     void saveEmployee(Employee employee);  
  12.        
  13.     void updateEmployee(Employee employee);  
  14.        
  15.     void deleteEmployeeBySsn(String ssn);  
  16.    
  17.     List<Employee> findAllEmployees();   
  18.        
  19.     Employee findEmployeeBySsn(String ssn);  
  20.    
  21.     boolean isEmployeeSsnUnique(Integer id, String ssn);  
  22.        
  23. }  


com.websystique.springmvc.service.EmployeeServiceImpl

 

 

[java] view plain copy
 
  1. package com.websystique.springmvc.service;  
  2.    
  3. import java.util.List;  
  4.    
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6. import org.springframework.stereotype.Service;  
  7. import org.springframework.transaction.annotation.Transactional;  
  8.    
  9. import com.websystique.springmvc.dao.EmployeeDao;  
  10. import com.websystique.springmvc.model.Employee;  
  11.    
  12. @Service("employeeService")  
  13. @Transactional  
  14. public class EmployeeServiceImpl implements EmployeeService {  
  15.    
  16.     @Autowired  
  17.     private EmployeeDao dao;  
  18.        
  19.     public Employee findById(int id) {  
  20.         return dao.findById(id);  
  21.     }  
  22.    
  23.     public void saveEmployee(Employee employee) {  
  24.         dao.saveEmployee(employee);  
  25.     }  
  26.    
  27.     /* 
  28.      * Since the method is running with Transaction, No need to call hibernate update explicitly. 
  29.      * Just fetch the entity from db and update it with proper values within transaction. 
  30.      * It will be updated in db once transaction ends.  
  31.      */  
  32.     public void updateEmployee(Employee employee) {  
  33.         Employee entity = dao.findById(employee.getId());  
  34.         if(entity!=null){  
  35.             entity.setName(employee.getName());  
  36.             entity.setJoiningDate(employee.getJoiningDate());  
  37.             entity.setSalary(employee.getSalary());  
  38.             entity.setSsn(employee.getSsn());  
  39.         }  
  40.     }  
  41.    
  42.     public void deleteEmployeeBySsn(String ssn) {  
  43.         dao.deleteEmployeeBySsn(ssn);  
  44.     }  
  45.        
  46.     public List<Employee> findAllEmployees() {  
  47.         return dao.findAllEmployees();  
  48.     }  
  49.    
  50.     public Employee findEmployeeBySsn(String ssn) {  
  51.         return dao.findEmployeeBySsn(ssn);  
  52.     }  
  53.    
  54.     public boolean isEmployeeSsnUnique(Integer id, String ssn) {  
  55.         Employee employee = findEmployeeBySsn(ssn);  
  56.         return ( employee == null || ((id != null) && (employee.getId() == id)));  
  57.     }  
  58.        
  59. }  

 

上面最有意思的地方就是 @Transactional注解了。它将在每个方法调用的时候开启事务。在每个方法结束的时候提交事务(或者在方法执行失败并产生错误的时候回滚他)。请注意,由于transaction注解是基于方法领域的。在方法里面我们使用DAO对象。dao方法将在同一个事务当中执行。

 第九步:创建领域对象(普通的java bean对象)

让我们创建这个实际的雇员实体对象。在数据里面有一张与之对应的。这个对象用于实例化这些数据。

 com.websystique.springmvc.model.Employee

 

[java] view plain copy
 
  1. package com.websystique.springmvc.model;  
  2.    
  3. import java.math.BigDecimal;  
  4.    
  5. import javax.persistence.Column;  
  6. import javax.persistence.Entity;  
  7. import javax.persistence.GeneratedValue;  
  8. import javax.persistence.GenerationType;  
  9. import javax.persistence.Id;  
  10. import javax.persistence.Table;  
  11. import javax.validation.constraints.Digits;  
  12. import javax.validation.constraints.NotNull;  
  13. import javax.validation.constraints.Size;  
  14.    
  15. import org.hibernate.annotations.Type;  
  16. import org.hibernate.validator.constraints.NotEmpty;  
  17. import org.joda.time.LocalDate;  
  18. import org.springframework.format.annotation.DateTimeFormat;  
  19.    
  20. @Entity  
  21. @Table(name="EMPLOYEE")  
  22. public class Employee {  
  23.    
  24.     @Id  
  25.     @GeneratedValue(strategy = GenerationType.IDENTITY)  
  26.     private int id;  
  27.    
  28.     @Size(min=3, max=50)  
  29.     @Column(name = "NAME", nullable = false)  
  30.     private String name;  
  31.    
  32.     @NotNull  
  33.     @DateTimeFormat(pattern="dd/MM/yyyy")   
  34.     @Column(name = "JOINING_DATE", nullable = false)  
  35.     @Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDate")  
  36.     private LocalDate joiningDate;  
  37.    
  38.     @NotNull  
  39.     @Digits(integer=8, fraction=2)  
  40.     @Column(name = "SALARY", nullable = false)  
  41.     private BigDecimal salary;  
  42.        
  43.     @NotEmpty  
  44.     @Column(name = "SSN", unique=true, nullable = false)  
  45.     private String ssn;  
  46.    
  47.     public int getId() {  
  48.         return id;  
  49.     }  
  50.    
  51.     public void setId(int id) {  
  52.         this.id = id;  
  53.     }  
  54.    
  55.     public String getName() {  
  56.         return name;  
  57.     }  
  58.    
  59.     public void setName(String name) {  
  60.         this.name = name;  
  61.     }  
  62.    
  63.     public LocalDate getJoiningDate() {  
  64.         return joiningDate;  
  65.     }  
  66.    
  67.     public void setJoiningDate(LocalDate joiningDate) {  
  68.         this.joiningDate = joiningDate;  
  69.     }  
  70.    
  71.     public BigDecimal getSalary() {  
  72.         return salary;  
  73.     }  
  74.    
  75.     public void setSalary(BigDecimal salary) {  
  76.         this.salary = salary;  
  77.     }  
  78.    
  79.     public String getSsn() {  
  80.         return ssn;  
  81.     }  
  82.    
  83.     public void setSsn(String ssn) {  
  84.         this.ssn = ssn;  
  85.     }  
  86.    
  87.     @Override  
  88.     public int hashCode() {  
  89.         final int prime = 31;  
  90.         int result = 1;  
  91.         result = prime * result + id;  
  92.         result = prime * result + ((ssn == null) ? 0 : ssn.hashCode());  
  93.         return result;  
  94.     }  
  95.    
  96.     @Override  
  97.     public boolean equals(Object obj) {  
  98.         if (this == obj)  
  99.             return true;  
  100.         if (obj == null)  
  101.             return false;  
  102.         if (!(obj instanceof Employee))  
  103.             return false;  
  104.         Employee other = (Employee) obj;  
  105.         if (id != other.id)  
  106.             return false;  
  107.         if (ssn == null) {  
  108.             if (other.ssn != null)  
  109.                 return false;  
  110.         } else if (!ssn.equals(other.ssn))  
  111.             return false;  
  112.         return true;  
  113.     }  
  114.    
  115.     @Override  
  116.     public String toString() {  
  117.         return "Employee [id=" + id + ", name=" + name + ", joiningDate="  
  118.                 + joiningDate + ", salary=" + salary + ", ssn=" + ssn + "]";  
  119.     }  
  120.        
  121. }  
  122.    

这是一个标准的java实体类。被JPA的注解 @Entity@Table@Column  和hibernate 特有的注解  @Type 所标注(我们将是通过他来映射Joda-Time的LocalDate对象和数据库的date type)。@DateTimeFormat是spring所特有的注解,用于声明一个字段应该被给定的时间格式来格式化。余下的注解是JSR303相关的验证。回调第四步我们已经配置好的属性文件(messages.properties)。在验证失败的情况下提供相应的消息。

 

 

 第十步:添加JSP视图

WEB-INF/views/allemployees.jsp [ 主页包含所有已经存在的员工]

[java] view plain copy
 
  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
  2.     pageEncoding="ISO-8859-1"%>  
  3. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
  4. <html>  
  5. <head>  
  6.     <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
  7.     <title>University Enrollments</title>  
  8.    
  9.     <style>  
  10.         tr:first-child{  
  11.             font-weight: bold;  
  12.             background-color: #C6C9C4;  
  13.         }  
  14.     </style>  
  15.    
  16. </head>  
  17.    
  18.    
  19. <body>  
  20.     <h2>List of Employees</h2>    
  21.     <table>  
  22.         <tr>  
  23.             <td>NAME</td><td>Joining Date</td><td>Salary</td><td>SSN</td><td></td>  
  24.         </tr>  
  25.         <c:forEach items="${employees}" var="employee">  
  26.             <tr>  
  27.             <td>${employee.name}</td>  
  28.             <td>${employee.joiningDate}</td>  
  29.             <td>${employee.salary}</td>  
  30.             <td><a href="<c:url value='/edit-${employee.ssn}-employee' />">${employee.ssn}</a></td>  
  31.             <td><a href="<c:url value='/delete-${employee.ssn}-employee' />">delete</a></td>  
  32.             </tr>  
  33.         </c:forEach>  
  34.     </table>  
  35.     <br/>  
  36.     <a href="<c:url value='/new' />">Add New Employee</a>  
  37. </body>  
  38. </html>  


WEB-INF/views/registration.jsp [注册页面用来创建和保存员工信息到数据库]

 

[html] view plain copy
 
  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
  2.     pageEncoding="ISO-8859-1"%>  
  3. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>  
  4. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
  5.    
  6. <html>  
  7.    
  8. <head>  
  9.     <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
  10.     <title>Employee Registration Form</title>  
  11.    
  12. <style>  
  13.    
  14.     .error {  
  15.         color: #ff0000;  
  16.     }  
  17. </style>  
  18.    
  19. </head>  
  20.    
  21. <body>  
  22.    
  23.     <h2>Registration Form</h2>  
  24.     
  25.     <form:form method="POST" modelAttribute="employee">  
  26.         <form:input type="hidden" path="id" id="id"/>  
  27.         <table>  
  28.             <tr>  
  29.                 <td><label for="name">Name: </label</td>  
  30.                 <td><form:input path="name" id="name"/></td>  
  31.                 <td><form:errors path="name" cssClass="error"/></td>  
  32.             </tr>  
  33.            
  34.             <tr>  
  35.                 <td><label for="joiningDate">Joining Date: </label</td>  
  36.                 <td><form:input path="joiningDate" id="joiningDate"/></td>  
  37.                 <td><form:errors path="joiningDate" cssClass="error"/></td>  
  38.             </tr>  
  39.        
  40.             <tr>  
  41.                 <td><label for="salary">Salary: </label</td>  
  42.                 <td><form:input path="salary" id="salary"/></td>  
  43.                 <td><form:errors path="salary" cssClass="error"/></td>  
  44.             </tr>  
  45.        
  46.             <tr>  
  47.                 <td><label for="ssn">SSN: </label</td>  
  48.                 <td><form:input path="ssn" id="ssn"/></td>  
  49.                 <td><form:errors path="ssn" cssClass="error"/></td>  
  50.             </tr>  
  51.        
  52.             <tr>  
  53.                 <td colspan="3">  
  54.                     <c:choose>  
  55.                         <c:when test="${edit}">  
  56.                             <input type="submit" value="Update"/>  
  57.                         </c:when>  
  58.                         <c:otherwise>  
  59.                             <input type="submit" value="Register"/>  
  60.                         </c:otherwise>  
  61.                     </c:choose>  
  62.                 </td>  
  63.             </tr>  
  64.         </table>  
  65.     </form:form>  
  66.     <br/>  
  67.     <br/>  
  68.     Go back to <href="<c:url value='/list' />">List of All Employees</a>  
  69. </body>  
  70. </html>  

 

 

WEB-INF/views/success.jsp [成功页面包含新员工创建成功的确认信息并重定向到员工列表页面]

 

[html] view plain copy
 
  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
  2.     pageEncoding="ISO-8859-1"%>  
  3. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
  4.    
  5. <html>  
  6. <head>  
  7. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
  8. <title>Registration Confirmation Page</title>  
  9. </head>  
  10. <body>  
  11.     message : ${success}  
  12.     <br/>  
  13.     <br/>  
  14.     Go back to <href="<c:url value='/list' />">List of All Employees</a>  
  15.        
  16. </body>  
  17.    
  18. </html>  


第十一步:创建数据表

 

 

[sql] view plain copy
 
  1. CREATE TABLE EMPLOYEE(  
  2.     id INT NOT NULL auto_increment,   
  3.     name VARCHAR(50) NOT NULL,  
  4.     joining_date DATE NOT NULL,  
  5.     salary DOUBLE NOT NULL,  
  6.     ssn VARCHAR(30) NOT NULL UNIQUE,  
  7.     PRIMARY KEY (id)  
  8. );  


第十二步:创建,部署和运行程序

 

 

 现在开始打war包(既可以通过eclipse) 或者通过maven命令行(mvn clean install).将war包部署到servlet3.0容器当中。由于这里我使用的是tomcat容器。我就直接将war包放在tomcat的webapps文件夹下。并点击start.bat脚本启动tomcat(在tomcat的bin目录下面)。

 打开浏览器输入网址:http://localhost:8080/SpringHibernateExample/

 

 

 

 

 
SpringHibernate_img6

 

SpringHibernate_img7

 

SpringHibernate_img8
 

SpringHibernate_img9
 

SpringHibernate_img10

 
SpringHibernate_img11

 

SpringHibernate_img12

 

SpringHibernate_img13

posted on 2017-11-23 14:12  6relation  阅读(138)  评论(0编辑  收藏  举报

导航