Java Spring数据是一种获取具有联接表的实体的JPA方法
我有一个非常具体的问题。我有一个实体A,它有一些变量和一个到其他表B的关系。我想创建一个查询,使用Locale参数从表B中获取实体A的id和值 表B具有对实体的转换 例如:Java Spring数据是一种获取具有联接表的实体的JPA方法,java,spring,spring-data-jpa,Java,Spring,Spring Data Jpa,我有一个非常具体的问题。我有一个实体A,它有一些变量和一个到其他表B的关系。我想创建一个查询,使用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:
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
现在我得到了:
[{ id: 1, tabParam: [ {value: "ASDF2"},{value : "ASDF"}]}]
JPA存储库中的我的方法:
List<A> findByTabParamLocale(Locale locale)
我正在使用Locale Hibernate转换器从实体到表,从表到实体,没有任何问题。根据您的问题描述 基本上,你想要得到实体A的Id。同样,你的JPA方法看起来很好,只是你需要更改才能得到实体A的Id 而不是
List<A> findByTabParamLocale(Locale locale);
AIdDto是投影接口。您将创建如下内容
public AIdDto {
Integer getId(); // This is id getter method of Enity A.
}
更多细节。请参考spring数据jpa参考文档
通过投影,您可以尝试使用像这样的创建自定义项目值映射器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
}
}
但这不是基于EntityB.id\u A+EntityB的优化解决方案。区域设置是唯一的。使用下面的投影代码获得您想要的:
// 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")
谢谢@Dhiren的回答。我得到:PropertyReferenceException:找不到类型Locale的projectedBy属性。我是否应该使用任何注释或编写不同的内容?是否可以使用AIDDTFindBytabParam_LocaleLocale locale;使用NonuiQueId生成错误的简单帮助。对于列表,我得到了结果:[{id:1},{id:2}]。我想用实体B中的值获取id。投影可用于连接表或仅适用于一个实体?通过spring数据jpa投影获得与连接表的精确匹配有点棘手。也可以通过连接表提取该值。需要编写自定义值映射器bean。最好使用上面提到的@rj hwang Answer谢谢你的回复。回答得好!我使用第二个查询first也可以,但在这个场景中,秒更适合。我必须更改它:@Queryselect id_A as id,locale as locale from EntityB,其中local=?1。使用locale而不使用as locale时,我将null重命名为locale。区域设置作为区域设置是不必要的,只要使用区域设置就可以了。
@Component
class ProjectionBean {
String getLocale(EntityA entityA) {
//Write the logic for find the exact 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")