您现在的位置是:首页 > java技术交流java技术交流
Spring Data JPA数据操作总结. findById getOne findOne save delete 等
上善若水2021-01-27 17:19:05【java技术交流】 4379人已围观
简介mybatis和SpringDataJPA基本上就是主要的数据库持久层的框架,本篇自己使用jpa的基本增删改查的方式帮助大家快速上手SpringDataJPA.本篇使用的springboot版
mybatis和Spring Data JPA基本上就是主要的数据库持久层的框架,本篇自己使用jpa的基本增删改查的方式帮助大家快速上手Spring Data JPA.
本篇使用的springboot版本为2.4.1 所依赖的jpa版本也是2.4.1不同版本会有些许差别.
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.4.1</version>
1. 实体于和repository
实体要使用包装类型
package com.fierykylin.jpa.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;
@Entity
@Data
@Table(name = "article")
@JsonIgnoreProperties(value = { "hibernateLazyInitializer"})
public class Article implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)//自增
private Integer id;
private Integer categoryId;
private String cover;
private String title;
private String introduction;
private String contentMarkdown;
private String content;
private Boolean top;
private Boolean recommend;
private Boolean hot;
private Integer browse;
private Integer up;
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime;
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss")
private LocalDateTime updateTime;
}
repository
package com.fierykylin.jpa.repository;
import com.fierykylin.jpa.entity.Article;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ArticleRepository extends JpaRepository<Article, Integer> {
}
2.方法基本使用
1.findById
通过id查找,没查询到就返回null
@Test
@Transactional
public void testFindById(){
Article one = articleRepository.findById(500).orElse(null);
}
2.getOne
通过id查找 采用懒加载 使用时才真正去查库.若id为查询到会异EntityNotFoundException
.
@Test
@Transactional
public void testGetOne(){
Article one = articleRepository.getOne(500);
String title = one.getTitle();
}
id为不存在报异常
javax.persistence.EntityNotFoundException: Unable to find com.fierykylin.jpa.entity.Article with id 500
3.findOne
所查询的结果必须是只包含一条结果,否则会报如下异常
org.springframework.dao.IncorrectResultSizeDataAccessException: query did not return a unique result: 2
查询标题包含故事 并且热门的文章!
@Test
@Transactional
public void testFindOne(){
Article article = new Article();
article.setHot(true);
article.setTitle("故事");
Example<Article> example = Example.of(article, ExampleMatcher.matching().withMatcher("title", ExampleMatcher.GenericPropertyMatcher::contains));
Article one = articleRepository.findOne(example).orElse(null);
}
4.findAllById
通过id查询多个 若未查询到则返回空集合
@Test
@Transactional
public void testFindAllById(){
List<Article> articles = articleRepository.findAllById(Arrays.asList(1,2,3));
}
5.findAllById
通过id查询多个 若未查询到则返回空集合
查询热门并且根据top升序id倒序查询
@Test
@Transactional
public void testFindAll(){
Article article = new Article();
article.setHot(true);
Example<Article> example = Example.of(article);
Sort sort = Sort.by(Sort.Order.asc("top"), Sort.Order.desc("id"));
List<Article> articles = articleRepository.findAll(example,sort);
YGDumper.tree(articles);
}
简单分页使用
@Test
@Transactional
public void testFindAll(){
Article article = new Article();
Example<Article> example = Example.of(article);
Sort sort = Sort.by(Sort.Order.asc("top"), Sort.Order.desc("id"));
PageRequest pageRequest = PageRequest.of(0, 2,sort);
Page<Article> articles = articleRepository.findAll(example,pageRequest);
YGDumper.tree(articles);
}
6.save
保存 需要配置主键自增策略 @Transactional注解要去掉不然会回滚数据添加失败!
@Test
public void testSave(){
Article article = new Article();
article.setTitle("测试添加");
Article save = articleRepository.save(article);
YGDumper.tree(save);
}
7.delete
删除 删除没有返回值
此种删除无效
@Test
public void testDelete(){
Article article = new Article();
article.setTitle("测试添加");
articleRepository.delete(article);
}
实际删除需要实体中包含id即可正确删除,可以直接先查询出实体,然后删除
@Test
public void testDelete(){
Article article = new Article();
article.setId(17);
articleRepository.delete(article);
}
//或者
@Test
public void testDelete(){
Article article = new Article();
article.setTitle("测试添加");
Article articleFind=articleRepository.findOne(Example.of(article)).orElse(null);
articleRepository.delete(articleFind);
}
7.deleteALL
删除所有数据 会执行两条sql 先查出所有id 然后根据id一条条的删除.慎用避免使用无参清空数据
@Test
public void testDeleteAll(){
articleRepository.deleteAll();
}
//删除指定 同样是依据ID进行删除操作
@Test
public void testDeleteAll1(){
Article article1 = new Article();
article1.setId(1);
Article article2 = new Article();
article2.setId(2);
ArrayList<Article> list = new ArrayList<>();
list.add(article1);
list.add(article2);
articleRepository.deleteAll(list);
}
出输入的sql可以看到,先查询的id,然后在进行删除.
8.count
查询数量 无参的方法会返回所有的记录
@Test
public void testCount(){
Article article = new Article();
article.setHot(true);
Example<Article> example = Example.of(article);
long count = articleRepository.count(example);
System.out.println(count);
}
目前就测试以上方法的基本用法,大部分方法都是都通过方法名就能轻松知道方法是怎么用的.本文只初略的总结了基本使用,更复杂的查询还待研究.
Tags: jpa
很赞哦! (53)
随机图文
-
PHP8.0新特性(6) Nullsafe 字符串与数字的比较更符合逻辑 Nullsafe operator
1.Nullsafe 运算符 $country = null; if ($session !== null) { $user = $session->user; if ($user != -
笑话几则:哄女孩开心的最佳方式,你知道么
1,老婆买了条狗,没事干就拿着人民币让狗闻。我感觉很奇怪,就问:老婆,你这是干嘛,让狗去给你大马路上捡钱?老婆神秘的一笑:“以后你就知道了!”没过几天,我的私房钱不见了,不说了,说多了都是泪。。。2,刚老婆妇儿拿圆珠笔不停的捣我的头,我说:别捣了,老是捣一个地方疼。老婆一巴掌过来:你也知道老是捣一个地方疼?3,千年后,在某山里住着一位修道千年的老神仙。某天,他徒弟突然问他:师傅,是什么让你 -
62个哄女孩开心的笑话,只为博你一笑!泡妞必备!
1.一天,牛给驴出了一个难题,问“蠢”字下面两只虫子哪只是公的,哪只是母的。驴绞尽脑汁,还是答不上来。牛骂道:真是头蠢驴,男左女右嘛!2.毕业后七年,总算接了个大工程,造一根三十米烟囱,工期两个月,造价三十万,不过要垫资。总算在去年年底搞完了。今天人家去验收,被人骂得要死,还没有钱拿。妈的!图纸看反了,人家是要挖一口井!3.一醉汉不慎从三楼掉下,引来路人围观,一警察过来:发生什么事?醉汉 -
linux 设置目录所属用户组 chown -R www:www /www/wwwroot/default
linux 设置目录所属用户组,我们经常需要将网站目录给设置成www用户组,每次老是忘记,只知道是chown命令例一:改变拥有者和群组命令:chown runoob:runoobgroup log1.