1. 程式人生 > >hibernate實現增刪改查的各種方法

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,有時候為了提高查詢和執行效率,我們只需要獲取部分資料,而不需要拿出關聯資料或者是整行的所有資料,這時候我們可以建構函式來解決這個問題。