1
votes

I'm developing an app with a user management system. There is a database table named user with the following columns:

| Column Name     | Column Type |
|-----------------|-------------|
| userId          | BIGINT      |
| email           | TEXT        |
| firstName       | TEXT        |
| lastName        | TEXT        |
| passwordDigest  | TEXT        |
| birthday        | DATE        |
| address         | TEXT        |

And there is a corresponding Hibernate entity called User:

@Entity
@Table(name = "user")
public class User {
    @Id
    private long userId;
    private String email;
    private String firstName;
    private String lastName;
    private String passwordDigest;
    private LocalDate birthday;
    private String address;
}

However, the general user info (i.e. email, first name, last name, birthday, address) and password are getting updated in separate pages in my app. Specifically, there is a "Edit Your General Info" page for users to update their general info, and there is a separate "Update Your Password" page for users to update their passwords. Just like lots of other apps.

Therefore, the code for each pages will be:

void updateUserGeneralInfo (User newUser) {
    User oldUser = userDao.getExistingUser(newUser.getUserId());
    newUser.setPasswordDigest(oldUser.getPasswordDigest());
    userDao.updateUser(newUser);
}

void updateUserPassword (long userId, String newPassword) {
    User oldUser = userDao.getExistingUser(userId);
    oldUser.setPasswordDigest(calculateDigest(newPassword)); // auto save to DB by Hibernate
}

The problem lies in updateUserGeneralInfo(). Since newUser is passed from GUI, it doesn't contain a passwordDigest. Therefore, directly calling updateUser(newUser) would wipe out the user's passwordDigest in the DB. To avoid that, it's necessary to retrieve the user's existing entity just to fill in the password digest, so that updateUser(newUser) won't affect the user's passwordDigest. This is kind of clunky and hard to maintain.

Assuming that I am allowed to re-design what the database table user and the Hibernate entity User. Is there any way to avoid retrieving the existing entity and filling in the field passwordDigest in updateUserGeneralInfo()?

1

1 Answers

0
votes

You can use a DML statement to update only the attributes that you care about, but managed entities work this way. When a managed entity is attached to a persistence context, it is synchronized to the database.