如何重用Spring Data JpaRepository接口

时间:2016-08-30 11:58:09

标签: java spring oop spring-data-jpa

(使用Java 8)

我有一个Spring Data JPA存储库接口,我在持久层中使用它。它负责表A。

以下是界面的代码:

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);
    ...
}

某些查询与辅助表A1连接。

我现在有表B,它与表A相同,但名称除外。表B使用表B1作为连接,这与表A1相同。

界面有很多方法,我讨厌复制代码。

我有没有办法创建一个与TableAJPARepository完全相同的界面,而是处理表B和B1呢?

1 个答案:

答案 0 :(得分:0)

您可以考虑创建自定义存储库 - 请注意@NoRepositoryBean注释 -

import org.springframework.data.repository.*;

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

第一种方法不需要@Query,因为Distinct是spring jpa上的方法名称选项 -

List<T> findDistinctUsernames();

我需要考虑更新 - 但你可能会使用泛型来实现这个