1

I am building a system on top of an existing (old and messy) database. For this I'm building a JPA layer above the database, but I do not want to map my domain objects directly to the existing database tables.

I currently have a wrapper object that encapsulates 4 entities (data from 4 tables) in the database. Is there a way I can use this wrapper class as a parameter in a JPQL query?

It would be great if the wrapper class itself acted somewhat like a JPA entity, but without having the corresponding database table. Can this be achieved, and if so, how?


For example, how should I change Wrapper

public class Wrapper {
    private FirstJpaEntity first;
    private SecondJpaEntity second;
}

so that I can use something like

List<Wrapper> wrappers = ...;

TypedQuery<Wrapper> query = entityManager.createQuery(
              "SELECT wrap" // This is probably where the problem lies: JPA needs a Type for `wrap`, but this type needs to be an @Entity which `wrap` is not
            + " WHERE wrap IN :wrappers"
            + "   AND wrap.first.property = 1"
            + "   AND wrap.second.property = 2"
            , Wrapper.class);

query.setParameter("wrappers", wrappers);

I looked into making Wrapper an @Embeddable, hoping JPQL could figure out how to navigate through it, but alas @Embeddable objects cannot be queried directly.

neXus
  • 2,005
  • 3
  • 29
  • 53
  • Have you considered creating database views on top of your database tables and mapping your entities to these views? – Alan Hay Oct 08 '14 at 14:21
  • I know a view can be used as if it was a table, and that might solve our problem, but alas we are restricted. They don't like us messing with the database, even if it is only adding a view. For now, we have to use the database read-only. – neXus Oct 08 '14 at 14:24

1 Answers1

1

Perhaps you can use Multiple Tables via Secondary Tables Annotation/Mapping in your wrapper class?

This way your wrapper can be composed of the four underlying tables but offer a cleaner interface to the application.

xelamitchell
  • 522
  • 1
  • 6
  • 18
  • 9 months later, exactly the answer I was looking for. Thanks! – neXus Jul 07 '15 at 14:46
  • My pleasure. I'm glad I was able to find your question. – xelamitchell Jul 07 '15 at 16:00
  • 1
    A constructor expression might be handy here too-http://stackoverflow.com/questions/12271305/jpql-constructor-expression-org-hibernate-hql-ast-querysyntaxexceptiontable-i – chrismarx Jul 08 '15 at 14:59
  • Yes, I used this kind of constructor expression to create these wrapper-objects. But I needed this answer to use them as input to other queries. – neXus Jul 09 '15 at 12:43