码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2015-03-09 15:38:48      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:

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,有时候为了提高查询和执行效率,我们只需要获取部分数据,而不需要拿出关联数据或者是整行的所有数据,这时候我们可以构造函数来解决这个问题。

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

标签:

原文地址:http://www.cnblogs.com/doudou618/p/4323519.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!