hibernate实现增删改查的各种方法

1》接口(主要是增删改查的接口)BaseDao.java

/**
 *
 * @author fly.zhou
 */
public interface IBaseDao {

    //增加对应实体的一条记录
    public boolean save(Object o);

    //更新对应实体的一条记录
    public boolean update(Object o);

    //增加或者更新对应实体的一条记录
    public boolean saveOrUpdate(Object o);

    //保存一系列对象集合
    public boolean saveOrUpdateAll(Collection l);

    //删除对应实体的一条记录
    public boolean delete(Object o);

    //根据id删除对应实体的一条记录
    public boolean delete(Class c, Serializable id);

    //执行hql语句删除一条记录
    public Integer delete(String hql, Object... values);

    //删除一系列数据
    public boolean deleteAll(Collection l);

    //执行hql语句查找
    public List find(String hql);

    //分页查询,多参数条件
    public List find(String hql, DataGridReq dgr, List values);

    //分页查询,多参数条件
    public List find(String hql, DataGridReq dgr, Object... values);

    //不带分页查询,多参数条件
    public List find(String hql, Object... values);

    //不带分页查询,多参数条件
    public boolean update(String hql, Object... values);

    //根据主键ID查询对应实体的一条记录
    public Object get(Class clazz, Serializable id);

    //获取某实体对象
    public Object load(Class c, Serializable id);

    //获取总记录数
    public Long total(String hql, List values);

    //获取总记录数
    public Long total(String hql, Object... values);

    //更新对应实体的某一条记录
    public boolean updateOneByProperty(Class clazz, Serializable id, String pName, Object pValue);

    //更新对应实体的某几条记录
    public boolean updateOneByPropertys(Class clazz, Serializable id, List<String> pName, List<Object> pValue);

    //更新对应实体的某几条记录(封装成map)
    public boolean updateOneByPropertys(Class clazz, Serializable id, Map<String, Object> map);

    //根据属性名以及对应的属性值查找一条记录
    public Object getSingleByProperty(Class clazz, String pName, Object pValue);

    //判断是否有对应的属性名和属性值存在,存在返回true
    public boolean ifHasOneByProperty(Class clazz, String pName, Object pValue);

    //根据一系列属性以及对应的属性值查询一条记录
    public Object getSingleByPropertys(Class clazz, List<String> pName, List<Object> pValue);

    //判断是否有一系列对应的属性名和属性值存在,存在返回true
    public boolean ifHasOneByPropertys(Class clazz, List<String> pName, List<Object> pValue);

    //根据一系列属性以及对应的属性值(封装成Map)查询一条记录
    public Object getSingleByPropertys(Class clazz, Map<String, Object> map);

    //判断是否有一系列对应的属性名和属性值(封装成Map)存在,存在返回true
    public boolean ifHasOneByPropertys(Class clazz, Map<String, Object> map);

    //通过某一对应的属性名和属性值,查询某一个属性的值
    public Object getValueByPropertys(Class clazz, Map<String, Object> map, String selectName);

    //通过一系列对应的属性名和属性值,查询某一个属性的值
    public Object getValueByProperty(Class clazz, String pName, Object pValue, String selectName);

    //通过一系列对应的属性名和属性值,查询某一个属性的值
    public Object getValueByPropertys(Class clazz, List<String> pNames, List<Object> pValues, String selectName);

    //查询对应实体的所有记录
    public List<Object> getObjects(Class clazz);

    //查询符合属性名以及对应的属性值的一系列记录
    public List<Object> getObjectsByProperty(Class clazz, String pName, Object pValue);

    //根据任意属性查询名以及对应的属性值的一系列记录
    public List<Object> getObjectsByAnyProperty(Class clazz, List<String> pName, List<Object> pValue);

    //查询符合一系列属性名以及对应的属性值的一系列记录
    public List<Object> getObjectsByPropertys(Class clazz, List<String> pName, List<Object> pValue);

    //根据某属性对应的属性值在某一范围内的一系列记录
    public List<Object> getObjectsByProperty(Class clazz, String pName, String operator, Object pValue);

    //根据某属性对应的属性值在某一范围内的一系列记录
    public List<Object> getObjectsByPropertys(Class clazz, List<String> pName, List<String> operator, List<Object> pValue);
}

2》接口的实现 BaseDaoImpl.java

public class BaseDaoImpl implements IBaseDao {

    private static final Logger logger = Logger.getLogger(BaseDaoImpl.class);
    private HibernateTemplate hibernateTemplate;

    public HibernateTemplate getHibernateTemplate() {
        hibernateTemplate.setCacheQueries(true);// 开启二级查询缓存
        return hibernateTemplate;
    }

    @Autowired
    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }

    @Override
    public boolean delete(Object o) {
//        logger.info("删除");
        try {
            this.getHibernateTemplate().delete(o);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean delete(Class c, Serializable id) {
//        logger.info("删除");
        try {
            this.getHibernateTemplate().delete(get(c, id));
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public Integer delete(final String hql, final Object... values) {
        return this.getHibernateTemplate().execute(new HibernateCallback<Integer>() {

            @Override
            public Integer doInHibernate(Session session) throws HibernateException, SQLException {
                Query q = session.createQuery(hql);
                if (values != null && values.length > 0) {
                    for (int i = 0; i < values.length; i++) {
                        q.setParameter(i, values[i]);
                    }
                }
                return q.executeUpdate();
            }
        });
    }

    @Override
    public boolean deleteAll(Collection l) {
//        logger.info("删除");
        try {
            this.getHibernateTemplate().deleteAll(l);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean update(Object o) {
//        logger.info("更新");
        try {
            this.getHibernateTemplate().update(o);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean save(Object o) {
//        logger.info("保存");
        try {
            this.getHibernateTemplate().save(o);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean saveOrUpdate(Object o) {
        try {
            this.getHibernateTemplate().saveOrUpdate(o);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean saveOrUpdateAll(Collection l) {
//        logger.info("编辑");
        try {
            this.getHibernateTemplate().saveOrUpdateAll(l);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public List find(String hql) {
//        logger.info("查询");
        return this.getHibernateTemplate().find(hql);
    }

    @Override
    public List find(final String hql, final DataGridReq dgr, final List values) {
        return this.getHibernateTemplate().execute(new HibernateCallback<List>() {

            @Override
            public List doInHibernate(Session session) throws HibernateException, SQLException {
                Query q = session.createQuery(hql);
                if (values != null && values.size() > 0) {
                    for (int i = 0; i < values.size(); i++) {
                        q.setParameter(i, values.get(i));
                    }
                }
                if (dgr == null) {
                    return q.list();
                }
                return q.setFirstResult(dgr.getStart()).setMaxResults(dgr.getLimit() * dgr.getPage()).list();
            }
        });
    }

    @Override
    public List find(final String hql, final DataGridReq dgr, final Object... values) {
        return this.getHibernateTemplate().execute(new HibernateCallback<List>() {

            @Override
            public List doInHibernate(Session session) throws HibernateException, SQLException {
                Query q = session.createQuery(hql);
                if (values != null && values.length > 0) {
                    for (int i = 0; i < values.length; i++) {
                        q.setParameter(i, values[i]);
                    }
                }
                if (dgr == null) {
                    return q.list();
                }
                return q.setFirstResult(dgr.getStart()).setMaxResults(dgr.getLimit() * dgr.getPage()).list();
            }
        });
    }

    @Override
    public List find(String hql, Object... values) {
        return this.getHibernateTemplate().find(hql, values);
    }

    @Override
    public boolean update(final String hql, final Object... values) {
        try {
            this.getHibernateTemplate().bulkUpdate(hql, values);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public Object get(Class c, Serializable id) {
        return this.getHibernateTemplate().get(c, id);
    }

    @Override
    public Object load(Class c, Serializable id) {
        return this.getHibernateTemplate().load(c, id);
    }

    @Override
    public Long total(final String hql, final List values) {
        return this.getHibernateTemplate().execute(new HibernateCallback<Long>() {

            @Override
            public Long doInHibernate(Session session) throws HibernateException, SQLException {
                Query q = session.createQuery(hql);
                if (values != null && values.size() > 0) {
                    for (int i = 0; i < values.size(); i++) {
                        q.setParameter(i, values.get(i));
                    }
                }
                return (Long) q.uniqueResult();
            }
        });
    }

    @Override
    public Long total(final String hql, final Object... values) {
        return this.getHibernateTemplate().execute(new HibernateCallback<Long>() {

            @Override
            public Long doInHibernate(Session session) throws HibernateException, SQLException {
                Query q = session.createQuery(hql);
                if (values != null && values.length > 0) {
                    for (int i = 0; i < values.length; i++) {
                        q.setParameter(i, values[i]);
                    }
                }
                return (Long) q.uniqueResult();
            }
        });
    }

    @Override
    public boolean updateOneByProperty(Class clazz, Serializable id, String pName, Object pValue) {
        String hql = "update " + clazz.getName() + " entity set entity." + pName + " = ‘" + pValue + "‘ where entity.id = " + id;
        getHibernateTemplate().bulkUpdate(hql);
        return true;
    }

    @Override
    public boolean updateOneByPropertys(Class clazz, Serializable id, List<String> pName, List<Object> pValue) {
        String hql = "update " + clazz.getName() + " entity set entity.";
        int maxIndex = pName.size() - 1;
        for (int i = 0; i < maxIndex; i++) {
            hql += pName.get(i) + " = ‘" + pValue.get(i) + "‘, entity.";
        }
        hql += pName.get(maxIndex) + " = ‘" + pValue.get(maxIndex) + "‘where entity.id = " + id;
        System.out.println(hql);
        getHibernateTemplate().bulkUpdate(hql);
        return true;
    }

    @Override
    public boolean updateOneByPropertys(Class clazz, Serializable id, Map<String, Object> map) {
        String hql = "update " + clazz.getName() + " entity set entity.";
        Set set = map.entrySet();
        if (set != null) {
            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                Entry entry = (Entry) iterator.next();
                Object key = entry.getKey();
                Object value = entry.getValue();
                hql += key + " = ‘" + value + "‘ and entity.";
            }
        }
        hql = hql.substring(0, hql.length() - 12);
        hql += "‘where entity.id = " + id;
        System.out.println(hql);
        getHibernateTemplate().bulkUpdate(hql);
        return true;
    }

    /**
     * 根据属性查询
     *
     * @param clazz
     * @param pName
     * @param pValue
     * @return
     */
    @Override
    public Object getSingleByProperty(Class clazz, String pName, Object pValue) {

        String hql = "from " + clazz.getName() + " entity where entity." + pName + " = ‘" + pValue + "‘";
        List<Object> os = getHibernateTemplate().find(hql);
        if (os != null && !os.isEmpty()) {
            return os.get(0);
        } else {
            return null;
        }
    }

    /**
     * 根据属性查询
     *
     * @param clazz
     * @param pName
     * @param pValue
     * @return
     */
    @Override
    public boolean ifHasOneByProperty(Class clazz, String pName, Object pValue) {
        String hql = "from " + clazz.getName() + " entity where entity." + pName + " = ‘" + pValue + "‘";
        List<Object> os = getHibernateTemplate().find(hql);
        if (os != null && !os.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据属性查询
     *
     * @param clazz
     * @param pName
     * @param pValue
     * @return
     */
    @Override
    public List<Object> getObjectsByAnyProperty(Class clazz, List<String> pName, List<Object> pValue) {
        String hql = "from " + clazz.getName() + " entity where entity.";
        int maxIndex = pName.size() - 1;
        for (int i = 0; i < maxIndex; i++) {
            hql += pName.get(i) + " = ‘" + pValue.get(i) + "‘ or entity.";
        }
        hql += pName.get(maxIndex) + " = ‘" + pValue.get(maxIndex) + "‘";
        System.out.println(hql);
        List<Object> os = getHibernateTemplate().find(hql);
        if (os != null && !os.isEmpty()) {
            return os;
        } else {
            return null;
        }
    }

    @Override
    public boolean ifHasOneByPropertys(Class clazz, List<String> pName, List<Object> pValue) {
        String hql = "from " + clazz.getName() + " entity where entity.";
        int maxIndex = pName.size() - 1;
        for (int i = 0; i < maxIndex; i++) {
            hql += pName.get(i) + " = ‘" + pValue.get(i) + "‘ and entity.";
        }
        hql += pName.get(maxIndex) + " = ‘" + pValue.get(maxIndex) + "‘";
        System.out.println(hql);
        List<Object> os = getHibernateTemplate().find(hql);
        if (os != null && !os.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Object getSingleByPropertys(Class clazz, List<String> pName, List<Object> pValue) {

        String hql = "from " + clazz.getName() + " entity where entity.";
        int maxIndex = pName.size() - 1;
        for (int i = 0; i < maxIndex; i++) {
            hql += pName.get(i) + " = ‘" + pValue.get(i) + "‘ and entity.";
        }
        hql += pName.get(maxIndex) + " = ‘" + pValue.get(maxIndex) + "‘";
        System.out.println(hql);
        List<Object> os = getHibernateTemplate().find(hql);
        if (os != null && !os.isEmpty()) {
            return os.get(0);
        } else {
            return null;
        }
    }

    @Override
    public Object getSingleByPropertys(Class clazz, Map<String, Object> map) {
        String hql = "from " + clazz.getName() + " entity where entity.";
        Set set = map.entrySet();
        if (set != null) {
            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                Entry entry = (Entry) iterator.next();
                Object key = entry.getKey();
                Object value = entry.getValue();
                hql += key + " = ‘" + value + "‘ and entity.";
            }
        }
        hql = hql.substring(0, hql.length() - 12);
        System.out.println("hql = " + hql);
        List<Object> os = getHibernateTemplate().find(hql);
        if (os != null && !os.isEmpty()) {
            return os.get(0);
        } else {
            return null;
        }
    }

    @Override
    public boolean ifHasOneByPropertys(Class clazz, Map<String, Object> map) {

        String hql = "from " + clazz.getName() + " entity where entity.";
        Set set = map.entrySet();
        if (set != null) {
            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                Entry entry = (Entry) iterator.next();
                Object key = entry.getKey();
                Object value = entry.getValue();
                hql += key + " = ‘" + value + "‘ and entity.";
            }
        }
        hql = hql.substring(0, hql.length() - 12);
        List<Object> os = getHibernateTemplate().find(hql);
        if (os != null && !os.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 查询所有
     */
    @Override
    public List<Object> getObjects(Class clazz) {
        String hql = "from " + clazz.getName();
        List list = getHibernateTemplate().find(hql);
        return list;
    }

    /**
     * 根据属性查询 全部
     *
     * @param clazz
     * @param pName
     * @param pValue
     * @return
     */
    @Override
    public List<Object> getObjectsByProperty(Class clazz, String pName, Object pValue) {
        String hql = "from " + clazz.getName() + " entity where entity." + pName + " = ‘" + pValue + "‘";
        return getHibernateTemplate().find(hql);
    }

    @Override
    public List<Object> getObjectsByPropertys(Class clazz, List<String> pName, List<Object> pValue) {
        String hql = "from " + clazz.getName() + " entity where entity.";
        int maxIndex = pName.size() - 1;
        for (int i = 0; i < maxIndex; i++) {
            hql += pName.get(i) + " = ‘" + pValue.get(i) + "‘ and ";
        }
        hql += pName.get(maxIndex) + " = ‘" + pValue.get(maxIndex) + "‘";
        return getHibernateTemplate().find(hql);
    }

    /**
     * 根据属性查询 全部
     *
     * @param clazz
     * @param pName
     * @param pValue
     * @return
     */
    @Override
    public List<Object> getObjectsByProperty(Class clazz, String pName, String operator, Object pValue) {
        String hql = "from " + clazz.getName() + " entity where entity." + pName + " " + operator + pValue;
        return getHibernateTemplate().find(hql);
    }

    @Override
    public List<Object> getObjectsByPropertys(Class clazz, List<String> pName, List<String> operator, List<Object> pValue) {
        String hql = "from " + clazz.getName() + " entity where entity.";
        int maxIndex = pName.size() - 1;
        for (int i = 0; i < maxIndex; i++) {
            hql += pName.get(i) + " " + operator.get(i) + " ‘" + pValue.get(i) + "‘ and ";
        }
        hql += pName.get(maxIndex) + " " + operator.get(maxIndex) + " ‘" + pValue.get(maxIndex) + "‘";
        System.out.println("hql = " + hql);
        return getHibernateTemplate().find(hql);
    }

    @Override
    public Object getValueByPropertys(Class clazz, Map<String, Object> map, String selectName) {
        String hql = "select entity." + selectName + "from " + clazz.getName() + " entity where entity.";
        Set set = map.entrySet();
        if (set != null) {
            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                Entry entry = (Entry) iterator.next();
                Object key = entry.getKey();
                Object value = entry.getValue();
                hql += key + " = ‘" + value + "‘ and entity.";
            }
        }
        hql = hql.substring(0, hql.length() - 12);
        System.out.println("hql = " + hql);
        return getHibernateTemplate().find(hql);
    }

    @Override
    public Object getValueByProperty(Class clazz, String pName, Object pValue, String selectName) {
        String hql = "select entity." + selectName + " from " + clazz.getName() + " entity where entity." + pName + " = ‘" + pValue + "‘";
        System.out.println("hql = " + hql);
        return getHibernateTemplate().find(hql);
    }

    @Override
    public Object getValueByPropertys(Class clazz, List<String> pNames, List<Object> pValues, String selectName) {
        String hql = "select entity." + selectName + "from " + clazz.getName() + " entity where entity.";
        int maxIndex = pNames.size() - 1;
        for (int i = 0; i < maxIndex; i++) {
            hql += pNames.get(i) + " = ‘" + pValues.get(i) + "‘ and ";
        }
        hql += pNames.get(maxIndex) + " = ‘" + pValues.get(maxIndex) + "‘";
        System.out.println("hql = " + hql);
        return getHibernateTemplate().find(hql);
    }
}

3》值得注意的地方Map如何获取key

        Set set = map.entrySet();
        if (set != null) {
            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                Entry entry = (Entry) iterator.next();
                Object key = entry.getKey();
                Object value = entry.getValue();
                hql += key + " = ‘" + value + "‘ and entity.";
            }
        }

4》这样写的话 会对项目省去大量的重复代码,在对具体的实体操作时,我们只需要把对应实体的实现继承BaseDaoImpl。

public class XXXDaoImpl extends BaseDaoImpl implements IXXXDao{}

当然我们也可以在XXXDaoImpl里面添加此实体特殊的实现方法。

5》对于hibernate,有时候为了提高查询和执行效率,我们只需要获取部分数据,而不需要拿出关联数据或者是整行的所有数据,这时候我们可以构造函数来解决这个问题。

时间: 2024-10-28 20:40:58

hibernate实现增删改查的各种方法的相关文章

hibernate+springMVC增删改查

原文:hibernate+springMVC增删改查 源代码下载地址:http://www.zuidaima.com/share/1550463770610688.htm 1,开发环境:MyEclipse 2013 字符集"UTF-8" 2,Web服务器:Tomcat 6-7都可以 3,SQL Server 2008 需要自己添加数据库db_new,也可以自己改配置文件. 4,使用技术:hibernate,springmvc     官方验证: 程序是没问题的,如楼主描述的功能,他没有

hibernate 入门增删改查demo

原文:hibernate 入门增删改查demo 源代码下载地址:http://www.zuidaima.com/share/1550463648238592.htm

用DBContext (EF) 实现通用增删改查的REST方法

我们用ADO.NET Entity Data Model来生成实体类后,一般都会对这些类进行基本的增删改查操作,如果每个类都要写这些基本的方法,实在太乏味了.下面就是通过step by step的方式介绍如何用DBContext来实现通用增删改查的REST方法,以及实现过程中容易出现的问题. 1. 打开vs2012,新建一个class library的项目 2. 新加一个ADO.NET Entity Data Model项到这个项目 3. 打开App.Config, 修改res://* 为res

Hibernate 批量增删改查操作

上文介绍Hibernate基本的增删改查,本例将介绍更实用的批量增删改查的操作的实现.本文中增删改查的操作,仅供参考.如果读者需要应用到实际的应用场景需要的话,需要在此基础上扩展与丰富. [转载使用,请注明出处:http://blog.csdn.net/mahoking] 在学习本例时,需要扩展一下Hibernate中Session的知识.Hibernate中的Session是一级缓存,可以理解为进程级的缓存.在进程运行期间一直存在.Session可以理解为一个可以操作数据库的对象 具体如何操作

Hibernate全套增删改查+分页

1.创建一个web工程 2.导入jar包 3.创建Student表 4.创建实体类 package com.entity; public class Student { private Integer sid; private String sname; private String password; private String sex; private Integer cid; public Student() { } public Student(Integer sid, String

EasyUI + Spring MVC + hibernate实现增删改查导入导出

(这是一个故事……) 前言 作为一个JAVA开发工程师,我觉得最基本是需要懂前端.后台以及数据库. 练习的内容很基础,包括:基本增删改查.模糊查询.分页查询.树菜单.上传下载.tab页 主管发我一个已经搭建好的框架平台,在平台上进行编码,不限制技术. 虽然说不限制技术,但还是得根据已经搭建的框架平台进行编码. 所以首先第一步,分析框架平台结构组成. 入手:看目录.看配置.看jar包.看js库.看数据库... 不难发现项目是基于:Spring + Hibernate + Spring MVC +

Hibernate 基本增删改查操作

本文将要介绍Hibernate基本的增删改查的操作的实现,首先我们创建一个对象实例.一般情况下会创建User,本例也不例外需要创建这样的对象. [转载使用,请注明出处:http://blog.csdn.net/mahoking] User对象 public class User { private Integer id; private String userName; private String password; /*以下省略getter与setter*/ } 配置User.hbm.xml

hibernate之增删改查demo

1 package dao; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 import org.hibernate.Query; 7 import org.hibernate.SQLQuery; 8 import org.hibernate.Transaction; 9 10 import com.sun.org.apache.bcel.internal.generic.GETSTATIC; 11 12 import

Hibernate的增删改查

一.搭建Hibernate开发环境,这里就不说了,直接说环境搭好后的事情. 二.项目的目录结构 三.base_image.hbm.xml配置文件内容 1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://w