手把手教你從最基本的Java工程搭建SpringMVC+SpringDataJPA+Hibernate(含原始碼下載)

anxpp發表於2016-05-15

轉載請註明出處: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

相關文章