I have following entities:
User:
@Entity
public class User {
@Id
@Column(nullable = false)
private String email = "";
@Column(nullable = false)
private String nickname = "";
@Column(nullable = false)
private String password = "";
@ManyToMany(cascade = CascadeType.ALL)
private List<NewsSource> newsSources;
// getters and setters
}
新闻来源:
@Entity
public class NewsSource {
@Id
@Column(nullable = false)
private URL url;
private LocalDateTime updateTime;
@OneToMany(cascade = CascadeType.ALL)
private List<News> newses;
@ManyToMany(cascade = CascadeType.ALL)
private List<User> users;
}
UsersRepository和NewsSourcesRepository是Spring Data JPA中简单的JpaRepositories。它们的配置如下:
@Configuration
@EnableTransactionManagement
@PropertySource("classpath:database_config.properties")
@EnableJpaRepositories(basePackages = {"news.repositories" })
public class RepositoriesConfiguration {
@Bean(destroyMethod = "close")
DataSource dataSource(Environment env) {
HikariConfig dataSourceConfig = new HikariConfig();
dataSourceConfig.setDriverClassName(env.getRequiredProperty("db.driver"));
dataSourceConfig.setJdbcUrl(env.getRequiredProperty("db.url"));
dataSourceConfig.setUsername(env.getRequiredProperty("db.username"));
dataSourceConfig.setPassword(env.getRequiredProperty("db.password"));
return new HikariDataSource(dataSourceConfig);
}
@Bean
LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, Environment env) {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
entityManagerFactoryBean.setPackagesToScan("pl.mielecmichal.news.entities");
Properties jpaProperties = new Properties();
jpaProperties.put("hibernate.dialect", env.getRequiredProperty("hibernate.dialect"));
jpaProperties.put("hibernate.hbm2ddl.auto", env.getRequiredProperty("hibernate.hbm2ddl.auto"));
jpaProperties.put("hibernate.ejb.naming_strategy", env.getRequiredProperty("hibernate.ejb.naming_strategy"));
jpaProperties.put("hibernate.show_sql", env.getRequiredProperty("hibernate.show_sql"));
jpaProperties.put("hibernate.format_sql", env.getRequiredProperty("hibernate.format_sql"));
entityManagerFactoryBean.setJpaProperties(jpaProperties);
return entityManagerFactoryBean;
}
@Bean
JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
}
我的测试在第15行抛出了一个LazyInitializationException异常。错误信息如下:
无法延迟初始化角色集合:news.entities.users.User.newsSources,无法初始化代理对象 - 未找到会话
@Test
public void cascadeRelationsShouldBeRetrieved() throws MalformedURLException {
NewsSource source = new NewsSource();
source.setUrl(new URL(SOME_URL));
newsSourcesRepository.save(source);
newsSourcesRepository.flush();
User user = new User();
user.setEmail(EMAIL);
List<NewsSource> sources = new ArrayList<>();
sources.add(source);
user.setNewsSources(sources);
usersRepository.save(user);
usersRepository.flush();
User savedUser = usersRepository.findOne(EMAIL);
NewsSource newsSource = savedUser.getNewsSources().get(0);
assertThat("News source should be saved", newsSource.getUrl(), is(SOME_URL));
NewsSource savedSource = newsSourcesRepository.findOne(newsSource.getUrl());
assertThat("New user should be saved in M2M relation", savedSource.getUsers(), Matchers.contains(user));
}
如果我用 @Transactional 注释我的测试,异常将不会被抛出,但我不确定这是否是解决问题的适当方式。