hibernate 映射之后,DAO类里有能做查询的方法吗? 哪个是怎么用,我想在DAO里做个查询的方法,谁能帮写一下主要部分代码??最好能加上注释,能让我明白是怎么回事..

解决方案 »

  1.   

    hibernate查询的语句还是来源于Session,也可以实现Query接口。例子你可以看看,这是我们用过的。具体到某一个DAO继承这个类就行,用super调用这个类中的方法就可以; 
    /**
     * 使用HQL语句来得到实体对象的列表
     * 
     * @param hsql
     *            需要执行的HQL语句
     * 
     * @throws Exception
     * 
     * @return 符合条件的实体对象的列表
     */
    public List getObjects(String hsql) {
    Transaction tx = null;
    try {
    tx = getSession().beginTransaction();
    List result = getSession().createQuery(hsql).list();
    tx.commit();
    return result;
    } catch (Exception e) {
    if (tx != null)
    tx.rollback();
    e.printStackTrace();
    } finally {
    HibernateUtil.closeSession();
    }
    return null;
    } /**
     * 使用HQL语句来得到实体对象或者其他类型对象的实例
     * 
     * @param hsql
     *            需要执行的HQL语句
     * 
     * @throws Exception
     * 
     * @return 符合条件的实体对象的列表
     */
    public Object getObject(String hsql) {
    Transaction tx = null;
    try {
    tx = getSession().beginTransaction();
    Object result = getSession().createQuery(hsql).uniqueResult();
    tx.commit();
    return result;
    } catch (Exception e) {
    if (tx != null)
    tx.rollback();
    e.printStackTrace();
    } finally {
    HibernateUtil.closeSession();
    } return null;
    } /**
     * 通过ID值来得到某种类型的实体对象
     * 
     * @param cls
     *            实体对象的类型
     * 
     * @param id
     *            实体对象的标识符
     * 
     * @throws Exception
     * 
     * @return 标识符相匹配的实体对象
     */
    public Object getObject(Class cls, String id) {
    Transaction tx = null;
    try {
    tx = getSession().beginTransaction();
    Object result = getSession().get(cls, Long.parseLong(id));
    tx.commit();
    return result;
    } catch (Exception e) {
    if (tx != null)
    tx.rollback();
    e.printStackTrace();
    } finally {
    HibernateUtil.closeSession();
    } return null;
    }
      

  2.   

    DAO层就是写查询什么的嘛,当然你也可以写在映射文件里
      

  3.   

    这句转型 不写可以吗? Long.parseLong(id)?
    像我这样:
    public  Object getObject( Class  cls , String id )
    {
    //Integer.parseInt(id)
    Object  result = getSession().get(cls, id);

    return result;
    }
    /**
    *
    * Session.get( Class  cls, Seriablizable  id )
    */