I have a User class marked as entity which also implements UserDetails. I want to be able to grab some properties of a certain user, and based on their values, to return specific roles in the getAuthorities method. Many of those properties are however lazy-loaded and require a Hibernate transaction.
I tried anything from making the user class @Transactional to making the UserDetailsService and RememberMeService which I use @Transactional. None of those works!
All of my other DAO and Service classes mapped as transactional work (and they are just simple classes – no other annotations besides a @Transactional on top)
UPDATE: This is the overriden getUserDetails in class User
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
GrantedAuthority auth = new GrantedAuthority() {
@Override
public String getAuthority() {
// TODO Auto-generated method stub
return "ROLE_USER";
}
};
ArrayList<GrantedAuthority> result = new ArrayList<GrantedAuthority>();
if (options.size() > 0) {
for (Option o : options) {
result.add(createAuthority(Option.getStringType(o.type)));
}
}
result.add(auth);
return result;
}
The
UserDetailsis not a Spring bean and thus is Spring is not going to look for@Transactionalon it.I would need to see a stack trace but what I’m assuming is that getAuthorities() is being called by another
UserDetailsServicemethod directly, i.e., not going through the transactional proxy.Inject the
PlatformTransactionManagerinto yourUserDetailsServiceand use aTransactionTemplateingetAuthorities()to wrap your DB accessing code in a transaction.