Spring Data JPA方法,用于获取具有连接表的实体

时间:2018-10-15 18:18:50

标签: java spring spring-data-jpa

我有一个非常具体的问题。我有一个带有一些变量的实体“ A”,并且与其他表“ B”具有OneToMany关系。我想创建查询以使用Locale参数从表“ B”中获取实体“ A”的id和值。

表B对实体进行了翻译。

示例:

Entity A:
  id: 1
  var_1: "SDFA"
  OneToMany
  List<B> tabParam;

Entity B:
  id: 2
  value: "ASDF2"
  locale: "en-EN"
  id_A: 1

Entity B:
  id: 3
  value: "ASDF"
  locale: "fr-FR"
  id_A: 1

我想合并这两个表以获取语言环境“ fr-FR”:

[ {id: 1, value: "ASDF" }]

现在我得到了:

[{ id: 1, tabParam: [ {value: "ASDF2"},{value : "ASDF"}]}]

我的JPA存储库中的方法:

List<A> findByTabParamLocale(Locale locale)

我正在使用从实体到表以及从表到实体的Locale Hibernate转换器。

2 个答案:

答案 0 :(得分:1)

基于EntityB.id_A + EntityB.locale的唯一。使用波纹管投影代码来获得想要的东西:

// define the dto interface
public interface LocaleDto {
  Integer getId();
  String getLocale();
}

// define a interface method in your repository
@Query("select a.id, b.locale from EntityA a join a.tabParam b where b.locale = ?1")
List<LocaleDto> findByTabParamLocale(Locale locale)

// or use
@Query("select id_A as id, locale from EntityB where locale = ?1")

答案 1 :(得分:0)

根据您的问题描述

基本上,您想获取实体A的ID。此外,您的JPA方法看起来还不错,只有您需要更改获取实体A的ID。

代替

 List<A> findByTabParamLocale(Locale locale);

使用此

AIdDto findByTabParamLocaleProjectedBy(Locale locale);

AIdDto是投影界面。您将创建如下

public AIdDto {

  Integer getId(); // This is id getter method of Enity A.
}

有关更多详细信息。请参考spring data jpa参考文档。

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections

通过投影,您可以尝试使用像这样创建自定义项目值映射器bean

修改AIdDto

 public AIdDto {

  @Value("#{target.id}")
  Integer getId();

  @Value("#{@projectionBean.getLocale(target)}")
  String getLocale();
}

创建ProjectionBean

@Component
class ProjectionBean {

  String getLocale(EntityA entityA) {
    //Write the logic for find the exact EntityB Locale
  }

}

但这不是优化的解决方案