jpa接口详解

快来打我* 2022-12-02 01:15 355阅读 0赞

jpa接口详解

  • Repository
  • CrudRepository
  • PagingAndSortingRepository
  • QueryByExampleExecutor

    @Data
    @Entity // 声明这个类对应了一个数据库表
    @Table(name = “BB_CLOTHES”) // 声明了数据库实体对应的表信息,如果没有指定,则表名和实体的名称保持一致
    public class Clothes implements Serializable{

    1. private static final long serialVersionUID = -3018808522887346432L;
    2. @Id
    3. @GeneratedValue(strategy=GenerationType.IDENTITY)//主键由数据库自动生成
    4. private Long id;
    5. @Column(length = 32)
    6. private String name;
    7. @Column(length = 32)
    8. private Integer size;
    9. @Column(length = 64)
    10. private Float price;

    }

在这里插入图片描述

Repository

中央存储库标记接口
T: 实体类
ID: 实体类的主键类型

  1. @Indexed
  2. public interface Repository<T, ID> {
  3. }

CrudRepository

通用的增删改查接口

  1. public interface CrudRepository<T, ID> extends Repository<T, ID> {
  2. <S extends T> S save(S entity);
  3. <S extends T> Iterable<S> saveAll(Iterable<S> entities);
  4. Optional<T> findById(ID id);
  5. boolean existsById(ID id);
  6. Iterable<T> findAll();
  7. Iterable<T> findAllById(Iterable<ID> ids);
  8. long count();
  9. void deleteById(ID id);
  10. void delete(T entity);
  11. void deleteAll(Iterable<? extends T> entities);
  12. void deleteAll();
  13. }
  14. @Autowired ClothesDao clothesDao;
  15. @GetMapping("/testCrudRepository")
  16. Object testCrudRepository(Clothes clothes) {
  17. log.info("【clothes】={}", clothes);
  18. // 保存对象
  19. clothesDao.save(clothes);
  20. // 保存列表里面的对象 对每条记录分别执行 insert into bb_clothes (name, price, size) values (?, ?, ?)
  21. ArrayList<Clothes> saveList = new ArrayList<>();
  22. Clothes saveO1 = new Clothes();saveO1.setName("save1");
  23. Clothes saveO2 = new Clothes();saveO2.setName("save2");
  24. saveList.add(saveO1);
  25. saveList.add(saveO2);
  26. clothesDao.saveAll(saveList);
  27. // 根据id查找 返回 Optional<Clothes> 对象
  28. Optional<Clothes> clothesOpt = clothesDao.findById(1l);
  29. clothesOpt.ifPresent(c -> log.info("【findById】={}", c));
  30. // 根据id查找记录是否存在
  31. log.info("【existsById】={}", clothesDao.existsById(1l));
  32. // 查找全部
  33. log.info("【findAll】={}", clothesDao.findAll());
  34. // 查找指定id列表对应的对象列表
  35. List<Long> idList = new ArrayList<>();
  36. idList.add(1l);
  37. idList.add(2l);
  38. log.info("【findAllById】.Iterable={}", clothesDao.findAllById(idList));
  39. log.info("【count】={}", clothesDao.count());
  40. // 根据id删除, 先查询数据库是否有该记录,如果有删除,否则删除不存在数据会抛出异常
  41. Optional<Clothes> beDeleteObject = clothesDao.findById(9l);
  42. beDeleteObject.ifPresent(c -> clothesDao.delete(c));
  43. // 最终执行的删除操作 delete from bb_clothes where id=?
  44. Optional<Clothes> opt = clothesDao.findById(24l);
  45. opt.ifPresent(c -> {
  46. clothesDao.delete(c);
  47. });
  48. // 删除所有数据 select * from bb_clothes;
  49. // 对每条记录 delete from bb_clothes where id=?
  50. // clothesDao.deleteAll();
  51. // 对每条记录遍历删除 delete from bb_clothes where id=?
  52. List<Clothes> deleteList = clothesDao.findAllById(idList);
  53. clothesDao.deleteAll(deleteList);
  54. return deleteList;
  55. }

PagingAndSortingRepository

增加分页和排序功能

  1. @NoRepositoryBean
  2. public interface PagingAndSortingRepository<T, ID> extends CrudRepository<T, ID> {
  3. Iterable<T> findAll(Sort sort);
  4. Page<T> findAll(Pageable pageable);
  5. }
  6. @SuppressWarnings("unused")
  7. @GetMapping("/testPagingAndSortingRepository")
  8. Object testPagingAndSortingRepository(Clothes clothes) {
  9. // 指定排序字段查找全部
  10. Sort sort01 = new Sort(Direction.ASC, "name");
  11. Sort sort02 = Sort.by(Direction.ASC, "name");
  12. Order idOrder = new Order(Direction.DESC, "id");
  13. Order idOrder2 = new Order(Direction.DESC, "name");
  14. Sort sort03 = Sort.by(idOrder,idOrder2);
  15. Sort sort04 = Sort.by(Direction.ASC, "id", "name");
  16. Sort sort05 = Sort.by("id", "name");
  17. log.info("【findAll】.sort={}", clothesDao.findAll(sort01));
  18. int pageIndex = 1;
  19. Pageable pageable=PageRequest.of(pageIndex-1, 2,sort01);
  20. Pageable pageable02 = PageRequest.of(pageIndex-1, 2, Direction.ASC, "id");
  21. Pageable pageable03 = PageRequest.of(pageIndex-1, 2, Direction.ASC, "id", "name");
  22. Page<Clothes> page = clothesDao.findAll(pageable);
  23. return page;
  24. }

QueryByExampleExecutor

  1. public interface QueryByExampleExecutor<T> {
  2. <S extends T> Optional<S> findOne(Example<S> example);
  3. <S extends T> Iterable<S> findAll(Example<S> example);
  4. <S extends T> Iterable<S> findAll(Example<S> example, Sort sort);
  5. <S extends T> Page<S> findAll(Example<S> example, Pageable pageable);
  6. <S extends T> long count(Example<S> example);
  7. <S extends T> boolean exists(Example<S> example);
  8. }
  9. @RestController
  10. @RequestMapping("/example")
  11. @Slf4j
  12. public class QueryByExampleController {
  13. @Autowired ClothesDao clothesDao;
  14. @GetMapping("/findOne")
  15. Object findOne(Long id) {
  16. // 1、 精准匹配对象,查出多条会报错
  17. Clothes ClothesObject = new Clothes();
  18. ClothesObject.setId(id);
  19. Example<Clothes> example = Example.of(ClothesObject);
  20. Optional<Clothes> optClothes = clothesDao.findOne(example);
  21. optClothes.ifPresent(c -> log.info("【findOne】.sort={}", c));
  22. return optClothes.get();
  23. }
  24. @GetMapping("/findAll")
  25. Object findAll() {
  26. Clothes Clothes = new Clothes();
  27. Clothes.setName("黑");
  28. ExampleMatcher matcher = ExampleMatcher.matching();
  29. // 注意matcher.withMatcher返回一个新的对象
  30. matcher = matcher.withMatcher("name", match -> match.startsWith());
  31. // matcher = matcher.withMatcher("name", match -> match.regex());
  32. // matcher = matcher.withMatcher("name", match -> match.endsWith());
  33. // matcher = matcher.withMatcher("name", match -> match.contains());
  34. // matcher = matcher.withIgnorePaths("name");
  35. // ExampleMatcher matcher = ExampleMatcher.matching().withMatcher("name", ExampleMatcher.GenericPropertyMatchers.endsWith());
  36. Example<Clothes> example = Example.of(Clothes, matcher);
  37. Sort sort = Sort.by(Direction.ASC, "name");
  38. List<Clothes> findAll = clothesDao.findAll(example, sort);
  39. log.info("【findAll】.example, sort, {}", findAll);
  40. return findAll;
  41. }
  42. @GetMapping("/getPage")
  43. Object getPage() {
  44. Clothes Clothes = new Clothes();
  45. Clothes.setName("衬衫");
  46. ExampleMatcher matcher = ExampleMatcher.matching();
  47. matcher = matcher.withMatcher("name", match -> match.contains());
  48. Example<Clothes> example = Example.of(Clothes, matcher);
  49. Pageable pageable = PageRequest.of(0, 15, Direction.DESC, "name");
  50. Page<Clothes> page = clothesDao.findAll(example, pageable);
  51. log.info("【findAll】.example, pageable={}", page);
  52. return page;
  53. }
  54. }

发表评论

表情:
评论列表 (有 0 条评论,355人围观)

还没有评论,来说两句吧...

相关阅读

    相关 JPA详解

    一、JPA是什么 1. PA(Java Persistence API)是Java持久化规范,是ORM框架的标准,主流ORM框架都实现了这个标准。 2. ORM是一种