泛型DAO在JPA中的应用

import java.io.Serializable;

import java.util.ArrayList;

import java.util.List;

import javax.persistence.EntityManager;

import javax.persistence.PersistenceException;

import javax.persistence.Query;

import org.springframework.orm.jpa.JpaCallback;

import org.springframework.orm.jpa.support.JpaDaoSupport;

import com.easyjf.core.dao.CanotRemoveObjectException;

import com.easyjf.core.dao.GenericDAO;

public class GenericDAOImpl<T> extends JpaDaoSupport implements GenericDAO<T> {

    private Class<T> clazz;

    public GenericDAOImpl(Class<T> clazz) {

        this.clazz = clazz;

    }

    /*

     * public void setClazz(Class<T> clazz) { this.clazz =

     * clazz; } public Class<T> getClazz() { return clazz; }

     */

    public T get(Serializable id) {

        if (id == null)

            return null;

        return this.getJpaTemplate().find(clazz, id);

    }

 

    public List<T> find(final String queryStr, final Object[] params,

            final int begin, final int max) {

        // TODO Auto-generated method stub

        List<T> ret = (List<T>) this.getJpaTemplate().execute(

                new JpaCallback() {

 

                    public Object doInJpa(EntityManager em)

                            throws PersistenceException {

                        // TODO Auto-generated method stub

                        String clazzName = clazz.getName();

                        StringBuffer sb = new StringBuffer("select obj from ");

                        sb.append(clazzName).append(" obj").append(" where ")

                                .append(queryStr);

                        Query query = em.createQuery(sb.toString());

                        int parameterIndex = 1;

                        if (params != null && params.length > 0) {

                            for (Object obj : params) {

                                query.setParameter(parameterIndex++, obj);

                            }

                        }

                        if (begin >= 0 && max > 0) {

                            query.setFirstResult(begin);

                            query.setMaxResults(max);

                        }

                        if (begin >= 0 && max > 0) {

                            query.setFirstResult(begin);

                            query.setMaxResults(max);

                        }

                        return query.getResultList();

                    }

                });

        if (ret != null && ret.size() >= 0) {

            return ret;

        } else {

            return new ArrayList<T>();

        }

    }

 

    public List query(final String queryStr, final Object[] params,

            final int begin, final int max) {

        // TODO Auto-generated method stub

        List ret = (List) this.getJpaTemplate().execute(new JpaCallback() {

 

            public Object doInJpa(EntityManager em) throws PersistenceException {

                // TODO Auto-generated method stub

                Query query = em.createQuery(queryStr);

                int parameterIndex = 1;

                if (params != null && params.length > 0) {

                    for (Object obj : params) {

                        query.setParameter(parameterIndex++, obj);

                    }

                }

                if (begin >= 0 && max > 0) {

                    query.setFirstResult(begin);

                    query.setMaxResults(max);

                }

            /*  if (begin >= 0 && max > 0) {

                    query.setFirstResult(begin);

                    query.setMaxResults(max);

                }*/

                return query.getResultList();

            }

        });

        if (ret != null && ret.size() >= 0) {

            return ret;

        } else {

            return new ArrayList();

        }

    }

 

    public void remove(Serializable id) throws CanotRemoveObjectException {

        // TODO Auto-generated method stub

        if (id == null)

            throw new java.lang.IllegalArgumentException("id值不能为空!");

        T object = this.get(id);

        if (object != null) {

            try {

                this.getJpaTemplate().remove(object);

            } catch (Exception e) {

                throw new CanotRemoveObjectException();

            }

        }

    }

 

    public void save(T instance) {

        // TODO Auto-generated method stub

        // this.getJpaTemplate().getEntityManager().joinTransaction();

        this.getJpaTemplate().persist(instance);

    }

 

    public T getBy(final String propertyName, final Object value) {

        if (propertyName == null || "".equals(propertyName) || value == null)

            throw new IllegalArgumentException("调用参数不正确,属性名称及值均不能为空!");

        // TODO Auto-generated method stub

        List<T> ret = (List<T>) this.getJpaTemplate().execute(

                new JpaCallback() {

 

                    public Object doInJpa(EntityManager em)

                            throws PersistenceException {

                        // TODO Auto-generated method stub

                        String clazzName = clazz.getName();

                        StringBuffer sb = new StringBuffer("select obj from ");

                        sb.append(clazzName).append(" obj");

                        Query query = null;

                        if (propertyName != null && value != null) {

                            sb.append(" where obj.").append(propertyName)

                                    .append(" = :value");

                            query = em.createQuery(sb.toString()).setParameter(

                                    "value", value);

                        } else {

                            query = em.createQuery(sb.toString());

                        }

                        return query.getResultList();

                    }

                });

        if (ret != null && ret.size() == 1) {

            return ret.get(0);

        } else if (ret != null && ret.size() > 1) {

            throw new java.lang.IllegalStateException(

                    "worning  --more than one object find!!");

        } else {

            return null;

        }

    }

 

    public void update(T instance) {

        // TODO Auto-generated method stub

        this.getJpaTemplate().merge(instance);

    }

 

    public void setClazzType(Class clazz) {

        this.clazz = clazz;

    }

 

    public Class getClassType() {

        return this.clazz;

    }

 

    public List executeNativeNamedQuery(final String nnq) {

        Object ret = this.getJpaTemplate().execute(new JpaCallback() {

 

            public Object doInJpa(EntityManager em) throws PersistenceException {

                Query query = em.createNativeQuery(nnq);

                return query.getResultList();

            }

        });

        return (List) ret;

    }

 

    public int executeNativeSQL(final String nnq) {

        Object ret = this.getJpaTemplate().execute(new JpaCallback() {

 

            public Object doInJpa(EntityManager em) throws PersistenceException {

                Query query = em.createNativeQuery(nnq);

                query.executeUpdate();

                return null;

            }

        });

        return (Integer) ret;

    }

    public int batchUpdate(final String jpql, final Object[] params) {

        Object ret = this.getJpaTemplate().execute(new JpaCallback() {

 

            public Object doInJpa(EntityManager em) throws PersistenceException {

                Query query = em.createQuery(jpql);

                int parameterIndex = 1;

                if (params != null && params.length > 0) {

                    for (Object obj : params) {

                        query.setParameter(parameterIndex++, obj);

                    }

                }

                return query.executeUpdate();

            }

        });

        return (Integer) ret;

    }

    public void flush() {

        this.getJpaTemplate().execute(new JpaCallback() {

 

            public Object doInJpa(EntityManager em) throws PersistenceException {

                em.getTransaction().commit();

                return null;

            }

        });

    }

}

最后再说的是,通过上面的配置你可以知道在EasyJWeb中的DAO是通过JPA实现的.

我想大家看了上面的代码以后也不会太明白.我建议下载EasyJWeb源代码看看.里面有很好MVC的实现.真的是很不错的..


下载地址: http://www.easyjf.com/download/easyjweb/easyjweb-1.0-m1-all.zip
SVN: http://svn.easyjf.com/repository/easyjf/easyjweb

你可能感兴趣的:(DAO,object,String,jpa,null,query)