将SQL本机查询映射到POJO类

时间:2018-04-02 10:34:53

标签: java hibernate jpa jpa-2.1 sqlresultsetmapping

我尝试使用@ConstructorResult @SqlResultSetMapping将本机SQL查询映射到POJO类,如下所示:

@SqlResultSetMapping(
        name = "AnomalieMapping",
        classes = @ConstructorResult(
                targetClass = Anomalie.class,
                columns = {
                        @ColumnResult(name = "anomalieElement", type = String.class),
                        @ColumnResult(name = "anomalieType", type = String.class),
                        @ColumnResult(name = "libelle", type = String.class) }))
public class Anomalie {

    private ElementAnomalieEnum anomalieElement;
    private TypeAnomalieEnum anomalieType;
    private String libelle;

    public Anomalie() {
        super();
    }

    public Anomalie(final String libelle, final String anomalieElement, final String anomalieType) {
        super();
        this.libelle = libelle;
        this.anomalieElement = ElementAnomalieEnum.valueOf(StringUtils.stripAccents(anomalieElement.toUpperCase()));
        this.anomalieType = TypeAnomalieEnum.valueOf(StringUtils.stripAccents(anomalieType.substring(5).toUpperCase()));

    }
//Getters and Setters
}

然后在创建本机查询时使用声明的结果集映射,我通过它的名称引用它:

Query query = entityManager.createNativeQuery(sqlQuery, "AnomalieMapping");
return query.getResultList();

但这对我不起作用我收到以下错误:

  

org.hibernate.MappingException:未知的SqlResultSetMapping   [AnomalieMapping]

这是我在SGBD中执行时我的SQL查询生成的内容:

enter image description here

1 个答案:

答案 0 :(得分:0)

这就是我解决问题的方法:

我没有声明@SqlResultSetMapping注释,而是在orm.xml文件中将其声明为:

<sql-result-set-mapping name="AnomalieMapping">
        <constructor-result target-class="xxx.Anomalie">
            <column name="libelle"/>
            <column name="anomalieElement"/>
            <column name="anomalieType"/>
        </constructor-result>
    </sql-result-set-mapping>

然后在我的DAO中我得到如下结果:

Query query = entityManager.createNativeQuery(sqlQuery, "AnomalieMapping");
return query.getResultList();