简体   繁体   中英

Nested Collection Using Hibernate Criteria

I have 2 table Tab1 and Tab2 .

Mapping of " Tab1 " to " Tab2 " is one-to-many .

Code is like that :

private Collection< Tab2 > obj = new ArrayList< Tab2 >();

@javax.persistence.OneToMany(fetch=javax.persistence.FetchType.LAZY,
                                                     mappedBy = "Tab1")

public Collection< Tab2 > getTab2() 
{ 
  return Tab2;
}

public void setTab2( Collection<Tab2 > val ) 
{ 
 this.Tab2 = val;
}

I want to fetch record from both table.

For example :
Tab1 has column:
Stu_Id, Stu_FirstName, Stu_LastName

Tab2 has column:
Stu_Id(foriegn Key),Stu_Subject, Stu_Teacher

Now I want to fetch Stu_id from Tab1 and Stu_Subject , Stu_Teacher from Tab2

You have different possibilities to solve your problem. Either you call a named query or you build your typed query with the CriteriaBuilder

There are already lots of other questions dealing with OneToMany -relations with either NamedQuery or CriteriaBuilder . It now depends on what you prefer. I personally prefer CriteriaBuilder due to the JPA-Metamodel you can use and the refactoring convenience it gives. (even though I wrote my own Wrapper to the CriteriaBuilder to get a better SQL -look-and-feel ;-))

Example for NamedQuery : Construct JPA query for a OneToMany relation

Example for TypedQuery : JPA CriteriaQuery OneToMany

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