首页 > 代码库 > 泛型持久层实现(深度减轻代码量)
泛型持久层实现(深度减轻代码量)
import java.math.BigDecimal; import java.util.List; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; @Repository public class BaseDao { @Autowired private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @SuppressWarnings("unchecked") public <T> List<T> queryBaseObject(String sql, Class<T> entity) { return this.getSessionFactory().getCurrentSession().createSQLQuery(sql) .addEntity(entity).list(); } public <T> void addBaseObject(T entity) { this.getSessionFactory().getCurrentSession().save(entity); } public <T> void updateBaseObject(T entity) { this.getSessionFactory().getCurrentSession().saveOrUpdate(entity); } public <T> void deleteBaseObject(T entity) { this.getSessionFactory().getCurrentSession().delete(entity); } public void insertOrUpdateObject(String sql) { this.getSessionFactory().getCurrentSession().createSQLQuery(sql) .executeUpdate(); } @SuppressWarnings("unchecked") public <T> T querySingleObject(int id, Class<T> entity) { return (T) this.getSessionFactory().getCurrentSession() .load(entity, id); } @SuppressWarnings("unchecked") public <T> T querySingleobject(String sql, Class<T> entity) { return (T) this.getSessionFactory().getCurrentSession() .createSQLQuery(sql).addEntity(entity).uniqueResult(); } @SuppressWarnings("rawtypes") public int queryListCount(String sql) { List gg = this.sessionFactory.getCurrentSession().createSQLQuery(sql) .list(); int result = ((BigDecimal) gg.get(0)).intValue(); return result; } public void deleteBaseObject(String sql) { this.getSessionFactory().getCurrentSession().createSQLQuery(sql) .executeUpdate(); } }
泛型持久层实现(深度减轻代码量)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。