Java 从 Spring Data 中的多个表中选择
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24638465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Selecting from Multiple Tables in Spring Data
提问by Himalay Majumdar
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?
我需要编写一个选择查询,从 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= ?;
采纳答案by souser
Your Interface method can use native SQL to select columns from multiple tables and the method will return a list of object arrays :
您的接口方法可以使用本机 SQL 从多个表中选择列,该方法将返回一个对象数组列表:
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
列表中的每一项都是一行数据的Object数组
You can also create a Custom Repository Implementation :
您还可以创建自定义存储库实现:
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();
}
}