jpa 如何使用@ConstructorResult注解

dpiehjr4  于 2022-12-13  发布在  其他
关注(0)|答案(2)|浏览(134)

我有一些本机查询,希望将查询执行结果Map到非实体POJO类列表中:

@SqlResultSetMapping(
    name = "SomeMapping",
    classes = {
        @ConstructorResult(targetClass = SomeClass.class,
            columns = {
                @ColumnResult(name = "id", type = Integer.class),
                @ColumnResult(name = "NAME", type = String.class),
                @ColumnResult(name = "DATE_BEGIN", type = java.util.Date.class)
            }
        )
    }
)

public class SomeClass{
    private Integer id;
    private String name;
    private java.util.Date begDate;
    private java.util.Date endDate;

    public SomeClass(Integer id, String name, Date begDate){
        this.id = id;
        this.name = name;
        this.begDate = begDate;
    }

    //Getters & Setters ...
}

以及通常我希望如何检索查询执行的结果:

String query = "SELECT " +
"A.id AS 'id', " +
"A.name AS 'NAME', " +
"A.begDate AS 'DATE_BEGIN' " + 
"FROM " +
"SomeTable A " +
"WHERE A.endDate < '2014-01-01'";

List<SomeClass> result = em.createNativeQuery(query, "SomeMapping").getResultList();

但我总是得到对象列表。如何检索我的POJO列表?

2nbm6dog

2nbm6dog1#

尝试在实体上移动@SqlResultSetMapping实体。

hfyxw5xn

hfyxw5xn2#

无法重现,但您的代码有一些问题。

  • 在实体类上添加@SqlResultSetMapping
  • 不要用'引用列别名

第一个

相关问题