Spring JPA 查询方法

2023年 3月 5日 34点热度 0人点赞 0条评论

标准 CRUD 功能存储库通常对底层数据存储有查询。使用 Spring Data,声明这些查询变成一个四步过程:

1、声明一个扩展 Repository 的接口或其子接口之一,并将其键入它应处理的域类和 ID 类型,如以下示例所示:

interface PersonRepository extends Repository<Person, Long> { … }

2、在接口上声明查询方法。

interface PersonRepository extends Repository<Person, Long> {
  List<Person> findByLastname(String lastname);
}

3、设置 Spring 以使用 JavaConfig 或 XML 配置为这些接口创建代理实例。

import org.springframework.data.….repository.config.EnableJpaRepositories;

@EnableJpaRepositories
class Config { … }

本例中使用了 JPA 命名空间。如果您对任何其他商店使用存储库抽象,则需要将其更改为存储模块的适当名称空间声明。换句话说,您应该将 jpa 换成 mongodb。

请注意,JavaConfig 变体不会显式配置包,因为默认使用注释类的包。要自定义要扫描的包,请使用数据存储特定存储库的 @EnableJpaRepositories-annotation 的 basePackage… 属性之一。

4、注入存储库实例并使用它,如以下示例所示:

class SomeClient {

  private final PersonRepository repository;

  SomeClient(PersonRepository repository) {
    this.repository = repository;
  }

  void doSomething() {
    List<Person> persons = repository.findByLastname("Matthews");
  }
}

本文来自:https://blog.duhbb.com

本文链接地址:Spring JPA 查询方法,英雄不问来路,转载请注明出处,谢谢。

有话想说:那就赶紧去给我留言吧。

rainbow

这个人很懒,什么都没留下

文章评论