Hibernate的使用技巧②

1.Hibernate统计记录的数量

Criteria c = session.createCriteria(User.class.getName());  

    

c.setProjection(Projections.rowCount());  

    

CheckRowNumResponseBean result = new CheckRowNumResponseBean();  

result.setRowNum(Integer.parseInt(c.uniqueResult().toString()));  

setResult(result); 

 能使用的是c.list.size().返回的记录数,其实这样的话,hibernate是从数据库里面把所有满足条件的记录查询出来放到一个list里 面,然后再用list的length返回长度。这样不是此需求的初衷。因为这样会消耗性能。。。并且在数据过多的情况下面,会造成tomcat的 OutOFMemory错误

2.Hibernate封装vo

首先是    VO    实体

package com.ntej.exam.model.vo;

 

/**

* 考试信息展示,显示在我的考试界面 和我的成绩界面

*

*/

public class ExamInfoVO {

 

    private String E_ID;

    private String E_Name;

    private Integer E_Score;

    private String MajorType;

    private String MajorName;

    private String ExamTitle;

    private Integer QuestionNumber;

    private Integer TotalTime;

    private String ExamBeginDateTime;

    private String ExamEndDateTime;

    private Integer ExamCode;

 

    public String getE_ID() {

        return E_ID;

    }

 

    public void setE_ID(String e_ID) {

        E_ID = e_ID;

    }

 

    public String getE_Name() {

        return E_Name;

    }

 

    public void setE_Name(String e_Name) {

        E_Name = e_Name;

    }

 

    public Integer getE_Score() {

        return E_Score;

    }

 

    public void setE_Score(Integer e_Score) {

        E_Score = e_Score;

    }

 

    public String getMajorType() {

        return MajorType;

    }

 

    public void setMajorType(String majorType) {

        MajorType = majorType;

    }

 

    public String getMajorName() {

        return MajorName;

    }

 

    public void setMajorName(String majorName) {

        MajorName = majorName;

    }

 

    public String getExamTitle() {

        return ExamTitle;

    }

 

    public void setExamTitle(String examTitle) {

        ExamTitle = examTitle;

    }

 

    public Integer getQuestionNumber() {

        return QuestionNumber;

    }

 

    public void setQuestionNumber(Integer questionNumber) {

        QuestionNumber = questionNumber;

    }

 

    public Integer getTotalTime() {

        return TotalTime;

    }

 

    public void setTotalTime(Integer totalTime) {

        TotalTime = totalTime;

    }

 

    public String getExamBeginDateTime() {

        return ExamBeginDateTime;

    }

 

    public void setExamBeginDateTime(String examBeginDateTime) {

        ExamBeginDateTime = examBeginDateTime;

    }

 

    public String getExamEndDateTime() {

        return ExamEndDateTime;

    }

 

    public void setExamEndDateTime(String examEndDateTime) {

        ExamEndDateTime = examEndDateTime;

    }

 

    public Integer getExamCode() {

        return ExamCode;

    }

 

    public void setExamCode(Integer examCode) {

        ExamCode = examCode;

    }

 

    @Override

    public String toString() {

        return "ExamInfoVO [E_ID=" + E_ID + ", E_Name=" + E_Name + ", E_Score="

                + E_Score + ", MajorType=" + MajorType + ", MajorName="

                + MajorName + ", ExamTitle=" + ExamTitle + ", QuestionNumber="

                + QuestionNumber + ", TotalTime=" + TotalTime

                + ", ExamBeginDateTime=" + ExamBeginDateTime

                + ", ExamEndDateTime=" + ExamEndDateTime + ", ExamCode="

                + ExamCode + "]";

    }

 

}

查询方法

public List<ExamInfoVO> getExamInfoVosByemp(Emp emp){

        try {

             String queryString = "     SELECT e.E_ID,e.E_Name,s.E_Score,m.MajorType,m.MajorName,ei.ExamTitle,ei.QuestionNumber,ei.TotalTime,DATE_FORMAT(ei.ExamBeginDateTime,'%Y-%m-%d %H:%i:%s') as ExamBeginDateTime,DATE_FORMAT(ei.ExamEndDateTime,'%Y-%m-%d %H:%i:%s') as ExamEndDateTime, ei.ExamCode"

                     + " FROM emp e,score s,major m,examinfo ei WHERE    e.E_ID=s.E_ID AND e.D_No=ei.D_No AND s.MajorID=m.MajorID AND s.ExamCode=ei.ExamCode AND e.E_ID='"+emp.getEId()+"';";

     Query query= getSession().createSQLQuery(queryString);

     List<ExamInfoVO> list = query.setResultTransformer(Transformers.aliasToBean(ExamInfoVO.class)).list();

     return list;

        } catch (RuntimeException re) {

            throw re;

        }

    }

3.使用criteria

Hibernate中共提供了三种检索方式:HQL(Hibernate Query Language)、QBC(Query By Criteria)、QBE(Query By Example)。而今天的这个查询方法属于QBC,

 
List list=getHibernateSession().createCriteria(MeterUser.class).add(Restrictions.eq("name", "11")).addOrder(Order.desc("userid")).list();

   

Restrictions的用法:

QBC常用限定方法

Restrictions.eq --> equal,等于.

Restrictions.allEq --> 参数为Map对象,使用key/value进行多个等于的比对,相当于多个Restrictions.eq的效果

Restrictions.gt --> great-than > 大于

Restrictions.ge --> great-equal >= 大于等于

Restrictions.lt --> less-than, < 小于

Restrictions.le --> less-equal <= 小于等于

Restrictions.between --> 对应SQL的between子句

Restrictions.like --> 对应SQL的LIKE子句

Restrictions.in --> 对应SQL的in子句

Restrictions.and --> and 关系

Restrictions.or --> or 关系

Restrictions.isNull --> 判断属性是否为空,为空则返回true

Restrictions.isNotNull --> 与isNull相反

Restrictions.sqlRestriction --> SQL限定的查询

Order.asc --> 根据传入的字段进行升序排序

Order.desc --> 根据传入的字段进行降序排序

MatchMode.EXACT --> 字符串精确匹配.相当于"like 'value'"

MatchMode.ANYWHERE --> 字符串在中间匹配.相当于"like '%value%'"

MatchMode.START --> 字符串在最前面的位置.相当于"like 'value%'"

MatchMode.END --> 字符串在最后面的位置.相当于"like '%value'"

例子
查询年龄在20-30岁之间的所有学生对象
List list = session.createCriteria(Student.class)
      .add(Restrictions.between("age",new Integer(20),new Integer(30)).list();
查询学生姓名在AAA,BBB,CCC之间的学生对象
String[] names = {"AAA","BBB","CCC"};
List list = session.createCriteria(Student.class)
      .add(Restrictions.in("name",names)).list();
查询年龄为空的学生对象
List list = session.createCriteria(Student.class)
      .add(Restrictions.isNull("age")).list();
查询年龄等于20或者年龄为空的学生对象
List list = session.createCriteria(Student.class)
      .add(Restrictions.or(Restrictions.eq("age",new Integer(20)),
                 Restrictions.isNull("age")).list();

--------------------------------------------------------------------
使用QBC实现动态查询
public List findStudents(String name,int age){

Criteria criteria = session.createCriteria(Student.class);
if(name != null){
  criteria.add(Restrictions.like("name",name,MatchMode.ANYWHERE));
}
if(age != 0){
  criteria.add(Restrictions.eq("age",new Integer(age)));
}
criteria.addOrder(Order.asc("name"));//根据名字升序排列
return criteria.list();
}

-----------------------------------------------------------------------------------

今天用了写hibernate高级查询时用了Restrictions(当然Expression也是可以以的)这个类.感觉不错.
下面的代码写的不易读.其实核心就是一句
Restrictions.or(Restrictions.like(),Restrictions.or(Restrictions.like,........))
里面的or可以无限加的.还是比较好用

Session session = getHibernateTemplate().getSessionFactory()
                .openSession();
        Criteria criteria = session.createCriteria(Film.class);
        List<Film> list = criteria.add(
            Restrictions.or(Restrictions.like("description", key,MatchMode.ANYWHERE),
            Restrictions.or(Restrictions.like("name", key,MatchMode.ANYWHERE),
                Restrictions.or(    Restrictions.like("direct", key,MatchMode.ANYWHERE),
                Restrictions.or(Restrictions.like("mainplay",key,MatchMode.ANYWHERE),
                        Restrictions.like("filearea", key,MatchMode.ANYWHERE)))))).list();

        session.close();
        return list;

窗体底端

4.使用随机数据库的数据放入list内

public List<Question> getQuestions(int majorid,int num){

        String majorType=new MajorDAO().getMajorType(majorid);

        System.out.println("getQuestions==="+majorType);

        try {

            if ("安全".equals(majorType)) {

                log.debug("安全题库查找。。");

                String hql="from Question q where q.majorId= 13 or q.majorId= "+majorid+"and q.isPass='' order by rand()";

                Query query = getSession().createQuery(hql);

                query.setMaxResults(num);

                List<Question>list=query.list();

                return list;

            }else {

                log.debug("质量题库查找。。");

                String hql="from Question q where q.majorId= "+majorid+" and q.isPass='' order by rand() ";

                Query query = getSession().createQuery(hql);

                query.setMaxResults(num);

                List<Question>list=query.list();

                return list;

            }

        } catch (RuntimeException re) {

            log.error("查找失败", re);

            throw re;

        }

    }

posted @ 2015-09-13 14:31  coder程  阅读(582)  评论(0编辑  收藏  举报