0

let say I have 2 tables joined by one-to-many relation

public class Slave
{
   @Id
   @Column(name = "id")
   long id;

   @JoinColumn(name = "master", referencedColumnName = "id")
   Master master;
}

public class Master
{
   @Id
   @Column(name = "id")
   long id;

   @OneToMany(mappedBy = "master", targetEntity = Slave.class)
   Collection<Slave> slaves;
}

Is it possible to create CriteriaQuery to select all Slaves of Master with known id? To generate SQL like this:

SELECT * FROM slave s WHERE s.master=XXX;

It should be CriteriaQuery not just "native query" like this

_entityManager.createNativeQuery( "SELECT s FROM master s WHERE s.master = ?1" );
query.setParameter( 1, XXX );

Thank you in advance

mirec
  • 627
  • 1
  • 8
  • 23

1 Answers1

0

I found some workaround. Not sure if it is part of JPA2 specs however for hibernate I was able to map another property to same DB column as Long. I just had to make it read-only using insertable=false, updatable=false

public class Slave
{
   @Id
   @Column(name = "id")
   long id;

   @Column(name = "master", insertable=false, updatable=false)
   long masterId;
   @JoinColumn(name = "master", referencedColumnName = "id")
   Master master;
}

then I just created CriteriaQuery using this property

mirec
  • 627
  • 1
  • 8
  • 23
  • Just a note, if you change `master` property, `masterId` isn't changed immediatelly, you need to persist entity and refresh it from EntityManager... – mirec Oct 04 '14 at 11:41