T
T
Timofey Lanevich2019-03-02 02:46:24
Java
Timofey Lanevich, 2019-03-02 02:46:24

Only one setter fires?

Just don't hit.
Through the constructor, when creating an object, I call the setter on password and username, the password is created, but username is not ...
Code of the class entity:

@Entity
@Table(name = "users")
@NoArgsConstructor
@Getter
@Setter
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String name;
    private String email;
    private String password;
    private String userName;

    public User(String name, String email, String password) {
        this.name = name;
        this.email = email;
        setUserName(email);
        setPassword(password);
    }

    private void setUserName(String email) {
        this.userName = email.split("@")[0];
        LoggerFilter.logger.info("User.java: set user name;");
    }

    private void setPassword(String password) {
        this.password = BCrypt.hashpw(password, BCrypt.gensalt());
        LoggerFilter.logger.info("User.java: set password;");
    }
}

Logger:
5c79c31521545774178787.png
If a separate method calls the setter on username, then it works.
@PostMapping("sign-up")
    public void signUp(@RequestBody User user) {
        
        user.setUserName(user.getEmail());
        
        userRepository.save(user);

    }

Can you please tell me what is the problem, why can't I call the second setter?
Thanks for the help!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
C4ET4uK, 2019-03-03
@C4ET4uK

The spider tells me a little that I shouldn't drag Lombok anywhere. This @NoArgsConstructor annotation
creates a constructor with no arguments. Accordingly, when creating a bean, it is called, and not your overloaded one. I would also venture to suggest that you do not pass the userName parameter, respectively, and the setter is not called for it.
IMHO the correct answer is that the wrong constructor is called.

A
Alexander Kosarev, 2019-03-11
@jaxtr

As C4ET4uK already wrote , the problem is with calling the wrong constructor.
Hibernate creates an object with a default constructor, then sets the properties of the object using set methods. Accordingly, Hibernate does not use your constructor to create an object. If the value of the userName
property is not stored in the database (in the user_name column, respectively), then the Hibernate setUserName method will also never be called. Alternatively, you can add a setUserName call to setEmail .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question