简体   繁体   中英

Spring Service - Should I pass an entity Id or the entity itself?

I have a User hibernate entity:

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column
    private String username;

    @Column
    private String password;

    // Getters and setters here
}

If I want to create a UserService method that validates the credentials of a user, should the design of the validate method be like this:

public Boolean validate(Long userId, String username, String password)

or like this:

public Boolean validate(User user, String username, String password)

Which design would be better? Thank you for your time

Your design goal does not make sense to me. The only time you should need a username and a password is during login. At that time, the username and password should uniquely identify a user.

I believe the method you want is this:

publid Optional<User> login(
    final String username,
    final String password);

Then either return an Optional that contains a User (as identified by the correct username and password combination) or return an Optional with null to indentify a bad combination of username and password.

I would create the User's instance with the given username, password and search in the database if the user is exits or not.

Pseudo code:

public booelan validate(User user) {
    userService.findUser(user) != null;
}

You should create the User's instance with the given username, password

User user = new User(userName, password);\\\\I am assuming username should be unique

Then use in your code:

if (isValidate(user)) {
    //doSomething();
}

You can simply add a method in your UserRepository :

    User findByIdAndUsernameAndPassword(long id, String userName, String pass);

This will return a User if all of these fields match with a specific database entry.

Passing entityId is better , I hope this addresses what you were asking.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM