暑期项目经验(十二)--hibernate

                  Hibernate

1.写一个BaseDao,写好CURD,再写一个其他DAO,继承他。

public void save(Object obj) {
        getSession().save(obj);
    }
    
    public void update(Object obj) {
        getSession().update(obj);
    }
    
    public void delete(Object obj) {
        getSession().delete(obj);
    }

2.按主键ID查找对应实体 用getSession().get(Entity.class, id)

public Teacher findTeacherByTeacherId(int teacherId) {
        return (Teacher)getSession().get(Teacher.class, teacherId);
    }

3.几种查询

//查询返回多个结果
List<Entity> lists = query.list();

//查询返回单个结果
Entity entity = (Entity)query.uniqueResult();

4.使用count(*)取表中记录总数

String hql = "select count(*) from FeedbackInfo where sendTeacherId=?";
Query query = getSession().createQuery(hql);
query.setParameter(0,teacherId);
int row = 0;
//重点下面这句
row = ((Number)query.uniqueResult()).intValue();

5.查询单独几个属性,并在Action中使用.  查询一个实体中的几个属性,查询结果的返回的是List<Object>集合,可以创建相应实体,将值保存.

package com.pl.pojo;

public class SumInfo {
    private String teacherId;
    private double workloadSum;
    public String getTeacherId() {
        return teacherId;
    }
    public void setTeacherId(String teacherId) {
        this.teacherId = teacherId;
    }
    public double getWorkloadSum() {
        return workloadSum;
    }
    public void setWorkloadSum(double workloadSum) {
        this.workloadSum = workloadSum;
    }
    
}

/------------************-------------------/
public List<SumInfo> findWorkloadAccountSumByTime(int startSchoolYear, int endSchoolYear) {
        String hql = "select teacherWorkId,round(sum(workload), 1) as workloadsum from TempWorkloadAccount where (schoolYear = ? and schoolTerm=2) or (schoolYear = ? and schoolTerm=1) group by teacherWorkId";
        Query query = getSession().createQuery(hql);
        query.setParameter(0, startSchoolYear);
        query.setParameter(1, endSchoolYear);
        List objs = query.list();
        List<SumInfo> sumInfos = new ArrayList<SumInfo>();
        for(Object obj:objs){
       //利用几行,分离每个对象 Object[] arrObj
= (Object[])obj; SumInfo info = new SumInfo(); info.setTeacherId((String)arrObj[0]); info.setWorkloadSum((Double)arrObj[1]); sumInfos.add(info); } return sumInfos; }

 

posted @ 2014-09-26 16:21  星尘pxj  阅读(204)  评论(0编辑  收藏  举报