[英]Spring Data JPA method for getting the Entity with Joined table
我有一个非常具体的问题。 我有带有某些变量的实体“ 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转换器,从实体到表以及从表到实体都没有任何问题。
基于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")
根据您的问题描述
基本上,您想获取实体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
}
}
但这不是优化的解决方案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.