Spring Data JPA官方参考文档笔记(一)

本文介绍了如何使用Spring Data JPA,包括核心接口Repository的使用,通过JavaConfig或XML配置创建存储库实例,以及如何区分不同数据模块如MySQL和MongoDB。文章详细阐述了4个步骤:定义存储库接口,定义查询方法,创建存储库实例,以及自定义实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

官方Spring Data JPA参看文档 2.1.9.RELEASE

1. 如何使用 Spring Data JPA ?

核心接口Repository ,Spring在此接口上使用了**@Indexed**注解

在继承了Repository接口的公共接口上使用了NoRepositoryBean注解

1.业务中要实现实体类增删改查,则要新建自己的接口去继承Repository接口或者去继承Repository接口的子接口,自己新建的接口需要把要操作的实体类和该类的主键类型作为泛型

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

2.在自己建的接口里面定义操作实体类的增删改查方法

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

3.设置Spring以使用JavaConfig或XML配置为这些接口创建代理实例
3.1 JavaConfig方式,@EnableJpaRepositories注解

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

@EnableJpaRepositories
class Config {}

3.2 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>

4.注入存储库实例并使用它

class SomeClient {

  private final PersonRepository repository;

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

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

以上就是使用Spring Data JPA的4个步骤,总结如下:

  • 定义存储库接口:继承Repository接口
  • 定义查询方法:根据JPA语法定义查询方法
  • 创建存储库实例:配置JavaConfig或者XML让Spring自动注入接口的实例
  • Spring数据存储库的自定义实现

1.2 区分数据模块(数据库MySQL、MonogoDB)的方法

  1. 看自己定义的接口继承的接口是哪个数据模块的
// JPA
interface MyRepository extends JpaRepository<User, Long> { }

@NoRepositoryBean
interface MyBaseRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {
  …
}

interface UserRepository extends MyBaseRepository<User, Long> {
  …
}
  1. 看实体类的注解使用的是什么数据模块的注解
interface PersonRepository extends Repository<Person, Long> {
 …
}

// JPA数据模块
@Entity
class Person {
  …
}

interface UserRepository extends Repository<User, Long> {
 …
}

//mongoDB数据模块
@Document
class User {
  …
}
  1. 看自己定义的接口所在的包,包定义了扫描接口定义
@EnableJpaRepositories(basePackages = "com.acme.repositories.jpa")//定义在这个包里的接口是JPA数据模块
@EnableMongoRepositories(basePackages = "com.acme.repositories.mongo")//定义在这个包里的接口是mongodb数据模块
interface Configuration { }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值