扩展spring数据的默认语法

时间:2016-06-12 22:12:53

标签: java spring spring-data

在我当前的项目中,几乎每个实体都有一个字段recordStatus,它可以有两个值:

  • A for Active
  • D已删除

在春季数据中,通常可以使用:

repository.findByLastName(lastName)

但是对于当前的数据模型,我们必须记住每个存储库调用中的活动部分,例如

repository.findByLastNameAndRecordStatus(lastName, A)

问题是:有没有办法以这样的方式扩展spring数据,它能够识别以下方法:

repository.findActiveByLastName(lastName)

并附加

recordStatus = 'A'

自动?

3 个答案:

答案 0 :(得分:1)

Spring Data JPA为您提供了2个额外的选项,可以处理他们的DSL默认无法处理的情况。

第一个解决方案是使用@Query注释的自定义查询

@Query("select s from MyTable s where s.recordStatus like 'A%'")
public MyObect findActiveByLastName(String lastName);

第二个解决方案是添加一个完全自定义的方法"旧时尚方式"您可以创建一个新的类设置,如:MyRepository Impl Impl非常重要,因为它是如何知道Spring找到您的新方法(注意:您可以避免这种情况,但您必须手动链接事物docs可以帮助你)

//Implementation
public class MyRepositoryImpl implements MyCustomMethodInterface {
   @PersistenceContext
   EntityManager em;

    public Object myCustomJPAMethod() {
       //TODO custom JPA work similar to this
       String myQuery = "TODO";
       return em.createQuery(myQuery).execute();
    }
}

//Interface
public interface MyCustomMethodInterface {
    public Object myCustomJPAMethod();
}

//For clarity update your JPA repository as well so people see your custom work
public interface MySuperEpicRepository extends JPARepository<Object, String>, MyCustomMethodInterface {

}

这些只是一些快速的示例,所以如果您希望获得更多的自定义,请随时阅读他们的Spring Data JPA文档。 http://docs.spring.io/spring-data/jpa/docs/current/reference/html/

最后只是一个快速说明。从技术上讲,这不是Spring Data JPA的内置功能,但您也可以使用Predicates。由于我对这种方法并不过分熟悉,因此我会将您链接到此博客上。 https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/

答案 1 :(得分:0)

您可以使用Spring Data的Specifications。请查看this文章。

如果使用recordStatus过滤器创建“基础”规范,并从中获取所有其他规范。

当然,团队中的每个人都应该使用api指令,而不是默认的spring数据api。

答案 2 :(得分:0)

我不确定是否可以扩展语法,除非您重写基类(SimpleReactiveMongoRepository;这是用于反应式mongo,但是您可以找到适合您的DB类型的类),我建议您扩展基本方法,然后让您的方法知道要执行的条件。如果您查看这篇文章,您会发现我对所有实体进行了补丁操作。

https://medium.com/@ghahremani/extending-default-spring-data-repository-methods-patch-example-a23c07c35bf9

相关问题