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

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

问题描述

我需要编写一个选择查询,从 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= ?;

推荐答案

你的接口方法可以使用原生 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();
}

列表中的每一项都是一行数据的Object数组

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 Data 中的多个表中选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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