简体   繁体   English

如何重用Spring Data JpaRepository接口

[英]How to reuse a Spring Data JpaRepository interface

(Using Java 8) (使用Java 8)

I have a Spring Data JPA repository interface that I use in my persistence layer. 我有一个Spring Data JPA存储库接口,我在持久层中使用它。 It's in charge of table A. 它负责表A.

Here is the code of the interface: 这是界面的代码:

package com.bla.bla.persistence;

import com.bla.bla..EntityA;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional
public interface TableAJPARepository extends JpaRepository<EntityA, Long> {

    @Query("select distinct i.username from EntityA i")
    List<Integer> findDistinctUsernames();

    @Modifying
    @Query("update EntityA i set i.firstName = ?3 where i.lastName = ?1 and i.age < ?2")
    int updateEntityA(Integer age, String firstName, String lastName);

    @Query("select i from EntityA i where i.firstName = ?1 and (i.age =?2 or i.lastName =?3)")
    List<EntityA> findByFirstNameAndAgeOrLastName(String firstName, Integer age, String lastName);

    @Query("select DISTINCT(i) from EntityA i, EntityA1 r  where r.bookId=i.id " +
            "and i.firstName=?1 and r.title=?2 and i.lastName=?3 and i.age!=2 and i.age<=?4 " +
            "order by i.firstName Desc, i.age DESC ")
    List<EntityA> findBySomeFields(String firstName, String title, String lastName, Integer age,  Pageable pageable);
    ...
}

Some of the queries join with a helper table A1. 一些查询与辅助表A1连接。

I now have table B which is identical to table A, except for its name. 我现在有表B,它与表A相同,但名称除外。 Table B uses table B1 for the joins, which is identical to table A1. 表B使用表B1作为连接,这与表A1相同。

The interface has many methods and I'd hate to duplicate the code. 界面有很多方法,我讨厌复制代码。

Id there any way to create an interface that is exactly like TableAJPARepository but deals with table B and B1 instead? 我有什么方法可以创建一个与TableAJPARepository完全相同但是处理表B和B1的接口?

You could consider making a custom repository - note the @NoRepositoryBean annotation - 您可以考虑创建自定义存储库 - 请注意@NoRepositoryBean注释 -

import org.springframework.data.repository.*;

@NoRepositoryBean
public interface YourRepository<T, ID extends Serializable> extends Repository<T, ID> {
}

The first method shouldnt need @Query since Distinct is a method name option on spring jpa - 第一种方法不应该需要@Query,因为Distinct是spring jpa上的方法名称选项 -

List<T> findDistinctUsernames();

Id need to have a think on the update - but you could likely use generics for this 我需要考虑更新 - 但您可能会使用泛型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM