手把手教你从最基本的Java工程搭建SpringMVC+SpringDataJPA+Hibernate(含源码下载)

转载自:http://blog.csdn.net/anxpp/article/details/51415366,谢谢!

    本文会介绍从一个最基本的java工程,到Web工程,到集成Spring、SpringMVC、SpringDataJPA+Hibernate。

    平时我们可能是通过一个模板搭建一个工程,或者是直接导入一个项目,而本文选择从最基本的java工程开始,目的是为了展示更多原理。

    当然,我们还是从一个最基本的Maven工程开始,其实普通的非Maven工程,搭建过程几乎是一模一样的,只是Jar包需要我们手动的添加到工程中,而Maven工程就只是修改配置文件即可。推荐几篇相关文章:

  1.     Maven介绍及安装和在eclipse中的配置
  2.     Eclipse中使用Maven创建基本的web项目
  3.     Eclipse搭建Maven工程集成Spring4MVC
  4.     Eclipse搭建Maven工程集成Spring4+MVC+Hibernate5
  5.     JPA规范介绍及实例(Java数据持久化解决方案)

    对 Spring Data JPA 更详细的介绍,请戳->Spring ORM+Hibernate?Out!换 Spring Data JPA 吧!

    下面就正式开始。

1、基于Maven(如果不使用Maven也可以用传统的工程)创建最基本的Java工程

    新建工程,选择Maven Project,Next:

    001

    勾选为简单的工程(Create a simple project),Next:

    002

    Group id为你的域名反序,通常跟工程源码的包名对应,Artifact id为这个Group id中工程的唯一名,根据你的爱好,怎么填都行,然后Finish:

    003

    这是得到的工程目录结构是这样的:

    004

    pom.xml就是Maven的核心文件。

2、将工程设置为动态网页模式

    接下来就将工程转换为Web工程,右键打开工程属性,如图,点击左边菜单中的Project Facets,然后点击Convert to faceted from...:

    005

    在右边,我们勾选Dynamic Web Module(动态网页),然后点OK:

    006

    这时会多出一个WebContent目录:

    007

    在WEB-INF目录下,添加web.xml文件,内如如下:

 
 
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns="http://java.sun.com/xml/ns/javaee"
  4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  5. version="3.0">
  6. <display-name>SpringDataJPA</display-name>
  7. <welcome-file-list>
  8. <welcome-file>index.html</welcome-file>
  9. </welcome-file-list>
  10. </web-app>

    然后添加一个欢迎页index.html:

 
 
  1. <html>
  2. <head>
  3. </head>
  4. <body>
  5. <h1>Hello Word!</h1>
  6. </body>
  7. </html>

    这时目录结构如下:

    008

    这时,就可以右键工程,Run On Server了,可以看下效果:

    10

3、集成Spring+SpringMVC

    新建包,并添加一些接口和类(具体代码后面会列出来),包结构如图:

    11

    需要添加jar包,直接修改pom文件即可,如果为普通工程,按pom.xml中的jar包,添加到工程中即可。

    首先添加使用的spring版本,方便统一管理,然后再添加所有需要的jar包,下面把此处需要的所有jar包添加进来,完成后的pom.xml如下:

 
 
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3. <modelVersion>4.0.0</modelVersion>
  4. <groupId>com.anxpp</groupId>
  5. <artifactId>SpringDataJPA</artifactId>
  6. <version>0.0.1-SNAPSHOT</version>
  7. <properties>
  8. <!-- spring版本号 -->
  9. <spring.version>4.2.5.RELEASE</spring.version>
  10. </properties>
  11. <dependencies>
  12. <!-- spring核心包 -->
  13. <dependency>
  14. <groupId>org.springframework</groupId>
  15. <artifactId>spring-core</artifactId>
  16. <version>${spring.version}</version>
  17. </dependency>
  18. <dependency>
  19. <groupId>org.springframework</groupId>
  20. <artifactId>spring-web</artifactId>
  21. <version>${spring.version}</version>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.springframework</groupId>
  25. <artifactId>spring-orm</artifactId>
  26. <version>${spring.version}</version>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.springframework</groupId>
  30. <artifactId>spring-tx</artifactId>
  31. <version>${spring.version}</version>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.springframework</groupId>
  35. <artifactId>spring-jdbc</artifactId>
  36. <version>${spring.version}</version>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.springframework</groupId>
  40. <artifactId>spring-webmvc</artifactId>
  41. <version>${spring.version}</version>
  42. </dependency>
  43. <dependency>
  44. <groupId>org.springframework</groupId>
  45. <artifactId>spring-aop</artifactId>
  46. <version>${spring.version}</version>
  47. </dependency>
  48. <dependency>
  49. <groupId>org.springframework</groupId>
  50. <artifactId>spring-context-support</artifactId>
  51. <version>${spring.version}</version>
  52. </dependency>
  53. <dependency>
  54. <groupId>org.springframework</groupId>
  55. <artifactId>spring-test</artifactId>
  56. <version>${spring.version}</version>
  57. </dependency>
  58. <dependency>
  59. <groupId>org.springframework</groupId>
  60. <artifactId>spring-orm</artifactId>
  61. <version>${spring.version}</version>
  62. </dependency>
  63. <dependency>
  64. <groupId>org.springframework.data</groupId>
  65. <artifactId>spring-data-jpa</artifactId>
  66. <version>1.10.1.RELEASE</version>
  67. </dependency>
  68. </dependencies>
  69. </project>

    在WEB-INF目录下添加Spring配置文件applicationContext.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" xmlns:context="http://www.springframework.org/schema/context"
  4. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p"
  5. xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context-4.2.xsd
  10. http://www.springframework.org/schema/tx
  11. http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
  12. http://www.springframework.org/schema/aop
  13. http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
  14. http://www.springframework.org/schema/mvc
  15. http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
  16. <!-- 开启IOC注解扫描 -->
  17. <context:component-scan base-package="com.anxpp.demo" />
  18. <!-- 开启MVC注解扫描 -->
  19. <mvc:annotation-driven />
  20. </beans>

    修改web.xml,将spring添加进去:

 
 
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns="http://java.sun.com/xml/ns/javaee"
  4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  5. version="3.0">
  6. <display-name>SpringDataJPA</display-name>
  7. <listener>
  8. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  9. </listener>
  10. <context-param>
  11. <param-name>contextConfigLocation</param-name>
  12. <param-value>WEB-INF/applicationContext.xml</param-value>
  13. </context-param>
  14. <servlet>
  15. <servlet-name>springmvc</servlet-name>
  16. <servlet-class>org.springframework.web.servlet.DispatcherServlet
  17. </servlet-class>
  18. <init-param>
  19. <param-name>contextConfigLocation</param-name>
  20. <param-value>classpath*:springmvc-servlet.xml</param-value>
  21. </init-param>
  22. <load-on-startup>1</load-on-startup>
  23. </servlet>
  24. <servlet-mapping>
  25. <servlet-name>springmvc</servlet-name>
  26. <url-pattern>/*</url-pattern>
  27. </servlet-mapping>
  28. <welcome-file-list>
  29. <welcome-file>index.html</welcome-file>
  30. </welcome-file-list>
  31. </web-app>

    下面开始编写代码,注意注解不要忘记写,在本小节开始部分已经给出了包的层次结构。

    实体User:


  
  
  1. package com.anxpp.demo.core.entity;
  2. public class User {
  3. private Integer id;
  4. private String name;
  5. public User(Integer id, String name) {
  6. this.id = id;
  7. this.name = name;
  8. }
  9. public Integer getId() {
  10. return id;
  11. }
  12. public void setId(Integer id) {
  13. this.id = id;
  14. }
  15. public String getName() {
  16. return name;
  17. }
  18. public void setName(String name) {
  19. this.name = name;
  20. }
  21. @Override
  22. public String toString() {
  23. return "id:"+id+",name:"+name;
  24. }
  25. }

    dao层接口UserDao:


  
  
  1. package com.anxpp.demo.core.dao;
  2. import com.anxpp.demo.core.entity.User;
  3. public interface UserDao {
  4. User getUser(Integer id,String name);
  5. }

    dao层实现UserDaoImpl:


  
  
  1. package com.anxpp.demo.core.dao.impl;
  2. import org.springframework.stereotype.Repository;
  3. import com.anxpp.demo.core.dao.UserDao;
  4. import com.anxpp.demo.core.entity.User;
  5. @Repository
  6. public class UserDaoImpl implements UserDao{
  7. @Override
  8. public User getUser(Integer id, String name) {
  9. return new User(id, name);
  10. }
  11. }

    service层接口UserService:


  
  
  1. package com.anxpp.demo.core.service;
  2. import com.anxpp.demo.core.entity.User;
  3. public interface UserService {
  4. User getUser(Integer id, String name);
  5. }

    service层实现:


  
  
  1. package com.anxpp.demo.core.service.impl;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.stereotype.Service;
  4. import com.anxpp.demo.core.dao.UserDao;
  5. import com.anxpp.demo.core.entity.User;
  6. import com.anxpp.demo.core.service.UserService;
  7. @Service
  8. public class UserServiceImpl implements UserService{
  9. @Autowired
  10. UserDao userDao;
  11. @Override
  12. public User getUser(Integer id, String name) {
  13. return userDao.getUser(id, name);
  14. }
  15. }

    controller层DemoController:


  
  
  1. package com.anxpp.demo.controller;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.ResponseBody;
  6. import com.anxpp.demo.core.service.UserService;
  7. @Controller
  8. @RequestMapping("/")
  9. public class demoController {
  10. @Autowired
  11. UserService userService;
  12. @RequestMapping("/")
  13. @ResponseBody
  14. public String index(){
  15. return "index";
  16. }
  17. @RequestMapping("/getuser")
  18. @ResponseBody
  19. public String getUser(Integer id, String name){
  20. return userService.getUser(id, name).toString();
  21. }
  22. }

    这是还不能直接Run On Server,因为jar包不会被一同发布,我们需要如下配置:

    右键工程选择属性,按下图配置:009

    这时候就可以运行测试了,效果如下:

    12

    13

    到这里,我们还没有操作数据库的。

4、添加返回Json格式数据支持

    现在,我们常使用json作为数据传输的格式,下面就为SpringMVC添加返回json的支持

    首先添加jar包:

 
 
  1. <dependency>
  2. <groupId>com.fasterxml.jackson.core</groupId>
  3. <artifactId>jackson-databind</artifactId>
  4. <version>2.5.0</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.fasterxml.jackson.core</groupId>
  8. <artifactId>jackson-core</artifactId>
  9. <version>2.5.0</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>com.fasterxml.jackson.core</groupId>
  13. <artifactId>jackson-annotations</artifactId>
  14. <version>2.5.0</version>
  15. </dependency>

    然后改写getUser()方法如下:


  
  
  1. @RequestMapping("/getuser")
  2. @ResponseBody
  3. public Map<String, Object> getUser(Integer id, String name){
  4. Map<String, Object> map = new HashMap<String, Object>();
  5. map.put("state", "success");
  6. map.put("data", userService.getUser(id, name));
  7. return map;
  8. }

    重新运行后访问效果如下:

    14

    此时,就可以返回json数据了。

5、配置静态资源访问

    通常情况下,WEB-INF目录下的资源,我们是无法直接访问的,如果我们的网站是html+ajax构成的,那么就可以在WEB-INF之外新建html的目录,并为web.xml配置默认的过滤器,不过注意要放到SpingMVC过滤器之前:

 
 
  1. <servlet-mapping>
  2. <servlet-name>default</servlet-name>
  3. <url-pattern>*.html</url-pattern>
  4. </servlet-mapping>

    如果一定要访问WEB-INF目录内的资源,通过查阅Spring官方文档,发现有两种方式:

    1、手写一个资源映射器:


  
  
  1. @Configuration
  2. @EnableWebMvc
  3. public class WebConfig extends WebMvcConfigurerAdapter {
  4. @Override
  5. public void addResourceHandlers(ResourceHandlerRegistry registry) {
  6. registry.addResourceHandler("/resources/**")
  7. .addResourceLocations("/public-resources/")
  8. .setCacheControl(CacheControl.maxAge(1, TimeUnit.HOURS).cachePublic());
  9. }
  10. }

    可以看到,还可以设置缓存时间的,而更简单的方式,就是xml配置:


  
  
  1. <mvc:resources mapping="/resources/**" location="/public-resources/">
  2. <mvc:cache-control max-age="3600" cache-public="true"/>
  3. </mvc:resources>

    也可以加上下面的这个:

 
 
  1. <!-- 对静态资源文件的访问,将无法mapping到Controller的path交给default servlet handler处理-->
  2. <mvc:default-servlet-handler />

6、乱码解决

    我们通常使用ajax提交请求,但也常用地址栏直接测试。请求提交分get和post。

    使用post提交请求是,一般是不会出现中文乱码的,但是如果确实出现了乱码,可以通过在web.xml添加一个编码过滤器解决:


  
  
  1. <filter>
  2. <filter-name>CharacterEncoding</filter-name>
  3. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  4. <init-param>
  5. <param-name>encoding</param-name>
  6. <param-value>UTF-8</param-value>
  7. </init-param>
  8. <init-param>
  9. <param-name>forceEncoding</param-name>
  10. <param-value>true</param-value>
  11. </init-param>
  12. </filter>
  13. <filter-mapping>
  14. <filter-name>CharacterEncoding</filter-name>
  15. <url-pattern>/*</url-pattern>
  16. </filter-mapping>

    上面只能解决post的中文乱码,对于get(含浏览器地址栏直接提交方式),我们需要修改tomcat配置,在conf目录下的server.xml中找到并如下修改:

 
 
  1. <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/>

    如果我们只是测试,项目并没有部署,可以直接在eclipse中的server下,找到server.xml,做出上面一样的改动即可:

18

7、整合SpringDataJPA+Hibernate

    你可以通过这篇文字了解JPA:JPA规范介绍及实例(Java数据持久化解决方案)

    SpringDataJPA也正是这样一种轻量级的解决方案,而首选的Hibernate就实现了JPA。

    首先还是jar包,SpringDataJPA的jar包,在之前整合Spring时已经一并加入,下面是Hibernate(和mysql驱动)的jar包:


  
  
  1. <!-- hibernate -->
  2. <dependency>
  3. <groupId>org.hibernate</groupId>
  4. <artifactId>hibernate-core</artifactId>
  5. <version>${hibernate.version}</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.hibernate</groupId>
  9. <artifactId>hibernate-ehcache</artifactId>
  10. <version>${hibernate.version}</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.hibernate</groupId>
  14. <artifactId>hibernate-entitymanager</artifactId>
  15. <version>${hibernate.version}</version>
  16. </dependency>
  17. <dependency>
  18. <groupId>org.hibernate</groupId>
  19. <artifactId>hibernate-c3p0</artifactId>
  20. <version>${hibernate.version}</version>
  21. </dependency>
  22. <dependency>
  23. <groupId>mysql</groupId>
  24. <artifactId>mysql-connector-java</artifactId>
  25. <version>5.1.9</version>
  26. </dependency>

    统一管理的版本为:

 
 
  1. <!-- hibernate 版本号 -->
  2. <hibernate.version>5.1.0.Final</hibernate.version>

    添加Jpa的配置文件persistence.xml到META-INF目录下,本文介绍时数据库使用MySQL。并添加如下内容:

 
 
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <persistence version="1.0"
  3. xmlns="http://java.sun.com/xml/ns/persistence"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
  6. <persistence-unit name="demo" transaction-type="RESOURCE_LOCAL">
  7. <!-- provider>org.eclipse.persistence.jpa.PersistenceProvider</provider -->
  8. <provider>org.hibernate.ejb.HibernatePersistence</provider>
  9. <class>com.ninelephas.meerkat.pojo.User</class>
  10. <!-- MYSql 的连接 -->
  11. <properties>
  12. <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
  13. <property name="hibernate.connection.url" value="jdbc:mysql://127.0.0.1:3306/demo?createDatabaseIfNotExist=true" />
  14. <property name="hibernate.connection.username" value="root" />
  15. <property name="hibernate.connection.password" value="root" />
  16. <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
  17. </properties>
  18. </persistence-unit>
  19. </persistence>

    Spring配置文件applicationContext.xml中增加JPA支持后的完整内容:

 
 
  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" xmlns:p="http://www.springframework.org/schema/p"
  5. xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xmlns:jpa="http://www.springframework.org/schema/data/jpa"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context-4.2.xsd
  11. http://www.springframework.org/schema/tx
  12. http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
  13. http://www.springframework.org/schema/aop
  14. http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
  15. http://www.springframework.org/schema/mvc
  16. http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
  17. http://www.springframework.org/schema/data/jpa
  18. http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
  19. <!-- 开启IOC注解扫描 -->
  20. <context:component-scan base-package="com.anxpp.demo" />
  21. <bean id="entityManagerFactory"
  22. class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
  23. <property name="jpaVendorAdapter">
  24. <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
  25. <property name="generateDdl" value="true" />
  26. <property name="database" value="MYSQL" />
  27. </bean>
  28. </property>
  29. <property name="persistenceUnitName" value="demo" />
  30. </bean>
  31. <!-- 开启MVC注解扫描 -->
  32. <mvc:annotation-driven />
  33. <bean
  34. class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
  35. <property name="viewResolvers">
  36. <list>
  37. <bean
  38. class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  39. <property name="prefix" value="/WEB-INF/view/" />
  40. <property name="suffix" value=".html" />
  41. </bean>
  42. </list>
  43. </property>
  44. <!-- 用于将对象转换为 JSON -->
  45. <property name="defaultViews">
  46. <list>
  47. <bean
  48. class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" />
  49. </list>
  50. </property>
  51. </bean>
  52. <!-- 对静态资源文件的访问,将无法mapping到Controller的path交给default servlet handler处理 -->
  53. <mvc:default-servlet-handler />
  54. <!-- 配置事务管理器 -->
  55. <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
  56. <property name="entityManagerFactory" ref="entityManagerFactory" />
  57. </bean>
  58. <!-- 启用 annotation事务 -->
  59. <tx:annotation-driven transaction-manager="transactionManager" />
  60. <!-- 配置Spring Data JPA扫描目录 -->
  61. <jpa:repositories base-package="com.anxpp.demo" />
  62. </beans>

    修改实体:


  
  
  1. package com.anxpp.demo.core.entity;
  2. import javax.persistence.Entity;
  3. import javax.persistence.GeneratedValue;
  4. import javax.persistence.GenerationType;
  5. import javax.persistence.Id;
  6. import javax.persistence.Table;
  7. @Entity
  8. @Table
  9. public class User {
  10. @Id
  11. @GeneratedValue(strategy = GenerationType.AUTO)
  12. private Integer id;
  13. private String name;
  14. public User() {
  15. }
  16. public User(String name) {
  17. this.name = name;
  18. }
  19. public Integer getId() {
  20. return id;
  21. }
  22. public void setId(Integer id) {
  23. this.id = id;
  24. }
  25. public String getName() {
  26. return name;
  27. }
  28. public void setName(String name) {
  29. this.name = name;
  30. }
  31. @Override
  32. public String toString() {
  33. return "id:"+id+",name:"+name;
  34. }
  35. }

    可以删掉dao层实现了,我们记住将dao层接口继承自强大的JpaRepository:


  
  
  1. public interface UserDao extends JpaRepository<User, Serializable>{
  2. User findById(Integer id);
  3. }

    是不是看上去特别简洁,而且都不需要写实现的,SpringDataJPA会自动帮我们完成。

    修改service层接口:


  
  
  1. package com.anxpp.demo.core.service;
  2. import java.util.List;
  3. import com.anxpp.demo.core.entity.User;
  4. public interface UserService {
  5. User findById(Integer id);
  6. User save(String name);
  7. List<User> findAll();
  8. }

    修改service层实现:


  
  
  1. package com.anxpp.demo.core.service.impl;
  2. import java.util.List;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Service;
  5. import com.anxpp.demo.core.dao.UserDao;
  6. import com.anxpp.demo.core.entity.User;
  7. import com.anxpp.demo.core.service.UserService;
  8. @Service
  9. public class UserServiceImpl implements UserService{
  10. @Autowired
  11. UserDao userDao;
  12. @Override
  13. public User findById(Integer id) {
  14. return userDao.findById(id);
  15. }
  16. @Override
  17. public User save(String name) {
  18. return userDao.save(new User(name));
  19. }
  20. @Override
  21. public List<User> findAll() {
  22. return userDao.findAll();
  23. }
  24. }

    修改controller,提供多个测试接口:


  
  
  1. package com.anxpp.demo.controller;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.ResponseBody;
  8. import com.anxpp.demo.core.service.UserService;
  9. @Controller
  10. @RequestMapping("/")
  11. public class demoController {
  12. @Autowired
  13. UserService userService;
  14. @RequestMapping("/")
  15. @ResponseBody
  16. public String index(){
  17. return "index";
  18. }
  19. @RequestMapping("/info")
  20. public String info(){
  21. return "info";
  22. }
  23. @RequestMapping("/findall")
  24. @ResponseBody
  25. public Map<String, Object> getUser(){
  26. Map<String, Object> map = new HashMap<String, Object>();
  27. map.put("state", "success");
  28. map.put("data", userService.findAll());
  29. return map;
  30. }
  31. @RequestMapping("/findbyid")
  32. @ResponseBody
  33. public Map<String, Object> findById(Integer id){
  34. Map<String, Object> map = new HashMap<String, Object>();
  35. map.put("state", "success");
  36. map.put("data", userService.findById(id));
  37. return map;
  38. }
  39. @RequestMapping("/add")
  40. @ResponseBody
  41. public Map<String, Object> save(String name){
  42. Map<String, Object> map = new HashMap<String, Object>();
  43. map.put("state", "success");
  44. map.put("data", userService.save(name));
  45. return map;
  46. }
  47. }

    运行效果:

    15

    16

17

    那么,如果需要添加一个查找id大于指定值的指定姓氏的数据呢?

    如果是SQL,我们会这样写(?表示参数):


  
  
  1. SELECT * FROM user WHERE id>? AND name like '?%';

    但是这里,我们连SQL(或者HQL)都可以不用写,直接在dao层接口添加一个方法即可:


  
  
  1. List<User> findByIdGreaterThanAndNameLike(Integer id,String name);

    你不需要怀疑,上面的方法执行偏偏就是能成功(注意:service实现的使用,调用该方法记得name+"%")!


源码:

    github地址:https://github.com/anxpp/SpringMVC-SpringDataJpa-Hibernate-Demo

    本地下载:SpringMVC + Spring Data JPA + Hibernate

    CSDN下载(不需要积分):http://download.csdn.net/download/anxpp/9520498

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值