Spring Boot 系列教程2-Data JPA
Spring Data JPA
用来简化创建 JPA 数据访问层和跨存储的持久层功能。
官网文档连接
http://docs.spring.io/spring-data/jpa/docs/current/reference/html/
Spring Data JPA提供的接口
- Repository:最顶层的接口,是一个空的接口,目的是为了统一所有Repository的类型,且能让组件扫描的时候自动识别
- CrudRepository :是Repository的子接口,提供CRUD的功能
- PagingAndSortingRepository:是CrudRepository的子接口,添加分页和排序的功能
- JpaRepository:是PagingAndSortingRepository的子接口,增加了一些实用的功能,比如:批量操作等
- JpaSpecificationExecutor:用来做负责查询的接口
- Specification:是Spring Data JPA提供的一个查询规范,要做复杂的查询,只需围绕这个规范来设置查询条件即可
项目图片
pom.xml
-只需要在pom.xml引入需要的数据库配置,就会自动访问此数据库,如果需要配置其他数据库,可以在application.properties进行添加
-默认使用org.apache.tomcat.jdbc.pool.DataSource创建连接池
<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.jege.spring.boot</groupId>
<artifactId>spring-boot-data-jpa</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot-data-jpa</name>
<url>http://maven.apache.org</url>
<!-- 公共spring-boot配置,下面依赖jar文件不用在写版本号 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
<relativePath />
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- 持久层 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- h2内存数据库 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>spring-boot-data-jpa</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
User.java
package com.jege.spring.boot.data.jpa.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author JE哥
* @email 1272434821@qq.com
* @description:jpa模型对象
*/
@Entity
@Table(name = "t_user")
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
private Integer age;
public User() {
}
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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;
}
}
UserRepository.java
package com.jege.spring.boot.data.jpa.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.jege.spring.boot.data.jpa.entity.User;
/**
* @author JE哥
* @email 1272434821@qq.com
* @description:持久层接口,由spring自动生成其实现
*/
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByNameLike(String name);
}
Repository接口查询规则
关键字 | 案例 | 效果 |
---|---|---|
And | findByLastnameAndFirstname | … where x.lastname = ?1 and x.firstname = ?2 |
Or | findByLastnameOrFirstname | … where x.lastname = ?1 or x.firstname = ?2 |
Is,Equals | findByFirstname,findByFirstnameIs,findByFirstnameEquals | … where x.firstname = ?1 |
Between | findByStartDateBetween | … where x.startDate between ?1 and ?2 |
LessThan | findByAgeLessThan | … where x.age < ?1 |
LessThanEqual | findByAgeLessThanEqual | … where x.age <= ?1 |
GreaterThan | findByAgeGreaterThan | … where x.age > ?1 |
GreaterThanEqual | findByAgeGreaterThanEqual | … where x.age >= ?1 |
After | findByStartDateAfter | … where x.startDate > ?1 |
Before | findByStartDateBefore | … where x.startDate < ?1 |
IsNull | findByAgeIsNull | … where x.age is null |
IsNotNull,NotNull | findByAge(Is)NotNull | … where x.age not null |
Like | findByFirstnameLike | … where x.firstname like ?1 |
NotLike | findByFirstnameNotLike | … where x.firstname not like ?1 |
StartingWith | findByFirstnameStartingWith | … where x.firstname like ?1 (parameter bound with appended %) |
EndingWith | findByFirstnameEndingWith | … where x.firstname like ?1 (parameter bound with prepended %) |
Containing | findByFirstnameContaining | … where x.firstname like ?1 (parameter bound wrapped in %) |
OrderBy | findByAgeOrderByLastnameDesc | … where x.age = ?1 order by x.lastname desc |
Not | findByLastnameNot | … where x.lastname <> ?1 |
In | findByAgeIn(Collection ages) | … where x.age in ?1 |
NotIn | findByAgeNotIn(Collection age) | … where x.age not in ?1 |
TRUE | findByActiveTrue() | … where x.active = true |
FALSE | findByActiveFalse() | … where x.active = false |
IgnoreCase | findByFirstnameIgnoreCase | … where UPPER(x.firstame) = UPPER(?1) |
Application.java
package com.jege.spring.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author JE哥
* @email 1272434821@qq.com
* @description:spring boot 启动类
*/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
application.properties
## JPA Settings
spring.jpa.generate-ddl: true
spring.jpa.show-sql: true
spring.jpa.hibernate.ddl-auto: create
spring.jpa.properties.hibernate.format_sql: false
UserRepositoryTest.java
package com.jege.spring.boot.data.jpa;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.After;
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.test.context.junit4.SpringJUnit4ClassRunner;
import com.jege.spring.boot.data.jpa.entity.User;
import com.jege.spring.boot.data.jpa.repository.UserRepository;
/**
* @author JE哥
* @email 1272434821@qq.com
* @description:
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest()
public class UserRepositoryTest {
@Autowired
UserRepository userRepository;
// 打印出class com.sun.proxy.$Proxy66表示spring注入通过jdk动态代理获取接口的子类
@Test
public void proxy() throws Exception {
System.out.println(userRepository.getClass());
}
@Test
public void save() throws Exception {
for (int i = 0; i < 10; i++) {
User user = new User("jege" + i, 25 + i);
userRepository.save(user);
}
}
@Test
public void all() throws Exception {
save();
assertThat(userRepository.findAll()).hasSize(10);
}
@Test
public void findByName() throws Exception {
save();
assertThat(userRepository.findByNameLike("jege%")).hasSize(10);
}
@After
public void destroy() throws Exception {
userRepository.deleteAll();
}
}
源码地址
https://github.com/je-ge/spring-boot
如果觉得我的文章对您有帮助,请予以打赏。您的支持将鼓励我继续创作!谢谢!
Spring Boot 系列教程2-Data JPA的更多相关文章
- Spring Boot 系列教程17-Cache-缓存
缓存 缓存就是数据交换的缓冲区(称作Cache),当某一硬件要读取数据时,会首先从缓存中查找需要的数据,如果找到了则直接执行,找不到的话则从内存中找.由于缓存的运行速度比内存快得多,故缓存的作用就是帮 ...
- Spring Boot 系列教程16-数据国际化
internationalization(i18n) 国际化(internationalization)是设计和制造容易适应不同区域要求的产品的一种方式. 它要求从产品中抽离所有地域语言,国家/地区和 ...
- Spring Boot 系列教程14-动态修改定时任务cron参数
动态修改定时任务cron参数 不需要重启应用就可以动态的改变Cron表达式的值 不能使用@Scheduled(cron = "${jobs.cron}")实现 DynamicSch ...
- Spring Boot 系列教程9-swagger-前后端分离后的标准
前后端分离的必要 现在的趋势发展,需要把前后端开发和部署做到真正的分离 做前端的谁也不想用Maven或者Gradle作为构建工具 做后端的谁也不想要用Grunt或者Gulp作为构建工具 前后端需要通过 ...
- Spring Boot 系列教程8-EasyUI-edatagrid扩展
edatagrid扩展组件 edatagrid组件是datagrid的扩展组件,增加了统一处理CRUD的功能,可以用在数据比较简单的页面. 使用的时候需要额外引入jquery.edatagrid.js ...
- Spring Boot 系列教程7-EasyUI-datagrid
jQueryEasyUI jQuery EasyUI是一组基于jQuery的UI插件集合体,而jQuery EasyUI的目标就是帮助web开发者更轻松的打造出功能丰富并且美观的UI界面.开发者不需要 ...
- Spring Boot 系列教程15-页面国际化
internationalization(i18n) 国际化(internationalization)是设计和制造容易适应不同区域要求的产品的一种方式. 它要求从产品中抽离所有地域语言,国家/地区和 ...
- Spring Boot 系列教程10-freemarker导出word下载
freemarker FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页.电子邮件.配置文件.源代码等)的通用工具. 它不是面向最终用户的,而是一个 ...
- Spring Boot 系列教程19-后台验证-Hibernate Validation
后台验证 开发项目过程中,后台在很多地方需要进行校验操作,比如:前台表单提交,调用系统接口,数据传输等.而现在多数项目都采用MVC分层式设计,每层都需要进行相应地校验. 针对这个问题, JCP 出台一 ...
- Spring Boot 系列教程18-itext导出pdf下载
Java操作pdf框架 iText是一个能够快速产生PDF文件的java类库.iText的java类对于那些要产生包含文本,表格,图形的只读文档是很有用的.它的类库尤其与java Servlet有很好 ...
随机推荐
- hdu_3341_Lost's revenge(AC自动机+状态hashDP)
题目链接:hdu_3341_Lost's revenge 题意: 有n个模式串,一个标准串,现在让标准串重组,使得包含最多的模式串,可重叠,问重组后最多包含多少模式串 题解: 显然是AC自动机上的状态 ...
- 0. Java开发中的23种设计模式详解(转)
设计模式(Design Patterns) ——可复用面向对象软件的基础 设计模式(Design pattern)是一套被反复使用.多数人知晓的.经过分类编目的.代码设计经验的总结.使用设计模式是为了 ...
- [ An Ac a Day ^_^ ] hdu 4565 数学推导+矩阵快速幂
从今天开始就有各站网络赛了 今天是ccpc全国赛的网络赛 希望一切顺利 可以去一次吉大 希望还能去一次大连 题意: 很明确是让你求Sn=[a+sqrt(b)^n]%m 思路: 一开始以为是水题 暴力了 ...
- solr与tomcat整合
一.准备工作:我使用的是tomcat7.0,solr-4.8.1 solr-4.8.1解压后是这样的. 二.开始配置了 1.首先要创建两个文件夹.home和server.我是创建在与solr-4.8. ...
- ecos 问题答疑(转)
1.为什么我购买的是源码版,但是我的base/ego.php(或者base/ego/目录下文件)却是加密的? 答:ego 源码商业授权文件仅用于和商派软件签订源码协议的商业用户按照甲乙的源码保护约定 ...
- python--sorted函数和operator.itemgetter函数
1.operator.itemgetter函数operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号(即需要获取的数据在对象中的序号),下面看例子. a = [1 ...
- 执行 npm run update-webdriver 提示文件不能获取错误
按照angularjs官网的入门教程中输入 npm run update-webdriver 总是提示 https://chromedriver.storage.googleapis.com/2.1 ...
- Objective-C 2.0属性(Property)介绍
通常在声明一些成员变量时会看到如下声明方式: @property (参数1,参数2) 类型 名字: 这里我们主要分析在括号中放入的参数,主要有以下三种: setter/getter方法(assign/ ...
- JavaScript 事件 事件流 事件对象 事件处理程序 回调函数 error和try...catch和throw
参考资料: 慕课网 DOM事件探秘 js事件对象 处理 事件驱动: JS是采用事件驱动的机制来响应用户操作的,也就是说当用户对某个html元素进行操作的时候,会产生一个时间,该时间会驱动某些函数 ...
- Linux Ubuntu 14.04安装LAMP(Apache+MySQL+PHP)网站环境
从虚拟主机到VPS/服务器的过度,对于普通的非技术型的站长用户来说可能稍许有一些困难,麦子建议我们如果能够在虚拟主机环境中满足建站需要的, 还是用虚拟主机比较好.除非我们真的有需要或者希望从虚拟主机过 ...