I am a little bit confused: I have a Java EE application with JSF, EJB and JPA.
I have a UserService
which is an EJB
.
@Stateless
public class UserService {
public User create(User u) throws ProcessingException {
if (!exists(u)) {
u = userDao.create(u);
addRole(u, RoleType.USER);
return u;
} else {
throw new ProcessingException("User " + u.getUsername() + " already exists");
}
}
public boolean hasRole(User u, RoleType r) {
if (u == null || r == null) {
return false;
}
if (!userDao.isManaged(u)) {
u = userDao.find(u.getId());
}
Set<Role> roles = u.getRoles();
...
}
}
I had some problems and did some debugging and found out that sometimes in hasRole
, the User
is not in managed-state, why I do userDao.isManaged(u)
. However I can't understand why it is sometimes not managed. Can you explain why?
Example:
@Test
public void test() throws ProcessingException {
Client c = clientBuilder.build();
User u = new User();
u.setClient(c);
userService.create(u);
userService.addRole(u, RoleType.APPROVER);
When addRole(u, RoleType.APPROVER)
is called, then u
has state unmanaged. But why?!
Do I always have to add checks to my methods in order to be sure that the entity is managed?