【发布时间】:2013-06-30 21:44:27
【问题描述】:
有没有类似OpenEntityManagerInViewInterceptor 的 CLI 应用程序?
我正在尝试在 CLI 应用程序中使用 Spring 的 CrudRepository 和由 Hibernate 4 支持的 JPA 数据源。
我的main 方法创建一个包含该方法的类的实例,并使用context.getBeanFactory().autowireBean(object); 注入服务。
用于获取数据的服务具有使用@Transactional 注释的方法。这些方法调用CrudRepository 的方法。
但是当我尝试在 CLI 应用程序中管理相关实体时收到org.hibernate.LazyInitializationException。
是否有任何解决方法可以在 @Transactional 方法之外的 CLI 应用程序中进行延迟加载,例如用于 Web 应用程序的 OpenEntityManagerInViewInterceptor?
看下面的sn-p:
public class test {
@Autowired
public UserService userService;
public static void main(String[] args) {
test test = new test();
//injecting dependencies into test
test.run();
}
private void run() {
User user = userService.findById(42);
System.out.println(user.getLogin()); //User was fetched successfully
Address address = new Address("London");
user.addAddress(address);//Exception in thread "main" java.lang.RuntimeException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection
}
}
【问题讨论】:
标签: java spring hibernate spring-data spring-data-jpa