您现在的位置是:首页 > java技术交流java技术交流
Spring Data JPA数据操作总结. findById getOne findOne save delete 等
上善若水2021-01-27 17:19:05【java技术交流】
5578人已围观
简介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)
随机图文
php把对象foreach 循环 Iterator遍历对象 php进阶
php高级技术把一个对象foreach循环遍历,很多框架中都实现了Iterator 然后就可以foreach去遍历这个对象,下面简单尝试编写一个简单的demo去循环遍历对象. class A implPHP8.1新特性 Final 类常量
PHP8.1新特性 Final 类常量 大家都知道cost修饰的常量是不可以改变的,然而再继承中却可以改变,新版的final就解决这个问题。旧版写法 class Foo { public coSpring Data JPA数据操作总结. findById getOne findOne save delete 等
mybatis和SpringDataJPA基本上就是主要的数据库持久层的框架,本篇自己使用jpa的基本增删改查的方式帮助大家快速上手SpringDataJPA.本篇使用的springboot版开心一笑, 爆笑简短的段子 ,幽默笑话
1、早上我去菜市场买青菜,我问小贩:“你这菜打过农药吗?”小贩想了想说:“估计打不过。”2、跟一女同事玩打手背的游戏,不小心抓到了她的手,破了一点表皮,然后女同事一脸认真的拿出手机,正在我以为她要拍照