1

I want to join two entities in a non-entity class, which will have the two entities as attributes of the class.

Take this as example:

@Entity
public class A {
}

@Entity
public class B {
}

public class C {
    private A a;
    private B b;
}

I found a solution using SqlResultSetMapping but I don't want to manually specify each column of A and B, because there would be 20+ columns.

The other solution that I found, was to use a JPQL query that will return an Object array results [ ], where results[0] is A and results[1] is B.

My ideea was a combination of both and I see it like this:

@SqlResultSetMapping(targetClass=C.class, 
entities={
@EntityResult (targetClass=A.class)
@EntityResult (targetClass=B.class)
}

Given that both A and B have multiple columns, which is the best way to solve my problem?

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
Alex Chihaia
  • 103
  • 2
  • 15

1 Answers1

1

IF you are using JPQL (and it also should work in hibernate) you can take advantage of the resultset class strategy.

1) Add constructor to your C class:

public C(A aEntity, B bEntity){
  this.a = aEntity;
  this.b = bEntity;
}

2) Create normal query and use NEW operator with fully qualified C class name which would take A and B as its constructor arguments:

Query query = session.createQuery("select new com.mypkg.C(a as aEntity, b as bEntity) 
                                   from A a, B b where a.id = b.a_id");
List<C> cList = (List<C>)query.list();
Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63