这段时间准备把几个基础库类重写,之前发现了Spring升级到3.1之后以前写的DAO类出现deprecated的问题,当时没有仔细研究把Spring降到3.0.5了事。最近突然想到这个问题觉得还是要研究一下,于是找来资料看看,发现Spring在3.1之后决定完全支持JPA2标准,准备放弃之前的JpaDaoSupport和JpaTemplate等。也就是说,以后Spring不再使用JpaTemplate的方式去回调实现JPA的接口,而是完全采用注解和注入的方式去实现,这样就实现了Spring的完全解耦合。恩,是个不错的思路!
对比一下代码来发现不同之处
3.1之前我扩展的DAO类
- public abstract class StrongDAOImpl<E, PK extends Serializable> extends JpaDaoSupport implements StrongDAO<E, PK> {
- public Class<E> entityClass;
- @SuppressWarnings("unchecked")
- public StrongDAOImpl() {
- this.entityClass = (Class<E>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
- }
- @Override
- public void delete(final E entity) {
- getJpaTemplate().remove(entity);
- }
- @Override
- public void delete(final PK id) {
- E entity = this.getByID(id);
- if (entity != null) {
- delete(entity);
- }
- }
3.1之后的实现方法
- public abstract class StrongDAOImpl<E, PK extends Serializable> implements StrongDAO<E, PK> {
- @PersistenceContext
- private EntityManager entityManager;
- public EntityManager getEntityManager() {
- return this.entityManager;
- }
- public void setEntityManager(EntityManager entityManager) {
- this.entityManager = entityManager;
- }
- public void delete(E entity) {
- if (entity == null) {
- return;// //////
- } else {
- entityManager.remove(entity);
- }
- }
- public void delete(PK id) {
- if (id != null) {
- E entity = this.getByID(id);
- this.delete(entity);
- } else {
- return;// //////
- }
- }
Spring3.1 对JPA支持原生的EntityManager注入
对Hibernate也支持原生的Session操作
都不推荐使用Template了
对Hibernate也支持原生的Session操作
都不推荐使用Template了