Reputation: 97
I have very specific question. I have Entity "A" with some variables and OneToMany
relations to other table "B". I want to create query to get id
of entity "A" and value from table "B" using Locale parameter.
Table B have a translations to entity.
Example:
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
I want to merge those both table to get for locale "fr-FR":
[ {id: 1, value: "ASDF" }]
Now I got:
[{ id: 1, tabParam: [ {value: "ASDF2"},{value : "ASDF"}]}]
My method from JPA repository:
List<A> findByTabParamLocale(Locale locale)
I am using Locale Hibernate converter from entity to table and from table to entity without any problem.
Upvotes: 0
Views: 2850
Reputation: 1903
Base on EntityB.id_A + EntityB.locale
is unique. Use bellow projection code to get want you want :
// 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")
Upvotes: 1
Reputation: 163
Based on your question description
Basically you want to get Id of Entity A. Also your JPA method is look ok only you have need change to getting the Id of Entity A.
Instead of
List<A> findByTabParamLocale(Locale locale);
Use This
AIdDto findByTabParamLocaleProjectedBy(Locale locale);
AIdDto is projection interface. You will create as follows
public AIdDto {
Integer getId(); // This is id getter method of Enity A.
}
For more detail. Please refer the spring data jpa reference doc.
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections
Through the projection you can try using create custom project value mapper bean like that
Modify AIdDto
public AIdDto {
@Value("#{target.id}")
Integer getId();
@Value("#{@projectionBean.getLocale(target)}")
String getLocale();
}
Create ProjectionBean
@Component
class ProjectionBean {
String getLocale(EntityA entityA) {
//Write the logic for find the exact EntityB Locale
}
}
But this is not optimised solution
Upvotes: 0