EclipseLink,可在事务外部访问懒惰的获取集合 [英] EclipseLink, lazy fetch collection is accessible outside of transaction
问题描述
我有一个名为User
的实体,该实体具有以下名为roles
的字段:
I have an entity named User
which has the following field called roles
:
@ManyToMany
@JoinTable(
name = "user_role",
joinColumns = {@JoinColumn(name = "user_id", nullable = false)},
inverseJoinColumns = {@JoinColumn(name = "role_id", nullable = false)}
)
private List<Role> roles;
我使用服务方法加载User
,并且该服务方法包装在事务(JTA)中.调用服务方法并检索User
之后,我在用于加载User
实体的事务之外访问此role
字段.我期望得到一个错误,因为eclipselink文档指出,默认情况下,ManyToMany关联的特征类型为
I load the User
via the use of a service method and the service method is wrapped in a transaction (JTA). After calling the service method and retrieving the User
, I access this role
field outside of the transaction that was used to load the User
entity. I was expecting to get an error because the eclipselink documentation states that, by default, the fechtype for a ManyToMany association is lazy. This tells me that when the User
entity was loaded in the service method, the roles
should not be automatically loaded.
为什么我可以在交易之外访问roles
?为什么看起来roles
是急切地取而代之的,而不是懒惰的?
Why was I able to access the roles
outside of the transaction? Why does it seem like the roles
were fetched eagerly instead of lazy?
这是加载用户的服务类(我删除了一些与问题无关的代码):
Here is the service class which loads the user (I've removed some code not relevant to the question):
@Service
@Transactional(rollbackFor = ServiceException.class)
public class UserServiceImpl implements UserService {
@Autowired(required = true)
private UserRepository userRepository;
@Override
public User authenticate(String username, String password) throws ServiceException {
//Get the user
List<User> users = userRepository.findByUsername(username);
if (users == null || users.isEmpty() || users.size() > 1) {
return null;
}
User user = users.get(0);
String hash = getHash(password, user.getSalt());
return StringUtils.equals(hash, user.getPassword()) ? user : null;
}
}
推荐答案
只要上下文仍然可用,EclipseLink即可获取惰性关系,如下所述:
EclipseLink allows fetching lazy relationships as long as the context is still available as described here: https://forums.oracle.com/forums/thread.jspa?messageID=1706796
这篇关于EclipseLink,可在事务外部访问懒惰的获取集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!