使用Hibernate 只查詢部分字段,有三种字现方式:
第一种是使用高级查询DetachedCriteria实现,代碼如下:
String alias = "user_"; //查詢時的table別名
DetachedCriteria dc = DetachedCriteria.forClass(User.class,alias);
ProjectionList pList = Projections.projectionList();
pList.add(Projections.property(alias + "." + "id").as("id"));
pList.add(Projections.property(alias + "." + "name").as("name"));
pList.add(Projections.property(alias + "." + "age").as("age"));
pList.add(Projections.property(alias + "." + "sex").as("sex"));
dc.setProjection(pList);
dc.setResultTransformer(Transformers.aliasToBean(User.class));
resultList = memberService.findByDetached(dc).size();
第二种方式是通过HQL语句new POJO()实现,方法如下:
package com.domain;
public class Link {
private String id;
private String name;
private String url;
private Integer index;
public Link(){}
//因为:String hql = "select new Link(id,name) from Link";
//所以必须要有接受2个参数的构造函数
public Link(String id,String name){
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
通過HQL语句查询
String hql = "select new Link(id,name) from Link";
Query query = session.createQuery(hql);
//默认查询出来的list里存放的是一个Object对象,但是在这里list里存放的不再是默认的Object对象了,而是Link对象了
List<Link> links = query.list();
for(Link link : links){
String id = link.getId();
String name = link.getName();
System.out.println(id + " : " + name);
}
第三种方式是通过HQL语句实现,类似SQL,方法如下:
String hql = "select id,name from Link";
Query query = session.createQuery(hql);
//默认查询出来的list里存放的是一个Object数组,还需要转换成对应的javaBean。
List<Object[]> links = query.list();
for(Object[] link : links){
String id = link[0];
String name = link[1];
System.out.println(id + " : " + name);
}