有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何不显示密码。查找JPA

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

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

此代码返回一个用户及其所有参数,包括密码。如何从返回的实体中删除密码?因为我需要用user对象返回一个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;
}

谢谢你的建议


共 (2) 个答案

  1. # 1 楼答案

    如果我理解正确的话,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.

    试试看

  2. # 2 楼答案

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

    Class Credential {
        password;
        username;
        user;
    }
    

    也要单独定义用户

    class User {
    }
    

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

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

    当然,通常密码是散列的,您可能不想在db中保存普通密码