2017-08-07 12 views
0

私はdaoメソッドを使用しようとするbussinessロジッククラスを持っています。これは、汎用Daoから保存します。これはblのコードです。NullPointerException hibernate Springを持つ汎用Dao

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

デバッグiは、ユーザーオブジェクトが正しくデータで満たされていることが判明し、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管理トランザクションを混在させても、動作しません。あなたは春を使用しているので、チュートリアルに従うことができます。チュートリアルhttps://spring.io/guides/gs/accessing-data-jpa/ –

+0

@André私はウェブ開発で新しいと私はあなたが本当に混乱して答えを見つけました – Andres

+0

あなたはそうではありませんSpringがあなたのためにトランザクションを管理できるようにします。 '@ Autowired'と' @ Transaction'だけが必要です。そのチュートリアルは必要なものすべてです。 Spring JPAのチュートリアルを読んでください。あなたは、あなたのコードを動作させるために遠くに行かないでしょう。 –

答えて

0

さて、私は私の休止状態セッションBean宣言に助けをすべてのおかげでエラーが発生しました

1

コンテナ作成のDAOオブジェクト豆ていることを確認して、自分のサービス・クラスで を注入するには、あなたがタグの後、あなたの春の設定ファイル/クラスを追加しましたことを確認してください/ annotation--

@ComponentScan(BasePackages="fully Qualified dao class name") 
following--

を試してみてください

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

+0

こんにちは私のコンテキスト:コンポーネントスキャンは、私は正しいと思うプロジェクトのメインフォルダを持っている?ありがとう – Andres

+0

daoクラスで '@リポジトリ'または '@コンポーネント'アノテーションを使用していることを確認してください –