3

I have 2 tables say

Table1 and Table2

Now Table1 has 3 columns say t1, t2, t3 and Table2 has 2 columns t4 and t5.

I have to fetch data from both tables by join but there is no mapped association between two tables in annotation or xml.

Now main issue is I have to use hibernate projection to fetch selected columns from both tables say t1,t2 from Table1 and t4 from Table2.

I have gone through the internet but have found examples of tables with association.

Glad if there will be any guidance on this.

Ankit
  • 2,753
  • 1
  • 19
  • 26

1 Answers1

2

Yes, this is supported in Hibernate. The only thing here is that we have to use HQL:

Multiple classes can appear, resulting in a cartesian product or "cross" join.

from Formula, Parameter
from Formula as form, Parameter as param

So in our case:

session
   .createQuery("SELECT t1.prop1, t1.prop2, t1.prop3 "
              + "       t2.prop4, t2.prop5 "
              + " FROM Entity1 AS t1, Entity2 As t2 " +
              // if there is some relation - unmapped
              + " WHERE t1.someProperty = t2.someProperty "
              + "   AND ... "
              )
   .setMaxResults(10) // we can even page here
   .list() 

NOTE: I used prop1, prop2 and Entity1, Entity2 ... to force the feeling that this is HQL. We are talking about mapped entities, not tables or columns

And we will recieve collection of object[] array...

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • Thanks Radim but I am using Hibernate criteria and hibernate projection to achieve this and I don't have any mappings between the entities representing Table1 and Table2. – Ankit Sep 05 '14 at 13:11
  • Once again ;) 1) This feature is supported only in HQL and 2) we do not have any relation between these tables! No. Check my HQL. it is just CROSS JOIN... and if you like... you can add WHERE... but you do not have to. It is **not** supported with Criteria. But if you will check that.. it is almost the same. As criteria and projection! Just pass result transformer.. SUMMARY: 1) with hql, 2) without any mapped relation and 3) with result [transformer](http://stackoverflow.com/a/25616261/1679310) ... you can have your results. NOTE: only thing needed is that both tables are mapped as entities – Radim Köhler Sep 05 '14 at 13:12
  • Thanks Radim I guess I will use HQL to achieve the same. – Ankit Sep 05 '14 at 13:19
  • Great sir! Enjoy awesome Hibernate ;) – Radim Köhler Sep 05 '14 at 13:19