javapostgresqlhibernatejpasqlresultsetmapping

Java JPA Hibernate SqlResultSetMapping Aliases


In Java application which uses JPA 2.1 with Hibernate 4.3.11 implementation I am trying to use SqlResultSetMapping to map native query results to entity. Query includes joined two tables with same column names, so I need to use aliases and map them (issue described here: http://www.tinesoft.com/java/be-aware-of-mutliple-result-mappings-in-jpa)

For simplicity of question I shrank query and entity to minimum, that still causes the issue. Real code uses two entities and DB function, which is the reason for using native query instead of JPQL.

Gateway entity:

@Entity
public class Gateway implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private Integer active;
    ...
    @Column(name = "activation_code")
    private String activationCode;
    ...
}

SqlResultSetMapping:

@SqlResultSetMapping(
        name = "GatewayWithLoc",
        entities = {
            @EntityResult( entityClass = Gateway.class , fields =     @FieldResult(name = "id", column = "gw_id"))
        }
)

Query:

Query query = em.createNativeQuery("SELECT gw.id AS gw_id, ..., active, activation_code, ... FROM gateway gw", "GatewayWithLoc");
List<Object[]> rows = query.getResultList();

Exception:

Caused by: org.postgresql.util.PSQLException: The column name activati2_1_0_ was not found in this ResultSet.
at org.postgresql.jdbc2.AbstractJdbc2ResultSet.findColumn(AbstractJdbc2ResultSet.java:2803)
...

If I use SELECT * without fields = @FieldResult... in SqlResultSetMapping, code works as expected, but I can't do that because of same column names in different tables.

I will solve this by manual mapping results to entities as I need quick solution, but it would be great to know if I am doing something wrong or Hibernate does not support what I am trying to do. Book "Pro JPA 2" contains very similar example which is supposed to work.

Update: Tested with Hibernate 5.1.1 (Spring 4.3.2) - same result

Update: It looks like all column names need to be specified as mentioned in multiple answers. This seems like a big issue of JPA/Hibernate to me - those column names could be derived from entity, with just exceptions specified manually. Instead, I need to write column names 3 times (1. query, 2. result set mapping 3. entity) which is ugly and difficult to maintain.


Solution

  • I think you need to specify all the @FieldResult explicitly especially since you have column names that are conflicting between the two tables.