从Spring数据中的多个表中选择

时间:2014-07-08 17:50:00

标签: java spring hql spring-data spring-data-jpa

我需要编写一个select查询,从Spring Data Repository层中的多个表中获取数据。我知道我们可以使用@Query编写自定义查询,但只返回单个表中的值吗?

SELECT s.service_id, s.name, us.rating_id 
FROM services s, 
     ratings r, 
     user_services us
where 
    us.service_id = s.service_id and
    us.rating_id = r.rating_id and
    us.user_id= ?;

1 个答案:

答案 0 :(得分:5)

您的Interface方法可以使用本机SQL从多个表中选择列,该方法将返回一个对象数组列表:

public interface MyRepository extends JpaRepository {
  @Query(name = [name], nativeQuery = true)
  List<Object[]> methodThatQueriesMultipleTables();
}

列表中的每个项目都是Object数组,它是一行数据

您还可以创建自定义存储库实现:

How to add custom method to Spring Data JPA

@NoRepositoryBean
public interface CustomRepository<[Your object]> {
    List<Object[]> methodThatQueriesMultipleTables();
}

public class MyRepositoryImpl<[Your object]> implements CustomRepository<[Your object] {
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public List<Object[]> methodThatQueriesMultipleTables() {
        //use JPA query to select columns from different tables
        Query nativeQuery = entityManager.createNativeQuery("query");
        return query.getResultList();
    }
}