1

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

ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
Abhay
  • 129
  • 1
  • 5

1 Answers1

0

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

Community
  • 1
  • 1
Roland
  • 22,259
  • 4
  • 57
  • 84