Spring Boot+Spring Data Jpa+DBCP2数据源

来源:互联网 发布:mac 配置java环境变量 编辑:程序博客网 时间:2024/06/07 07:31

Spring Data JPA是Spring Data的一个子项目,它通过提供基于JPA的Repository极大地减少了JPA作为数据访问方案的代码量。

pom.xml文件

父类pom

<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>

Spring Data Jpa 子项pom

<?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;}@Overridepublic String toString() {return "Person [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + "]";}}

DAO层实现

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);}

Controller 层实现

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;@RestControllerpublic 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;    }}

Spring Boot 配置文件

server.port=80# 数据源配置spring.datasource.url=jdbc:mysql://localhost:3306/ssb_testspring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.username=rootspring.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来配置,有下列可选项:#1、create:启动时删除上一次生成的表,并根据实体类生成表,表中数据会被清空。#2、create-drop:启动时根据实体类生成表,sessionFactory关闭时表会被删除。#3、update:启动时会根据实体类生成表,当实体类属性变动的时候,表结构也会更新,在初期开发阶段使用此选项。#4、validate:启动时验证实体类和数据表是否一致,在我们数据结构稳定时采用此选项。#5、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=debuglogging.level.org.springframework.web=debuglogging.level.org.springframework.transaction=debuglogging.level.org.apache.commons.dbcp2=debugdebug=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)@SpringBootTestpublic class SpringBootStudentDataJpaApplicationTests {@Testpublic 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)@SpringBootTestpublic 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/releases

spring-boot-student-data-jpa工程