Issue
I have a table say A and table B. I wrote a query.
String s="select *
from A fch
inner join B ht on A.columnA = B.columnB
where columnD = 'ASDERT'
and
columnE = true
order by columnDate asc;";
I have a hibernate class for table A and table B separately. The issue is from the result set of
rdsSession.createNativeQuery(s).setParameter("columnD", columnD)
.addEntity(A.class).list();
this query I want to get some values from table B also. I have a class with variables as column names in table B. Do we have something as ResultSet in Hibernate so that I can use the column values of table B particularly?
Solution
You should read into how ORM mappings work and in particular how you can use association mappings for this. Your mappings could look like this:
@Entity
public class A {
@Id
@GeneratedValue
Integer id;
@ManyToOne(fetch = LAZY)
@JoinColumn(name = "columnA")
B b;
}
@Entity
public class B {
@Id
@GeneratedValue
@Column(name = "columnB")
Integer id;
String columnD;
boolean columnE;
LocalDateTime columnDate;
}
And then all you'd have to do is execute this HQL query:
List<A> list = rdsSession.createQuery("from A a join fetch a.b b where b.columnD = :columnD and b.columnE = true order by b.columnDate", A.class)
.setParameter("columnD", columnD)
.getResultList();
Using a native query requires you to use the same mapping, but then you would also have to add a join result, which also requires a slightly different SQL query:
List<A> list = rdsSession.createNativeQuery("select {a.*}, {b.*} from A a join B b on a.columnA = b.columnB where columnD = :columnD and columnE = true order by columnDate", A.class)
.setParameter("columnD", columnD)
.addEntity("a", A.class)
.addJoin("b", "a.b")
.list();
Answered By - Christian Beikov
Answer Checked By - Senaida (JavaFixing Volunteer)