Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring JPA配置:EntityManager抛出NullPointerException_Spring_Spring Mvc_Jpa_Entitymanager_Spring Java Config - Fatal编程技术网

Spring JPA配置:EntityManager抛出NullPointerException

Spring JPA配置:EntityManager抛出NullPointerException,spring,spring-mvc,jpa,entitymanager,spring-java-config,Spring,Spring Mvc,Jpa,Entitymanager,Spring Java Config,我试图在Spring中创建一个RESTAPI,并且只需要使用JavaConfig通过JPA建立数据库连接。这是我的配置类: @Configuration @ComponentScan @EnableTransactionManagement public class ApplicationConfig { @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final Loca

我试图在Spring中创建一个RESTAPI,并且只需要使用JavaConfig通过JPA建立数据库连接。这是我的配置类:

@Configuration
@ComponentScan
@EnableTransactionManagement
public class ApplicationConfig {
@Bean
   public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
      final LocalContainerEntityManagerFactoryBean em = new  LocalContainerEntityManagerFactoryBean();
      em.setDataSource(dataSource());
      em.setPackagesToScan(new String[] { "com.backend.domain", "com.backend.infrastructure.persistence" } );
      JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
      em.setJpaVendorAdapter(vendorAdapter);
      em.setJpaProperties(additionalProperties());
      em.afterPropertiesSet();

      return em;
   }

   @Bean
   public DataSource dataSource(){
      DriverManagerDataSource dataSource = new DriverManagerDataSource();
      dataSource.setDriverClassName("com.mysql.jdbc.Driver");
      dataSource.setUrl("jdbc:mysql://localhost:3306/mydb");
      dataSource.setUsername( "root" );
      dataSource.setPassword( "root" ); 
      return dataSource;
   }

   @Bean
   public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
      JpaTransactionManager transactionManager = new JpaTransactionManager();
      transactionManager.setEntityManagerFactory(emf);

      return transactionManager;
   }



   @Bean
   public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
      return new PersistenceExceptionTranslationPostProcessor();
   }

   Properties additionalProperties() {
      Properties properties = new Properties();
      properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
      properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
      properties.setProperty("hibernate.show_sql", "true");
      properties.setProperty("hibernate.format_sql", "true");
      return properties;
   }
 }
我有一个自定义存储库实现,因此:

@Repository
@Transactional
public class GenericRepositoryImpl<K, E> implements GenericRepository<K, E> {

 protected static final Logger LOG = LoggerFactory.getLogger(GenericRepositoryImpl.class);
 private Class<E> entityClass;

 @PersistenceContext()
 protected EntityManager entityManager;



 @SuppressWarnings("unchecked")
    public GenericRepositoryImpl() {
        ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
        this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[0];
    }

    public void start() throws DomainException {
        try {
            entityManager.getTransaction().begin();
        } catch (Exception e) {
            LOG.error(e.getMessage());
            throw new DomainException(e);
        }
    }

    public void commit() throws DomainException {
        try {
            entityManager.getTransaction().commit();
        } catch (Exception e) {
            LOG.error(e.getMessage());
            throw new DomainException(e);
        }
    }

    @Override
    public void detach(E entity) throws DomainException {
        try {
            entityManager.detach(entity);
        } catch (Exception e) {
            LOG.error(e.getMessage());
            throw new DomainException(e);
        }
    }

    @Override
    public E findById(K id) throws DomainException {
        try {
            return entityManager.find(entityClass, id);
        } catch (Exception e) {
            LOG.error(e.getMessage());
            throw new DomainException(e);
        }
    }

    @Override
    public E findLockedEntityById(K id) throws DomainException {
        try {
            return entityManager.find(entityClass, id, LockModeType.OPTIMISTIC);
        } catch (Exception e) {
            LOG.error(e.getMessage());
            throw new DomainException(e);
        }
    }

    @Override
    public void persist(E entity) throws DomainException {
        try {
            entityManager.persist(entity);
        } catch (Exception e) {
            LOG.error(e.getMessage());
            throw new DomainException(e);
        }
    }

    @Override
    public E merge(E entity) throws DomainException {
        try {
            return entityManager.merge(entity);
        } catch (Exception e) {
            LOG.error(e.getMessage());
            throw new DomainException(e);
        }
    }

    @Override
    public void flush() throws DomainException {
        try {
            entityManager.flush();
        } catch (Exception e) {
            LOG.error(e.getMessage());
            throw new DomainException(e);
        }
    }

    @Override
    public void remove(E entity) throws DomainException {
        try {
            entityManager.remove(entity);
        } catch (Exception e) {
            LOG.error(e.getMessage());
            throw new DomainException(e);
        }
    }

    @Override
    public void refresh(E entity) throws DomainException {
        try {
            entityManager.refresh(entity);
        } catch (Exception e) {
            LOG.error(e.getMessage());
            throw new DomainException(e);
        }
    }

    @Override
    public void refreshLockedEntity(E entity) throws DomainException {
        try {
            entityManager.refresh(entity, LockModeType.OPTIMISTIC);
        } catch (Exception e) {
            LOG.error(e.getMessage());
            throw new DomainException(e);
        }
    }

    @Override
    public void lock(E entity) throws DomainException {
        try {
            entityManager.lock(entity, LockModeType.OPTIMISTIC);
        } catch (Exception e) {
            LOG.error(e.getMessage());
            throw new DomainException(e);
        }
    }

}
@存储库
@交易的
公共类GenericRepositoryImpl实现GenericRepository{
受保护的静态最终记录器日志=LoggerFactory.getLogger(GenericRepositoryImpl.class);
私有类实体类;
@PersistenceContext()
受保护的实体管理器实体管理器;
@抑制警告(“未选中”)
公共一般报告impl(){
ParameteredType genericSuperclass=(ParameteredType)getClass().getGenericSuperclass();
this.entityClass=(类)genericSuperclass.getActualTypeArguments()[0];
}
public void start()引发DomainException{
试一试{
entityManager.getTransaction().begin();
}捕获(例外e){
LOG.error(例如getMessage());
抛出新的域异常(e);
}
}
public void commit()引发DomainException{
试一试{
entityManager.getTransaction().commit();
}捕获(例外e){
LOG.error(例如getMessage());
抛出新的域异常(e);
}
}
@凌驾
public void detach(E实体)引发DomainException{
试一试{
entityManager.detach(实体);
}捕获(例外e){
LOG.error(例如getMessage());
抛出新的域异常(e);
}
}
@凌驾
公共E findById(K id)抛出DomainException{
试一试{
返回entityManager.find(entityClass,id);
}捕获(例外e){
LOG.error(例如getMessage());
抛出新的域异常(e);
}
}
@凌驾
公共E findLockedEntityById(K id)引发DomainException{
试一试{
返回entityManager.find(entityClass,id,LockModeType.Optimized);
}捕获(例外e){
LOG.error(例如getMessage());
抛出新的域异常(e);
}
}
@凌驾
public void persist(E实体)引发DomainException{
试一试{
entityManager.persist(实体);
}捕获(例外e){
LOG.error(例如getMessage());
抛出新的域异常(e);
}
}
@凌驾
公共E合并(E实体)引发DomainException{
试一试{
返回entityManager.merge(实体);
}捕获(例外e){
LOG.error(例如getMessage());
抛出新的域异常(e);
}
}
@凌驾
public void flush()引发DomainException{
试一试{
entityManager.flush();
}捕获(例外e){
LOG.error(例如getMessage());
抛出新的域异常(e);
}
}
@凌驾
public void remove(E实体)引发DomainException{
试一试{
entityManager.remove(实体);
}捕获(例外e){
LOG.error(例如getMessage());
抛出新的域异常(e);
}
}
@凌驾
公共无效刷新(E实体)引发DomainException{
试一试{
entityManager.refresh(实体);
}捕获(例外e){
LOG.error(例如getMessage());
抛出新的域异常(e);
}
}
@凌驾
public void refreshLockedEntity(E实体)引发DomainException{
试一试{
entityManager.refresh(实体,LockModeType.OPTIMISTIC);
}捕获(例外e){
LOG.error(例如getMessage());
抛出新的域异常(e);
}
}
@凌驾
公共无效锁(E实体)引发DomainException{
试一试{
entityManager.lock(实体,LockModeType.Optimized);
}捕获(例外e){
LOG.error(例如getMessage());
抛出新的域异常(e);
}
}
}
它编译正确,我可以看到数据库连接正在建立,但在尝试保存实体时,会调用merge()方法并抛出NullPointerException。我做错了什么


提前感谢

您如何使用
通用存储impl
。查看实现时,您的启动/提交方法不应该存在,因为您使用的是
@Transactional
。另一个技巧不是尝试编写自己的通用解决方案,我强烈建议您看看哪些解决方案已经为您完成了所有这些。我也尝试过不使用@Transactional,但问题仍然存在。我从GenericRepositoryImpl扩展了其他自定义存储库。我已经看过Spring数据JPA,但我非常想知道我在这里做错了什么。正如我在前面的评论中所问的,请添加代码,显示您在哪里使用这个类以及如何获得这个类。