Spring3.1+ JpaDaoSupport被deprecated后的研究

来源:互联网 发布:免费手机视频监控软件 编辑:程序博客网 时间:2024/05/17 07:25

这段时间准备把几个基础库类重写,之前发现了Spring升级到3.1之后以前写的DAO类出现deprecated的问题,当时没有仔细研究把Spring降到3.0.5了事。最近突然想到这个问题觉得还是要研究一下,于是找来资料看看,发现Spring在3.1之后决定完全支持JPA2标准,准备放弃之前的JpaDaoSupport和JpaTemplate等。也就是说,以后Spring不再使用JpaTemplate的方式去回调实现JPA的接口,而是完全采用注解和注入的方式去实现,这样就实现了Spring的完全解耦合。恩,是个不错的思路!

 

对比一下代码来发现不同之处

 

3.1之前我扩展的DAO类

Java代码  收藏代码
  1. public abstract class StrongDAOImpl<E, PK extends Serializable> extends JpaDaoSupport implements StrongDAO<E, PK> {  
  2.   public Class<E> entityClass;  
  3.   
  4.   @SuppressWarnings("unchecked")  
  5.   public StrongDAOImpl() {  
  6.     this.entityClass = (Class<E>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];  
  7.   }  
  8.   
  9.   @Override  
  10.   public void delete(final E entity) {  
  11.     getJpaTemplate().remove(entity);  
  12.   }  
  13.   
  14.   @Override  
  15.   public void delete(final PK id) {  
  16.     E entity = this.getByID(id);  
  17.     if (entity != null) {  
  18.       delete(entity);  
  19.     }  
  20.   }  

 

3.1之后的实现方法

Java代码  收藏代码
  1. public abstract class StrongDAOImpl<E, PK extends Serializable> implements StrongDAO<E, PK> {  
  2.   
  3.   @PersistenceContext  
  4.   private EntityManager entityManager;  
  5.   
  6.   public EntityManager getEntityManager() {  
  7.     return this.entityManager;  
  8.   }  
  9.   
  10.   public void setEntityManager(EntityManager entityManager) {  
  11.     this.entityManager = entityManager;  
  12.   }  
  13.   
  14.   public void delete(E entity) {  
  15.     if (entity == null) {  
  16.       return;// //////  
  17.     } else {  
  18.       entityManager.remove(entity);  
  19.     }  
  20.   }  
  21.   
  22.   public void delete(PK id) {  
  23.     if (id != null) {  
  24.       E entity = this.getByID(id);  
  25.       this.delete(entity);  
  26.     } else {  
  27.       return;// //////  
  28.     }  
  29.   }  

Spring3.1 对JPA支持原生的EntityManager注入
              对Hibernate也支持原生的Session操作

都不推荐使用Template了

0 0