不论是nativequery还是hql的query,都可以指定需要查询的字段,只是必须定义这些字段所对应的实体,而且需要一个构造函数,构造函数的参数就是查询的字段列表。举个栗子:
查询人员的实体,我需要返回所有人员的名字。查询如下:
@Entity
@Table(name="Human")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Human {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer humanID;
private String humanName;
//人员代码
private String humanCode;
private String humanPassword;
private String description;
//所属单位
private Integer unitID;
private Integer displayOrder;
private Integer identifyType;
private Integer activeFlag;
public Human() {
}
public Human(String humanName) {
this.humanName = humanName;
}
//getter setter...
}
@Query("select new Human (h.humanName) from Human h ")
List<Human> getHumanList();
我们需要查询humanName,所以必须要有public Human(String humanName)这个构造函数,而且必须提供默认的构造函数,否则entity无法构造。
这样虽然方便,但是如果返回的字段偏多,那么这个构造函数就参数列表就很长。这种情况最好还是用nativequery,定义的接口其返回类型为List
对于Object[]返回结果的处理如果想做成通用的,可以参考下GSON的反序列化,通过传递T.class,通过反射去构造对象并设置字段。