0
votes

I am using QueryDSL-JPA on JBoss and want at one point select an entity from a different table than the one I am normally using and annotating via @Table. I do not want to create a separate Java class since in the end, it should return me the same class I am using.

Any idea on how to achieve this? Alternatively via the EntityManager or QueryDSL-SQL or Hiberate. Using this approach for accessing historic tables should not be so uncommon...

1
In FluentJPA this can be easily achieved by derivation. Potentially the same can be done in QueryDSL as well - Konstantin Triger

1 Answers

0
votes

The best way I could see was via custom SQL in JPA. QueryDSL does not allow this:

   final AbstractEntityPersister persister = getEntityPersister();
   final String[] idColumnNames = persister.getIdentifierColumnNames();
   Validate.isTrue(idColumnNames.length == 1);

   final String sql = "select * from " + getEntityPersister().getTableName() + HIST_TABLE_SUFFIX + " where " + idColumnNames[0] + " = ?";
   @SuppressWarnings("unchecked")
   final List<E> histList = em.createNativeQuery(sql, getEntityClass()).setParameter(1, id).getResultList();

using

@PersistenceContext(name = "MyDS")
protected EntityManager em;

protected AbstractEntityPersister getEntityPersister() {
    final MetamodelImplementor mm = (MetamodelImplementor) em.getEntityManagerFactory().getMetamodel();
    return (AbstractEntityPersister) mm.entityPersister(getEntityClass());
}