问题是我得到LazyInitializationException但是当我不使用RxJava时我没有得到这个异常。
这里我没有例外:
<<<<<<< HEAD
在这个方法中我得到LazyInitializationException:
@Override
@Transactional
public User addOrder(String username, Order order) {
if (username != null && order!= null) {
final User user = userRepository.findByUsername(username);
if (user != null) {
user.getOrders().add(order);
order.setUser(user);
try {
return userRepository.save(user);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return null;
}
与用户相关的收集订单:
@Override
@Transactional
public Observable<User> addOrderAsynchronously(String username, Order order) {
if (username != null && order != null) {
return Observable
.fromCallable(() -> userRepository.findByUsername(username))
.filter(Objects::nonNull)
.map(user -> {
synchronized (this) {
user.getOrders().add(order); // I get here LazyInitializationException
order.setUser(user);
}
return user;
})
.map(userRepository::save);
}
return Observable.empty();
}
我将此列表映射为 @OneToMany(
mappedBy = "user",
cascade = { CascadeType.PERSIST, CascadeType.MERGE }
)
private Collection<Order> orders = new ArrayList<>();
,因为Hibernate不需要初始化Collection类型。
有什么问题?