Hibernate查询特定几个字段
1. 问题场景
考试系统开发中,类似考题、答题卡等对象,可能包含如“题目内容”、“答案及评语”等信息量非常大的字段,而实际使用中,列表显示不需要查询所有的对象属性,这时若把所有属性全部取出来太耗费资源,因此查询特定的几个字段就可以。
2. 实现方法
说明:实现方法可能有很多,这里只列出亲测有效的两种:
1.通过hql语句实现,分别获取字段数据并手动组装成对象
Question.java
package com.geariot.platform.exam.entities;
import java.util.Date;
import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table;
import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.GenericGenerator;
@Entity @Table(name="question") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region="javaClassName") public class Question {
private String id; private int level; //难度 private int type; //类别,单选题0,多选题1,填空题2,问答题3 private String typeName; //类别名称 private String abs;//题目缩略内容 private String content;//题目内容 private String subject;//科目名称 private String subjectId;//科目Id private Date createTime;//创建时间 private String answer; //标准答案
@Id @Column(length=32) @GeneratedValue(generator="system-uuid") @GenericGenerator(name="system-uuid", strategy="uuid") public String getId() { return id; } public void setId(String id) { this.id = id; }
public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public int getType() { return type; } public void setType(int type) { this.type = type; }
@Column(name = "type_name") public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getSubject() { return subject; } public void setSubject(String subject) {
|