当前位置:编程学习 > JAVA >>

Hibernate - 查询部分字段

第一种是使用高级查询DetachedCriteria实现,代易做图如下:

[java] www.zzzyk.com
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 + "." + "易做图").as("易做图")); 
 
dc.setProjection(pList); 
 
dc.setResultTransformer(Transformers.aliasToBean(User.class)); 
 
resultList = memberService.findByDetached(dc).size(); 

通過HQL语句查询
[java] 
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,方法如下:

[java] 
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); 
 

 

 

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,