Q:

How to not show password with .find JPA

I have a question. I have a User entity with a password in it. I have a function that returns a User object:
public User findUser(long id) {
    return em.find(User.class, id);
}

This code returns a User with all his parameters, password included. How can I remove the password from my returned entity? Because I need to send back a Json response with the user object. 
I've thought about something like that, but it's ugly...
public User findUser(long id) {
    User user = new User();
    find = em.find(User.class, id);
    user.setUsername(find.getUsername());
    user.setMail(find.getMail());

    return user;
}

Thanks for your advice.

A:

If i understand correctly, the findUser methods is a transactional one.
Also you want to clear the password inside it, but you do not want PersistenceContext to know about it and flush the change to the database causing the password to be emptied.
If this is the case then do the following:
find = em.find(User.class, id);
em.detach(find);
find.setPassword(null);

return find;

Thanks to the detachment from the PersistenceContext you can make any changes you like and they will not be persisted to the database.
Spec:

void detach(java.lang.Object entity)
Remove the given entity from the persistence context, causing a
managed entity to become detached. Unflushed changes made to the
entity if any (including removal of the entity), will not be
synchronized to the database. Entities which previously referenced the
detached entity will continue to reference it.

Try it out.

