简体   繁体   中英

JPA parent child relationship

I have a scenario where I need to load all the child values in one case and some specific child values in other . I am using a single bean for both the cases and writing the queries using named query.

@namedqueries{
@namedQuery(name="query1") = "select parent from Parent parent",
@namedQuery(name="query2") = "select parent from Parent parent",
}
Class Parent {

@manytomany
@join mentioned my join condition here // 
 List<Child> child ; 

}

Class Child 
{ 
 String A;
 String B;
 String C;

 @manytomany(mappedby = "child")
 List<parent> parent ; 
 }

Now in my query 2 I need to load only String A not String B and String C . I tried using

"select parent.child .A from Parent parent" as Query 2 

but getting the below error

 "Attempting to navigate to relation field via multi-valued association and
 jpql doesnt  allow traversal through multi valued relationship. Try join instead"

So any suggestions on how to proceed on this ..

1) Should I have to create a new bean for each Query
2) Or Can we control the child object parameters in specific named queries

You are accessing a collection when you say select parent.child and you can't say select parent.child.A this is wrong according HQL standards. You need to do this using join as the error message is suggesting:

select c.A from parent as p join p.child as c

Then no, you don't have to create a new bean for each query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM