春季数据jpa

时间:2019-02-20 06:17:13

标签: java spring hibernate jpa spring-data-jpa

我在春季数据jpa中遇到了'org.hibernate.LazyInitializationException: could not initialize proxy - no Session'。

下面是我的代码。

    // this is service layer
    @Transactional(rollbackFor = Exception.class)
    public BlogEntity saveBlog(BlogEntity blogEntityInput) {
        BlogEntity blogEntity = blogDao.find(blogEntityInput.getId());
        System.out.println(blogEntity);
        return blogDao.saveBlog(blogEntityInput);
    }

   // this is dao layer which will call
   @Override
   public BlogEntity find(Integer id) {
    return blogRepository.getOne(id); // JpaRepository#getOne
   }

在调用 getOne 后打印 blogEntity 时,将发生异常。我知道 getOne 是延迟加载的。 但是我已经添加了 @Transactional ,它将确保内部方法在休眠会话中。 LazyInitializationException仍如何发生?

谢谢。

下面是我完整的数据库相关的Spring代码。

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
  entityManagerFactoryRef = "h2_entityManagerFactory",
  basePackages = { "com.taobao.rest.repository.h2" },
        transactionManagerRef = "h2_manager"

)
public class H2DBConfig {

  @Primary
  @Bean(name = "h2_dataSource")
  public DataSource dataSource(){
      DriverManagerDataSource dataSource = new DriverManagerDataSource();
      dataSource.setDriverClassName("org.h2.Driver");
      dataSource.setUrl("jdbc:h2:~/new-taobao");
      dataSource.setUsername("taobao");
      dataSource.setPassword("");

      return dataSource;
  }

  @Primary
  @Bean(name = "h2_entityManagerFactory")
  public LocalContainerEntityManagerFactoryBean h2EntityManagerFactory() {
      LocalContainerEntityManagerFactoryBean em
              = new LocalContainerEntityManagerFactoryBean();
      em.setDataSource(dataSource());
      em.setPackagesToScan(new String[] { "com.taobao.rest.entity.h2" });
      em.setPersistenceUnitName("h2_unit");
      JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
      em.setJpaVendorAdapter(vendorAdapter);
      em.setJpaProperties(additionalProperties());

      return em;
  }

  Properties additionalProperties() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.hbm2ddl.auto", "update");
        properties.setProperty(
                "hibernate.dialect", "org.hibernate.dialect.H2Dialect");
        properties.setProperty("hibernate.show_sql", "true");
        return properties;
    }


    @Bean(name = "h2_manager")
    public PlatformTransactionManager transactionManager(
            @Qualifier("h2_entityManagerFactory") EntityManagerFactory emf){
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);
        return transactionManager;
    }
}

0 个答案:

没有答案