Hibernate進行增刪查改

勿在浮沙築高臺LS發表於2016-12-18
package cn.itcast.oa.base;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class BaseDaoImpl<T> implements BaseDao<T>{
    @Resource
    private SessionFactory sessionFactory;
    private Class<T> clazz;
    /**
     * 獲取當前的session物件
     * @return
     */
    public BaseDaoImpl(){
        ParameterizedType pt=(ParameterizedType) this.getClass().getGenericSuperclass();
        this.clazz= (Class<T>) pt.getActualTypeArguments()[0];
        System.out.println(clazz);
    }
    protected Session getSession(){
        return sessionFactory.getCurrentSession();
    }
    public void delete(Long id) {
        // TODO Auto-generated method stub
        Object obj=getById(id);
        if(obj!=null){
            getSession().delete(obj);
        }
    }

    public List<T> findAll(T entity) {
        // TODO Auto-generated method stub
        return getSession().createQuery("FROM"+clazz.getSimpleName()).list();
    }

    @SuppressWarnings("unchecked")
    public T getById(Long id) {
        // TODO Auto-generated method stub
        return (T) getSession().get(clazz, id);
    }

    @SuppressWarnings("unchecked")
    public List<T> getByIds(Long[] ids) {
        // TODO Auto-generated method stub
        return getSession().createQuery("FROM User WHERE id IN (?)").setParameterList("ids", ids).list();
    }

    public void save(T entity) {
        getSession().save(entity);

    }

    public void update(T entity) {

        getSession().update(entity);
    }



}

相關文章