如何不使用 .find JPA 显示密码

How to not show password with .find JPA

我有一个问题。我有一个带有密码的用户实体。我有一个 returns 用户对象的函数:

public User findUser(long id) {
    return em.find(User.class, id);
}

此代码 returns 一个用户及其所有参数,包括密码。如何从我退回的实体中删除密码?因为我需要发回带有用户对象的 Json 响应。 我也想过类似的东西,但是很丑...

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;
}

感谢您的建议。

如果我理解正确,findUser 方法是一种事务性方法。 您还想清除其中的密码,但不希望 PersistenceContext 知道它并将更改刷新到数据库导致密码被清空。

如果是这种情况,请执行以下操作:

find = em.find(User.class, id);
em.detach(find);
find.setPassword(null);

return find;

由于与 PersistenceContext 的分离,您可以进行任何您喜欢的更改,并且它们不会持久保存到数据库中。 规格:

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.

试试吧。

在这种情况下,建议您使用单独的域作为凭据。例如

Class Credential {
    password;
    username;
    user;
}

也单独定义用户。

class User {
}

然后在凭据域的命名查询上使用 jpa 登录用户。

SELECT c.user FROM Credential c WHERE c.username = :username AND password = :password;

当然通常密码是散列的,你可能不想在数据库中保存普通密码