iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >JPA中JpaRepository接口的使用方式
  • 371
分享到

JPA中JpaRepository接口的使用方式

2024-04-02 19:04:59 371人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

目录JPAJpaRepository接口的使用springData的所有接口JpaRepository继承自定义接口的主意事项整体代码如下解决方案JPA JpaRepository接

JPA JpaRepository接口的使用

SpringData的所有接口

CrudRepository接口 ,其中提供了这些方法提供使用,同时继承了其父接口的方法

其中saveAndFlush()方法就相当于hibernate中的saveOrUpdate()和JPA中的merge()


	@Test
	public void JpaRepository() {
		Person person = new Person();
		person.setId(27);
		person.setName("ab");
		person.setAge(22);
		person.setEmail("ab@qq.com");
		//该方法就相当于hibernate中的saveOrUpdate()和JPA中的merge()
		personRepositoiry.saveAndFlush(person);
	}

该接口提供了JPA的相关功能


List<T> findAll(); //查找所有实体
List<T> findAll(Sort sort); //排序、查找所有实体
List<T> save(Iterable<? extends T> entities);//保存集合 void flush();//执行缓存数据库同步
T saveAndFlush(T entity);//强制执行持久化
void deleteInBatch(Iterable<T> entities);//删除一个实体集合

Jpa Repository继承自定义接口的主意事项

今天翻看别人写的项目,看到大神在Repository的接口里又继承了一个自定义接口,觉得这样写挺好,后面注入还是用原来Repository,然后我就把当下自己手里项目也改了改,结果启动报错,错误信息大致如下。

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'TestService': Unsatisfied dependency expressed through field 'repository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'TestRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Failed to create query method public abstract void net.csdn.repository.Test.batchSave(java.util.List)! No property batchSave found for type TestEntity!

整体代码如下

1.自定义接口


public interface Test{
    public void batchSave(List<TestEntity> list);
}

2.创建一个接口,该接口 extends JpaRepository 或者 CurdRepository, 以及上面自己定义的接口 Test


public interface TestRepository extends CrudRepository<TestEntity, Integer>, Test{
}

3.实现TestCustom自定义接口,类名我自然而然写成TestService此类的


public class TestService implements Test{
 public void batchSave(List<TestEntity> list){
  //.....
 }
}

解决方案

自定义接口的实现类名是有要求的,必须以 2 中创建的接口的名字TestRepository加上 Impl 来声明,例如


public class TestRepositoryImpl implements Test{
 public void batchSave(List<TestEntity> list){
  //.....
 }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: JPA中JpaRepository接口的使用方式

本文链接: https://www.lsjlt.com/news/158133.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作