hql语句中要注意的几点

本文介绍使用Hibernate进行数据库操作的方法,包括条件查询、增删改等基本操作,并提供具体代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、在条件查询中,对属性的赋值应该为=:,千万不能写反了

@SuppressWarnings("unchecked")
    public List<TOrder> listUpMoney(int state,float money1){
        Session session = null;
        session = HibernateSessionFactory.getSession();
        List<TOrder> list = new ArrayList<TOrder>();
        try {
            String hql = "from TOrder as n where n.FState=:state and n.FMoney>=:money1";
            Query query = session.createQuery(hql);
            query.setParameter("state", state);
            query.setParameter("money1", money1);
            list = query.list();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

2、query.setParameter()方法中,第一个参数为字符串,第二个参数为参数值。
3、hql语句对对象的增加,删除,更新写在BaseDAO中。所有的DAO方法继承BaseDAO。

package com.dao;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.model.Pojo;
import com.sessionFactory.HibernateSessionFactory;

public class BaseDAO implements DAO {

    @Override
    public void add(Pojo pojo) {
        Session session = HibernateSessionFactory.getSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.save(pojo);
            tx.commit();
        } catch (Exception e) {
            if(tx!=null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
            HibernateSessionFactory.closeSession();
        }

    }

    @Override
    public void delete(Pojo pojo) {
        Session session = HibernateSessionFactory.getSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.delete(pojo);
            tx.commit();
        } catch (Exception e) {
            if(tx!=null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
            HibernateSessionFactory.closeSession();
        }
    }

    @Override
    public void update(Pojo pojo) {
        Session session = HibernateSessionFactory.getSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.update(pojo);
            tx.commit();
        } catch (Exception e) {
            if(tx!=null) {
                tx.rollback();
            }
            e.printStackTrace();
        } finally {
            HibernateSessionFactory.closeSession();
        }
    }
}

BaseDAO实现DAO的接口

package com.dao;

import com.model.Pojo;

public interface DAO {

    void add(Pojo pojo);

    void delete(Pojo pojo);

    void update(Pojo pojo);

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值