我似乎不能让我的Spring JPA配置正常工作。我有一个Spring REST服务。如果我将所有实体都设置为FetchType.EAGER,一切都会正常工作。但出于显而易见的原因,我不想这么做。
当我将我的实体设置为FetchType.LAZY时,我得到以下错误:
proxy org.hibernate.LazyInitializationException:延迟初始化角色集合失败: com.service.entities.MyEntity.lawfirmCaseDecisions,无法初始化
-无会话
我已经看过其他类似的SO问题,但我仍然遇到了同样的问题。这是我的配置:
@Configuration
@Import(EnvironmentProvider.class)
@EnableTransactionManagement
@Slf4j
public class DataSourceProvider {
@Autowired EnvironmentProvider envProvider;
@Bean
DataSource dataSource() {
final EnvConfig env = envProvider.envConfig();
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUrl(env.findProperty("db.url"));
dataSource.setPortNumber( Integer.parseInt(env.findProperty("db.port")) );
dataSource.setUser(env.findProperty("db.username"));
dataSource.setPassword(env.findProperty("db.password"));
return dataSource;
}
@Bean
LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPackagesToScan("com.offtherecord.service.core.entities");
//entityManagerFactoryBean.setPersistenceUnitName("OTR");
HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
entityManagerFactoryBean.setJpaVendorAdapter(va);
Properties ps = new Properties();
ps.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
// ps.put("hibernate.show_sql", "true"); //useful for debugging
ps.put("hibernate.format_sql", "true");
entityManagerFactoryBean.setJpaProperties(ps);
return entityManagerFactoryBean;
}
@Bean
@PersistenceContext
JpaTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().nativeEntityManagerFactory);
return transactionManager;
}
}
为了快速测试,我在控制器方法上添加了@Transactional注释。在下面的代码中,UserEntity类有一个没有填充的订单列表:
@RequestMapping(method = RequestMethod.GET)
@Transactional
public ResponseEntity<GetOrdersResponse> getOrders() {
UserEntity activeUser = controllerUtil.getActiveUser();
...
return new ResponseEntity<>(new GetOrdersResponse(), HttpStatus.OK);
}
我很想忘掉这件事!
发布于 2015-06-29 17:23:54
您需要使用类似于referenced from here.的方法
@Entity
@NamedEntityGraph(name = "GroupInfo.detail",
attributeNodes = @NamedAttributeNode("members"))
public class GroupInfo {
// default fetch mode is lazy.
@ManyToMany
List<GroupMember> members = new ArrayList<GroupMember>();
…
}
示例48。引用存储库查询方法上的命名实体图定义。
@Repository
public interface GroupRepository extends CrudRepository<GroupInfo, String> {
@EntityGraph(value = "GroupInfo.detail", type = EntityGraphType.LOAD)
GroupInfo getByGroupName(String name);
}
在上面的示例中,您需要标记该特定方法中的成员,您希望在该方法中迫切地加载特定的关联。在上面的示例中,它是"members“字段。
一般来说,所有的关联都被标记为惰性的,并且您想要获取的那些作为case需求的关联可以被获取,可以创建这样的特殊方法。
当然有效,谢谢。
https://stackoverflow.com/questions/31062867
复制相似问题