返回介绍

4.2 查询方法

发布于 2020-08-26 12:31:29 字数 3908 浏览 1451 评论 0 收藏 0

标准的CRUD(增删改查)功能都要使用查询语句来查询数据库。但通过使用Spring Data,只要四个步骤就可以实现。

1.声明一个继承Repository接口或其子接口的持久层接口。并标明要处理的域对象类型及其主键的类型(在下面的例子中,要处理的域对象是Person,其主键类型是Long)

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

2.在接口中声明查询方法(spring会为其生成实现代码)

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

3.让Spring创建对这些接口的代理实例。
通过JavaConfig

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

@EnableJpaRepositories
class Config {}

通过XML配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:jpa="http://www.springframework.org/schema/data/jpa"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/data/jpa
     http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

   <jpa:repositories base-package="com.acme.repositories"/>

</beans>

这里使用JPA的命名空间作为例子,需要根据实际使用的模块更改命名空间,比如可以改为mongodb等等。需要注意的是,在使用JavaConfig时,如果需要自定义扫描的包而不是使用其默认值,可以利用注解@EnableJpaRepositories的basePackage属性。具体使用方式如下:

@EnableJpaRepositories(basePackages = "com.cshtong")//单个包
@EnableJpaRepositories(basePackages = {"com.cshtong.sample.repository", "com.cshtong.tower.repository"})//多个包路径

4.注入repository实例,并使用

public class SomeClient {

  @Autowired
  private PersonRepository repository;

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

这一部分会在之后详细解释

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文