2017-08-07 191 views
0

我有一個bussiness邏輯類,嘗試使用dao方法保存從一個通用的道,這是來自BL的代碼。NullPointerException休眠與春天Generic Dao

public void setUsuario(Usuario usuario) { 
    this.usuario = usuario; 
    usuarioDao.save(usuario); 
} 

調試我發現,用戶對象適當地填充了數據並且DaoImpl是本

@Component 
public class UsuarioDaoImpl extends GenericDaoImpl<Usuario> implements UsuarioDao { 

@Override 
public Usuario get(String id) throws DataAccessException { 
    // TODO Auto-generated method stub 
    return null; 
} 

@Override 
public boolean saveBatchFull(Collection<Usuario> entity, boolean update) throws DataAccessException { 
    // TODO Auto-generated method stub 
    return false; 
} 

@Override 
public Usuario get(Long id) throws DataAccessException { 
    // TODO Auto-generated method stub 
    return null; 
} 

@Override 
public boolean save(Usuario usuario) throws DataAccessException { 
    super.save(usuario); 
    return false; 
} 

,這是一般類即時通訊使用。

import java.lang.reflect.ParameterizedType; 
import java.util.Collection; 
import java.util.Iterator; 
import org.slf4j.LoggerFactory; 
import org.apache.log4j.LogManager; 
import org.apache.logging.log4j.*; 
import org.apache.log4j.LogManager; 
import org.apache.log4j.Logger; 
import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.hibernate.Transaction; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.dao.DataAccessException; 
import org.springframework.transaction.annotation.Transactional; 


public class GenericDaoImpl<T> implements GenericDao<T> { 



     private static final Logger logger = LogManager.getLogger("GenericDaoImpl"); 



     protected Class<T> domainClass; 



//   @Autowired(required = true) 
      protected SessionFactory sessionFactory; 



     // Para conexion sin Injection Dependency 

     private Transaction transactionNoID; 



     public GenericDaoImpl() { 

      // Constructor default 

     } 



     // Obtener el objeto 

     @SuppressWarnings({ "unchecked", "rawtypes" }) 

     protected Class<T> getDomainClass() { 

      if (domainClass == null) { 

        ParameterizedType thisType = (ParameterizedType) getClass().getGenericSuperclass(); 

        domainClass = (Class) thisType.getActualTypeArguments()[0]; 

      } 

      return domainClass; 

     } 



     @SuppressWarnings("unchecked") 

     @Transactional(readOnly = true) 

     public T get(Long id) throws DataAccessException { 

      Session session = null; 

      if (sessionFactory != null) { 

        session = this.sessionFactory.getCurrentSession(); 

      } 



      String listQuery; 

      StringBuilder sb = new StringBuilder(" from "); 

        sb.append(this.getDomainClass().getName()); 

        sb.append(" entity "); 

        sb.append(" where id = :id "); 

      listQuery = sb.toString(); 



      T result = null; 



      if (session == null) { 

        session = SessionFactoryUtil.getSessionFactory().openSession(); 

        try { 

          result = (T) session.createQuery(listQuery).setLong("id", id).uniqueResult(); 

        } catch (Exception e) { 

          e.printStackTrace(); 

          logger.info("Error en la clase: " + this.getClass().getName() + " - " + e.getMessage()); 

        } finally { 

          session.close(); 

        } 

      } else { 

        try {      

          result = (T) session.createQuery(listQuery).setLong("id", id).uniqueResult(); 

        } catch (Exception e) { 

          e.printStackTrace(); 

          logger.info("Error en la clase: " + this.getClass().getName() + " - " + e.getMessage()); 

        } 

      } 


      return result; 

     } 



     @SuppressWarnings("unchecked") 

     @Transactional(readOnly = true) 

     public T get(String id) throws DataAccessException { 

      Session session = null; 

      if (sessionFactory != null) { 

        session = this.sessionFactory.getCurrentSession(); 

      } 



      String listQuery; 

      StringBuilder sb = new StringBuilder(" from "); 

        sb.append(this.getDomainClass().getName()); 

        sb.append(" entity "); 

        sb.append(" where id = :id "); 

      listQuery = sb.toString(); 



      T result = null; 



      if (session == null) { 

        session = SessionFactoryUtil.getSessionFactory().openSession(); 

        try { 

          result = (T) session.createQuery(listQuery).setString("id", id).uniqueResult(); 

        } catch (Exception e) { 

          e.printStackTrace(); 

          logger.info("Error en la clase: " + this.getClass().getName() + " - " + e.getMessage()); 

        } finally { 

          session.close(); 

        } 

      } else { 

        try {      

          result = (T) session.createQuery(listQuery).setString("id", id).uniqueResult(); 

        } catch (Exception e) { 

          e.printStackTrace(); 

          logger.info("Error en la clase: " + this.getClass().getName() + " - " + e.getMessage()); 

        } 

      } 



      return result; 

     } 



     @SuppressWarnings("unchecked") 

     @Transactional(readOnly = true) 

     public Collection<T> list() throws DataAccessException { 

      Session session = null; 

      if (sessionFactory != null) { 

        session = this.sessionFactory.getCurrentSession(); 

      } 



      String listQuery; 

      StringBuilder sb = new StringBuilder(" from "); 

        sb.append(this.getDomainClass().getName()); 

        sb.append(" entity "); 

      listQuery = sb.toString(); 



      Collection<T> result = null; 



      if (session == null) { 

        session = SessionFactoryUtil.getSessionFactory().openSession(); 

        try { 

          result = session.createQuery(listQuery).list(); 

        } catch (Exception e) { 

          e.printStackTrace(); 

          logger.info("Error en la clase: " + this.getClass().getName() + " - " + e.getMessage()); 

        } finally { 

          session.close(); 

        } 

      } else { 

        try {      

          result = session.createQuery(listQuery).list(); 

        } catch (Exception e) { 

          e.printStackTrace(); 

          logger.info("Error en la clase: " + this.getClass().getName() + " - " + e.getMessage()); 

        } 

      } 



      return result; 

     } 



     @SuppressWarnings("unchecked") 

     @Transactional(readOnly = true) 

     public Collection<T> listById(Long id) throws DataAccessException { 

      Session session = null; 

      if (sessionFactory != null) { 

        session = this.sessionFactory.getCurrentSession(); 

      } 



      String listQuery; 

      StringBuilder sb = new StringBuilder(" from "); 

        sb.append(this.getDomainClass().getName()); 

        sb.append(" entity "); 

        sb.append(" where id = :id "); 

      listQuery = sb.toString(); 



      Collection<T> result = null; 



      if (session == null) { 

        session = SessionFactoryUtil.getSessionFactory().openSession(); 

        try { 

          result = session.createQuery(listQuery).setLong("id", id).list(); 

        } catch (Exception e) { 

          e.printStackTrace(); 

          logger.info("Error en la clase: " + this.getClass().getName() + " - " + e.getMessage()); 

        } finally { 

          session.close(); 

        } 

      } else { 

        try {      

          result = session.createQuery(listQuery).setLong("id", id).list(); 

        } catch (Exception e) { 

          e.printStackTrace(); 

          logger.info("Error en la clase: " + this.getClass().getName() + " - " + e.getMessage()); 

        } 

      } 



      return result; 

     } 



     @SuppressWarnings("unchecked") 

     @Transactional(readOnly = true) 

     public Collection<T> listById(String id) throws DataAccessException { 

      Session session = null; 

      if (sessionFactory != null) { 

        session = this.sessionFactory.getCurrentSession(); 

      } 



      String listQuery; 

      StringBuilder sb = new StringBuilder(" from "); 

        sb.append(this.getDomainClass().getName()); 

        sb.append(" entity "); 

        sb.append(" where id = :id "); 

      listQuery = sb.toString(); 



      Collection<T> result = null; 



      if (session == null) { 

        session = SessionFactoryUtil.getSessionFactory().openSession(); 

        try { 

          result = session.createQuery(listQuery).setString("id", id).list(); 

        } catch (Exception e) { 

          e.printStackTrace(); 

          logger.info("Error en la clase: " + this.getClass().getName() + " - " + e.getMessage()); 

        } finally { 

          session.close(); 

        } 

      } else { 

        try {      

          result = session.createQuery(listQuery).setString("id", id).list(); 

        } catch (Exception e) { 

          e.printStackTrace(); 

          logger.info("Error en la clase: " + this.getClass().getName() + " - " + e.getMessage()); 

        } 

      } 



      return result; 

     } 



     @Transactional 

     public boolean save(Object entity) throws DataAccessException { 

      Session session = null; 

      if (sessionFactory != null) { 

        session = this.sessionFactory.getCurrentSession(); 

      } 



      if (session == null) { 

        session = SessionFactoryUtil.getSessionFactory().openSession(); 

        try { 

          transactionNoID = session.beginTransaction(); 

          session.saveOrUpdate(entity); 

          transactionNoID.commit(); 

          return true; 

        } catch (Exception e) { 

          transactionNoID.rollback(); 

          e.printStackTrace(); 

          logger.info("Error en la clase: " + this.getClass().getName() + " - " + e.getMessage()); 

        } finally { 

          session.close(); 

        } 

      } else { 

        try {      

          session.saveOrUpdate(entity); 

        } catch (Exception e) { 

          e.printStackTrace(); 

          logger.info("Error en la clase: " + this.getClass().getName() + " - " + e.getMessage()); 

        } 

      } 



      return false; 

     } 



     @Transactional 

     public boolean saveNoUpdate(Object entity) throws DataAccessException { 

      Session session = null; 

      if (sessionFactory != null) { 

        session = this.sessionFactory.getCurrentSession(); 

      } 



      if (session == null) { 

        session = SessionFactoryUtil.getSessionFactory().openSession(); 

        try { 

          transactionNoID = session.beginTransaction(); 

          session.save(entity); 

          transactionNoID.commit(); 

          return true; 

        } catch (Exception e) { 

          transactionNoID.rollback(); 

          e.printStackTrace(); 

          logger.info("Error en la clase: " + this.getClass().getName() + " - " + e.getMessage()); 

        } finally { 

          session.close(); 

        } 

      } else { 

        try {      

          session.save(entity); 

        } catch (Exception e) { 

          e.printStackTrace(); 

          logger.info("Error en la clase: " + this.getClass().getName() + " - " + e.getMessage()); 

        } 

      } 



      return false; 

     } 





     @SuppressWarnings({ "unchecked", "rawtypes" }) 

     @Transactional 

     @Override 

     public boolean saveBatchFull(Collection<T> entity, boolean update) throws DataAccessException { 

      Session session = null; 

      if (sessionFactory != null) { 

        session = this.sessionFactory.getCurrentSession(); 

      } 



      if (session == null) { 

        session = SessionFactoryUtil.getSessionFactory().openSession(); 

        try { 

          transactionNoID = session.beginTransaction(); 

          for (Iterator iterator = entity.iterator(); iterator.hasNext();) { 

            T t = (T) iterator.next(); 

            if (update) { 

             session.saveOrUpdate(t); 

            } else { 

             session.save(t); 

            } 

          } 

          transactionNoID.commit(); 

          return true; 

        } catch (Exception e) { 

          transactionNoID.rollback(); 

          e.printStackTrace(); 

          logger.info("Error en la clase: " + this.getClass().getName() + " - " + e.getMessage()); 

        } finally { 

          session.close(); 

        } 

      } else { 

        try { 

          for (Iterator iterator = entity.iterator(); iterator.hasNext();) { 

            T t = (T) iterator.next(); 

            if (update) { 

             session.saveOrUpdate(t); 

            } else { 

             session.save(t); 

            } 

          } 

          return true; 

        } catch (Exception e) { 

          e.printStackTrace(); 

          logger.info("Error en la clase: " + this.getClass().getName() + " - " + e.getMessage()); 

        } 

      } 



      return false; 

     } 



     public SessionFactory getSessionFactory() { 

      return sessionFactory; 

     } 



     @Transactional 

     public void flush() throws DataAccessException { 

      sessionFactory.getCurrentSession().flush(); 

     } 



} 

有人可以請幫助理解爲什麼當對象用戶在save()中使用時出現此錯誤。

謝謝。

+1

您正在混合容器管理的事務和bean管理的事務,它將不起作用。既然你使用的是spring,你可以按照教程https://spring.io/guides/gs/accessing-data-jpa/ –

+0

@André對不起,即時通訊新的web開發,我發現你的回答非常混亂 – Andres

+0

你不是讓Spring爲您管理交易。你只需要'@ Autowired'和'@ Transaction'。該教程是您需要的一切。刮掉所有內容並閱讀Spring JPA上的其他一些教程,直到您掌握它爲止。你不會走得太遠,試圖讓你的代碼工作。 –

回答

0

嗯,我在我的Hibernate的Session Bean聲明由於一個錯誤的所有的幫助

1

確保容器創建DAO對象豆和服務類注射 嘗試following--

確保您添加下面的標記/ annotation--

@ComponentScan(BasePackages="fully Qualified dao class name") 
Spring配置文件/班

<context:component-scan="fully Qualified dao class name">

+0

您好我的背景:組件掃描有項目的主文件夾,我認爲是正確的?謝謝 – Andres

+0

確保你在dao類中使用'@repository'或'@component'註釋 –