一个Hibernate Dao的模板

Model:
package com.pandy.model;


import com.pandy.common.BaseObject;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;

@Entity
@Table(name = "rh_sys_user")
@NamedQueries(
        value = {
                @NamedQuery(name = "getAllByNamedQuery1", query = "from RhSysUser"),
                @NamedQuery(name = "getAllByNamedQuery2", query = "from RhSysUser")
        }

)
public class RhSysUser extends BaseObject implements Serializable {
    private static final long serialVersionUID = 9812345L;
    private Long userId;
    private String code;
    private String loginName;
    private String userName;
    //......

    @Id
    @Column(name = "user_id", unique = true, nullable = false)
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getUserId() {
        return this.userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    @Column(name = "code", length = 50)
    public String getCode() {
        return this.code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    //......
}





公共接口:
package com.pandy.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

public interface BaseDAO <T, PK extends Serializable>{
    public void setSessionFactoryOverride(SessionFactory sessionFactory);
    public Session getSession();

    T get(PK id);
    boolean exists(PK id);
    T save(T object);
    void remove(T object);
    void remove(PK id);
    void delete(T object);
    public int delete(Map<String,Object> map);


    List<T> getAll();
    public List<T> getAll(List<Order> orderList);
    List<T> searchByField(String field,Object value, String orderField) throws RuntimeException;
    List<T> searchByFields(Map fields) throws RuntimeException;
    List<T> searchByFields(Map fields,Map<String,String> order) throws RuntimeException;
    T searchFirstByFields(Map fields) throws RuntimeException;
    T getFirstByCode(String code);
    List<T> findByNamedQuery(String queryName, Map<String, Object> queryParams);
    T findFirstByNamedQuery(String queryName, Map<String, Object> queryParams);
}



公共实现:
package com.pandy.dao.impl;

import com.pandy.dao.BaseDAO;
import org.hibernate.*;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;

import javax.annotation.Resource;
import javax.persistence.EntityManagerFactory;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BaseDAOImpl<T, PK extends Serializable> extends HibernateDaoSupport implements BaseDAO<T, PK> {
    protected EntityManagerFactory entityManagerFactory;
    private Class<T> persistentClass;
    @Resource
    private SessionFactory sessionFactory;

    public BaseDAOImpl(final Class<T> persistentClass) {
        this.persistentClass = persistentClass;
    }

    public BaseDAOImpl(final Class<T> persistentClass, SessionFactory sessionFactory) {
        this.persistentClass = persistentClass;
        this.sessionFactory = sessionFactory;
    }

    @Autowired
    public void setSessionFactoryOverride(SessionFactory sessionFactory) {
        super.setSessionFactory(sessionFactory);
        this.sessionFactory=sessionFactory;
    }
    public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
        this.entityManagerFactory = entityManagerFactory;
    }

    public Session getSession() throws HibernateException {
        Session sess = getSessionFactory().getCurrentSession();
        if (sess == null) {
            sess = getSessionFactory().openSession();
        }
        return sess;
    }

    @SuppressWarnings("unchecked")
    public List<T> getAll() {
        Session sess = getSession();
        return sess.createCriteria(persistentClass).list();
    }

    public List<T> getAll(List<Order> orderList) {
        Session sess = getSession();
        Criteria criteria = sess.createCriteria(persistentClass);
        criteria.setCacheable(true);
        if (orderList != null) {
            for (Order order : orderList) {
                criteria.addOrder(order);
            }
        }
        return criteria.list();
    }

    public List<T> searchByField(String field, Object value, String orderField) throws RuntimeException {
        Session sess = getSession();
        Criteria criteria = sess.createCriteria(persistentClass);
        criteria.setCacheable(true);

        if (field != null && field.trim().length() > 0) {
            criteria.add(Restrictions.eq(field, value));
        }

        if (orderField != null && orderField.trim().length() > 0) {
            criteria.addOrder(Order.asc(orderField));
        }

        return criteria.list();
    }


    public List<T> searchByFields(Map fields) throws RuntimeException {
        Session sess = getSession();
        Criteria criteria = sess.createCriteria(persistentClass);
        criteria.setCacheable(true);

        for (Object field : fields.keySet()) {
            String fieldName = field != null ? field.toString() : "";

            if (!fieldName.equals("")) {
                Object fieldValue = fields.get(field);
                criteria.add(Restrictions.eq(fieldName, fieldValue));

                if (fieldName.equals("orderField")) {
                    criteria.addOrder(Order.asc(fieldValue.toString()));
                }

            }


        }

        return criteria.list();

    }

    @Override
    public T getFirstByCode(String code) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("code", code);
        return searchFirstByFields(param);
    }

    @Override
    public T searchFirstByFields(Map fields) throws RuntimeException {
        List<T> list = searchByFields(fields);
        if (list != null && list.size() > 0) return list.get(0);
        return null;
    }

    @SuppressWarnings("unchecked")
    public T get(PK id) {
        Session sess = getSession();
        IdentifierLoadAccess byId = sess.byId(persistentClass);
        T entity = (T) byId.load(id);

        if (entity == null) {
            throw new ObjectRetrievalFailureException(this.persistentClass, id);
        }

        return entity;
    }

    @SuppressWarnings("unchecked")
    public boolean exists(PK id) {
        Session sess = getSession();
        IdentifierLoadAccess byId = sess.byId(persistentClass);
        T entity = (T) byId.load(id);
        return entity != null;
    }

    @SuppressWarnings("unchecked")
    public T save(T object) {
        Session sess = getSession();
        return (T) sess.merge(object);
    }

    public void remove(T object) {
        Session sess = getSession();
        sess.delete(object);
    }

    public void remove(PK id) {
        Session sess = getSession();
        IdentifierLoadAccess byId = sess.byId(persistentClass);
        T entity = (T) byId.load(id);
        sess.delete(entity);
    }

    @SuppressWarnings("unchecked")
    public List<T> findByNamedQuery(String queryName, Map<String, Object> queryParams) {
        Session sess = getSession();
        Query namedQuery = sess.getNamedQuery(queryName);
        namedQuery.setCacheable(true);
        for (String s : queryParams.keySet()) {
            namedQuery.setParameter(s, queryParams.get(s));
        }

        return namedQuery.list();
    }

    @SuppressWarnings("unchecked")
    public T findFirstByNamedQuery(String queryName, Map<String, Object> queryParams) {
        List<T> list = findByNamedQuery(queryName, queryParams);
        if (list != null && list.size() > 0)
            return list.get(0);
        return null;
    }

    @Override
    public void delete(T object) {
        getSession().delete(object);
    }

    @Override
    public int delete(Map<String, Object> map) {
        // TODO Auto-generated method stub
        if (map == null || map.size() == 0) {
            throw new RuntimeException("参数map不能为空或者size=0");
        }

        String className = this.persistentClass.getName();
        String name = className.substring(className.lastIndexOf(".") + 1);
        //System.out.println(name);
        String hql = "delete from " + name + " a where 1=1 ";

        for (String key : map.keySet()) {
            hql += " and a." + key + "=:" + key.replace(".", "_");
        }
        Query query = getSession().createQuery(hql);
        for (String key : map.keySet()) {
            //TODO: add by Pandy: 这里可能会有问题,比如int的类型经过instanceof会是Integer么?
            Object value = map.get(key);
            key = key.replace(".", "_");
            if (value instanceof Integer) {
                query.setInteger(key, (Integer) value);
            } else if (value instanceof Double) {
                query.setDouble(key, (Double) value);
            } else if (value instanceof Boolean) {
                query.setBoolean(key, (Boolean) value);
            } else if (value instanceof Date) {
                query.setDate(key, (Date) value);
            } else if (value instanceof Long) {
                query.setLong(key, (Long) value);
            } else {
                query.setString(key, value.toString());
            }


        }

        return query.executeUpdate();

    }


    @SuppressWarnings({"rawtypes", "unchecked"})
    @Override
    public List<T> searchByFields(Map fields, Map<String, String> orders) throws RuntimeException {
        Session sess = getSession();
        Criteria criteria = sess.createCriteria(persistentClass);
        criteria.setCacheable(true);

        for (Object field : fields.keySet()) {
            String fieldName = field != null ? field.toString() : "";

            if (!fieldName.equals("")) {
                Object fieldValue = fields.get(field);
                criteria.add(Restrictions.eq(fieldName, fieldValue));
            }
        }

        for (String field : orders.keySet()) {
            String order = orders.get(field);
            if ("desc".equalsIgnoreCase(order)) {
                criteria.addOrder(Order.desc(field));
            } else {
                criteria.addOrder(Order.asc(field));
            }

        }

        return criteria.list();
    }
}



使用接口定义:
package com.pandy.dao;

import com.pandy.model.RhSysUser;

public interface RhSysUserDao extends BaseDAO<RhSysUser, Integer> {
    public void test();
}



最终使用实现:

package com.pandy.dao.impl;

import com.pandy.dao.RhSysUserDao;
import com.pandy.model.RhSysUser;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
@Repository(value="rhSysUserDao")
public class RhSysUserDaoImpl extends BaseDAOImpl<RhSysUser, Integer> implements RhSysUserDao{

    public RhSysUserDaoImpl() {
        super(RhSysUser.class);
    }

    @Override
    public void test() {
        Session session = getSessionFactory().getCurrentSession();
        Query query = session.createQuery("from RhSysUser");
        List<RhSysUser> list = query.list();
        if(list!=null && list.size()>0){
            for(RhSysUser rhSysUser :list){
                System.out.println(rhSysUser.getUserName());
            }
        }
    }
}

你可能感兴趣的:(Hibernate)