从Spring数据中的多个表中选择 [英] Selecting from Multiple Tables in Spring Data

查看:87
本文介绍了从Spring数据中的多个表中选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to write a select query fetching data from multiple tables in Spring Data Repository layer. I know we can use @Query to write custom queries, but that returns value from a single table only?

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= ?;


推荐答案

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

Your Interface method can use native SQL to select columns from multiple tables and the method will return a list of object arrays :

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

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

Each item in the list is Object array that is a row of data

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

You can also create a Custom Repository Implementation :

如何向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();
    }
}

这篇关于从Spring数据中的多个表中选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆