问题
I try to map a native query to a non-Entity class. I have the following Entity:
@Entity
@Table(name = "Groups")
@SqlResultSetMapping(name = "groupList", classes = {
@ConstructorResult(targetClass = GroupListEntry.class, columns = {
@ColumnResult(name = "id", type = Long.class),
@ColumnResult(name = "name", type = String.class),
@ColumnResult(name = "typeId", type = Long.class),
@ColumnResult(name = "lastUpdateDate", type = Date.class)
})
})
public class GroupEntity implements Serializable {
...
}
I expected that calling
final Query query = getEntityManager().createNativeQuery(q.toString(), "groupList");
final List<GroupListEntry> result = Collections.checkedList(query.getResultList(), GroupListEntry.class);
will result in creating GroupListEntry
objects using the following constructor (as it is described in @ColumnResult
annotations)
public GroupListEntry(
final Long groupId,
final String name,
final Long typeId,
final Date lastUpdateDate) {
...
}
but it turned out that the expected constructor is dependent on the underlying database... In integration tests I use HSQLDB and JPA/Hibernate tries to call:
public GroupListEntry(
final BigInteger groupId,
final String name,
final BigInteger typeId,
final Date lastUpdateDate) {
...
}
whereas on a development environment, where MSSQL is used, it calls:
public GroupListEntry(
final Integer groupId,
final String name,
final Integer typeId,
final Date lastUpdateDate) {
...
}
Apparently the specified type in each @ColumnResult
is simply ignored. I want to have only one constructor instead of three.
Below is a fragment of my pom.xml
file:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
Am I missing something?
Writing some annotations is much more elegant than manual mapping after executing a query, but I cannot force it to work properly.
Regards,
M
回答1:
The answer is that your expectation was correct, namely the following is true for Hibernate 4.3.5:
Apparently the specified type in each @ColumnResult is simply ignored.
There is an official Hibernate bug for this: HHH-8237 - Type mapping of @ColumnResult is ignored. As you can see there, this bug was fixed in Hibernate version 4.3.6.
来源:https://stackoverflow.com/questions/24761770/constructorresult-mapping-in-jpa-2-1-does-not-work-properly-with-hibernate-4-3