Spring Data JPA是Spring Data的一個子項目,它經過提供基於JPA的Repository極大地減小了JPA做爲數據訪問方案的代碼量。java
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.xiaolyuh</groupId> <artifactId>spring-boot-student</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>pom</packaging> <name>spring-boot-student</name> <!-- 添加Spring Boot的父類依賴,這樣當前項目就是Spring Boot項目了。 spring-boot-starter-parent是一個特殊的starter,他用來 提供相關的maven默認依賴, 使用它以後,經常使用的依賴能夠省去version標籤 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.3.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <modules> <module>spring-boot-student-banner</module> <module>spring-boot-student-config</module> <module>spring-boot-student-log</module> <module>spring-boot-student-profile</module> <module>spring-boot-student-data-jpa</module> <module>spring-boot-student-mybatis</module> </modules> </project>
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <artifactId>spring-boot-student-data-jpa</artifactId> <packaging>jar</packaging> <name>spring-boot-student-data-jpa</name> <description>Spring boot profile 配置</description> <parent> <groupId>com.xiaolyuh</groupId> <artifactId>spring-boot-student</artifactId> <version>0.0.1-SNAPSHOT</version> <relativePath /> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> </dependency> </dependencies> </project>
CREATE TABLE `person` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `age` int(11) NOT NULL, `address` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8; -- 文件名修改爲data.sql放到resources文件夾下才會執行 insert into person(name,age,address) values('wyf',32,'合肥'); insert into person(name,age,address) values('xx',31,'北京'); insert into person(name,age,address) values('yy',30,'上海'); insert into person(name,age,address) values('zz',29,'南京'); insert into person(name,age,address) values('aa',28,'武漢'); insert into person(name,age,address) values('bb',27,'合肥');
package com.xiaolyuh.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.NamedQuery; @Entity // @Entity註解指明這是一個和數據庫表映射的實體類。 @NamedQuery(name = "Person.withNameAndAddressNamedQuery", query = "select p from Person p where p.name=?1 and address=?2") public class Person { @Id // @Id註解指明這個屬性映射爲數據庫的主鍵。 @GeneratedValue // @GeneratedValue註解默認使用主鍵生成方式爲自增,hibernate會爲咱們自動生成一個名爲HIBERNATE_SEQUENCE的序列。 private Long id; private String name; private Integer age; private String address; public Person() { super(); } public Person(Long id, String name, Integer age, String address) { this.id = id; this.name = name; this.age = age; this.address = address; } public Person(String name, Integer age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Person [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + "]"; } }
package com.xiaolyuh.repository; import com.xiaolyuh.entity.Person; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.List; public interface PersonRepository extends JpaRepository<Person, Long> { // 使用方法名查詢,接受一個name參數,返回值爲列表。 List<Person> findByAddress(String name); // 使用方法名查詢,接受name和address,返回值爲單個對象。 Person findByNameAndAddress(String name, String address); // 使用@Query查詢,參數按照名稱綁定。 @Query("select p from Person p where p.name= :name and p.address= :address") Person withNameAndAddressQuery(@Param("name") String name, @Param("address") String address); // 使用@NamedQuery查詢,請注意咱們在實體類中作的@NamedQuery的定義。 Person withNameAndAddressNamedQuery(String name, String address); }
package com.xiaolyuh.controller; import com.xiaolyuh.entity.Person; import com.xiaolyuh.repository.PersonRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController public class DataController { // 1 Spring Data JPA已自動爲你註冊bean,因此可自動注入 @Autowired PersonRepository personRepository; /** * 保存 save支持批量保存:<S extends T> Iterable<S> save(Iterable<S> entities); * <p> * 刪除: 支持使用id刪除對象、批量刪除以及刪除所有: void delete(ID id); void delete(T entity); * void delete(Iterable<? extends T> entities); void deleteAll(); */ @RequestMapping("/save") public Person save(@RequestBody Person person) { Person p = personRepository.save(person); return p; } /** * 測試findByAddress */ @RequestMapping("/q1") public List<Person> q1(String address) { List<Person> people = personRepository.findByAddress(address); return people; } /** * 測試findByNameAndAddress */ @RequestMapping("/q2") public Person q2(String name, String address) { Person people = personRepository.findByNameAndAddress(name, address); return people; } /** * 測試withNameAndAddressQuery */ @RequestMapping("/q3") public Person q3(String name, String address) { Person p = personRepository.withNameAndAddressQuery(name, address); return p; } /** * 測試withNameAndAddressNamedQuery */ @RequestMapping("/q4") public Person q4(String name, String address) { Person p = personRepository.withNameAndAddressNamedQuery(name, address); return p; } /** * 測試排序 */ @RequestMapping("/sort") public List<Person> sort() { List<Person> people = personRepository.findAll(new Sort(Direction.ASC, "age")); return people; } /** * 測試分頁 */ @RequestMapping("/page") public Page<Person> page(@RequestParam("pageNo") int pageNo, @RequestParam("pageSize") int pageSize) { Page<Person> pagePeople = personRepository.findAll(new PageRequest(pageNo, pageSize)); return pagePeople; } }
server.port=80 # 數據源配置 spring.datasource.url=jdbc:mysql://localhost:3306/ssb_test spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.username=root spring.datasource.password=root #鏈接池配置 spring.datasource.type=org.apache.commons.dbcp2.BasicDataSource #初始化鏈接:鏈接池啓動時建立的初始化鏈接數量 spring.datasource.dbcp2.initial-size=50 #最大活動鏈接:鏈接池在同一時間可以分配的最大活動鏈接的數量, 若是設置爲非正數則表示不限制 spring.datasource.dbcp2.max-active=250 #最大空閒鏈接:鏈接池中允許保持空閒狀態的最大鏈接數量,超過的空閒鏈接將被釋放,若是設置爲負數表示不限制 spring.datasource.dbcp2.max-idle=50 #最小空閒鏈接:鏈接池中允許保持空閒狀態的最小鏈接數量,低於這個數量將建立新的鏈接,若是設置爲0則不建立 spring.datasource.dbcp2.min-idle=5 #最大等待時間:當沒有可用鏈接時,鏈接池等待鏈接被歸還的最大時間(以毫秒計數),超過期間則拋出異常,若是設置爲-1表示無限等待 spring.datasource.dbcp2.max-wait-millis=10000 #SQL查詢,用來驗證從鏈接池取出的鏈接,在將鏈接返回給調用者以前.若是指定,則查詢必須是一個SQL SELECT而且必須返回至少一行記錄 spring.datasource.dbcp2.validation-query=SELECT 1 #當創建新鏈接時被髮送給JDBC驅動的鏈接參數,格式必須是 [propertyName=property;]。注意:參數user/password將被明確傳遞,因此不須要包括在這裏。 spring.datasource.dbcp2.connection-properties=characterEncoding=utf8 # JPA配置 #hibernate提供了根據實體類自動維護數據庫表結構的功能,可經過spring.jpa.hibernate.ddl-auto來配置,有下列可選項: #一、create:啓動時刪除上一次生成的表,並根據實體類生成表,表中數據會被清空。 #二、create-drop:啓動時根據實體類生成表,sessionFactory關閉時表會被刪除。 #三、update:啓動時會根據實體類生成表,當實體類屬性變更的時候,表結構也會更新,在初期開發階段使用此選項。 #四、validate:啓動時驗證明體類和數據表是否一致,在咱們數據結構穩定時採用此選項。 #五、none:不採起任何措施。 spring.jpa.hibernate.ddl-auto=update #spring.jpa.show-sql用來設置hibernate操做的時候在控制檯顯示其真實的sql語句。 spring.jpa.show-sql=true #讓控制器輸出的json字符串格式更美觀。 spring.jackson.serialization.indent-output=true #日誌配置 logging.level.com.xiaolyuh=debug logging.level.org.springframework.web=debug logging.level.org.springframework.transaction=debug logging.level.org.apache.commons.dbcp2=debug debug=false
package com.xiaolyuh; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import net.minidev.json.JSONObject; @RunWith(SpringRunner.class) @SpringBootTest public class SpringBootStudentDataJpaApplicationTests { @Test public void contextLoads() { } private MockMvc mockMvc; // 模擬MVC對象,經過MockMvcBuilders.webAppContextSetup(this.wac).build()初始化。 @Autowired private WebApplicationContext wac; // 注入WebApplicationContext // @Autowired // private MockHttpSession session;// 注入模擬的http session // // @Autowired // private MockHttpServletRequest request;// 注入模擬的http request\ @Before // 在測試開始前初始化工做 public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test public void testQ1() throws Exception { Map<String, Object> map = new HashMap<>(); map.put("address", "合肥"); MvcResult result = mockMvc.perform(post("/q1?address=合肥").content(JSONObject.toJSONString(map))) .andExpect(status().isOk())// 模擬向testRest發送get請求 .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))// 預期返回值的媒體類型text/plain;charset=UTF-8 .andReturn();// 返回執行請求的結果 System.out.println(result.getResponse().getContentAsString()); } @Test public void testSave() throws Exception { Map<String, Object> map = new HashMap<>(); map.put("address", "合肥"); map.put("name", "測試"); map.put("age", 50); MvcResult result = mockMvc.perform(post("/save").contentType(MediaType.APPLICATION_JSON).content(JSONObject.toJSONString(map))) .andExpect(status().isOk())// 模擬向testRest發送get請求 .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))// 預期返回值的媒體類型text/plain;charset=UTF-8 .andReturn();// 返回執行請求的結果 System.out.println(result.getResponse().getContentAsString()); } @Test public void testPage() throws Exception { MvcResult result = mockMvc.perform(post("/page").param("pageNo", "1").param("pageSize", "2")) .andExpect(status().isOk())// 模擬向testRest發送get請求 .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))// 預期返回值的媒體類型text/plain;charset=UTF-8 .andReturn();// 返回執行請求的結果 System.out.println(result.getResponse().getContentAsString()); } }
package com.xiaolyuh; import net.minidev.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import javax.sql.DataSource; import java.util.HashMap; import java.util.Map; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @SpringBootTest public class DataSourceTests { @Autowired ApplicationContext applicationContext; @Autowired DataSourceProperties dataSourceProperties; @Test public void testDataSource() throws Exception { // 獲取配置的數據源 DataSource dataSource = applicationContext.getBean(DataSource.class); // 查看配置數據源信息 System.out.println(dataSource); System.out.println(dataSource.getClass().getName()); System.out.println(dataSourceProperties); } }
https://github.com/wyh-spring-ecosystem-student/spring-boot-student/tree/releasesmysql
spring-boot-student-data-jpa工程git