How to persist data from the entity class and combined with data transfer object?

纵饮孤独 提交于 2020-06-17 13:15:31

问题


I'm working on an authentication feature and have run into an issue with persisting the data from the entity class. I'm able to access the password_hash and the username from the data transfer object but am not able to see the email, firstName, lastName, or phoneNumber from the User class in the database. The photo below is an example of what happens when I register a new user. You can see that there are 4 columns without data.

When I'm adding a newUser I use a processRegistrationForm method that looks like this...

    @PostMapping("/register")
    public String processRegistrationForm(@ModelAttribute @Valid RegisterFormDTO registerFormDTO,
                                          Errors errors, HttpServletRequest request,
                                          Model model) {

        // a few conditionals that I removed for brevity

        User newUser = new User(registerFormDTO.getUsername(), registerFormDTO.getPassword(), registerFormDTO.getFirstName(), registerFormDTO.getLastName(), registerFormDTO.getEmail(), registerFormDTO.getPhoneNumber());
        userRepository.save(newUser);
        setUserInSession(request.getSession(), newUser);

        return "redirect:";
    }

the registerFromDTO

public class RegisterFormDTO extends LoginFormDTO{

    private String verifyPassword;


    private String firstName;

    private String lastName;

    private String email;

    private String phoneNumber;
//getters and setters.

the LoginFormDTO

public class LoginFormDTO {

    @NotNull
    @NotBlank
    @Size(min = 3, max = 20, message = "Invalid username. Must be between 3 and 30 characters.")
    private String username;

    @NotNull
    @NotBlank
    @Size(min = 5, max = 20, message = "Invalid password. Must be between 5 and 30 characters.")
    private String password;
//getters and setters

the User class..

@Entity
public class User extends AbstractEntity {

    @NotBlank
    private String username;

    @NotBlank
    private String pwHash;

    //@Column(name = "first_name")
    private String firstName;
    //@Column(name = "last_name")
    private String lastName;
    //@Column(name = "email")
    private String email;
    //@Column(name = "phone_number")
    private String phoneNumber;

    public User() {}

    private static final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    public User(String username, String password, String firstName, String lastName, String email, String phoneNumber){
        this.username =username;
        this.pwHash = encoder.encode(password);
        this.firstName =firstName;
        this.lastName = lastName;
        this.email = email;
        this.phoneNumber = phoneNumber;
    }

    public boolean isMatchingPassword(String password) {
        return encoder.matches(password, pwHash);
    }
//getters and setters

Last but not least here is my register form view

<form method="post">
    <div class="form-group">
        <label>Username
            <input class="form-control" th:field="${registerFormDTO.username}" />
        </label>
        <p class="error" th:errors="${registerFormDTO.username}"></p>
    </div>
    <div class="form-group">
        <label>Password
            <input class="form-control" th:field="${registerFormDTO.password}" type="password" />
        </label>
        <p class="error" th:errors="${registerFormDTO.password}"></p>
    </div>
    <div class="form-group">
        <label>Verify Password
            <input class="form-control" th:field="${registerFormDTO.verifyPassword}" type="password" />
        </label>
    </div>
    <div class="form-group">
        <label>First Name
            <input class="form-control" th:field="${registerFormDTO.firstName}" type="firstName" />
        </label>
    </div>
    <div class="form-group">
        <label>Last Name
            <input class="form-control" th:field="${registerFormDTO.lastName}" type="lastName" />
        </label>
    </div>

    <input type="submit" class="btn btn-primary" value="Register" />
</form>

回答1:


You can use MapStruct to map from DTO to the model.

For example:

    @Mapper
public interface EmployeeMapper {
    @Mappings({
      @Mapping(target="employeeId", source="entity.id"),
      @Mapping(target="employeeName", source="entity.name")
    })
    EmployeeDTO employeeToEmployeeDTO(Employee entity);
    @Mappings({
      @Mapping(target="id", source="dto.employeeId"),
      @Mapping(target="name", source="dto.employeeName")
    })
    Employee employeeDTOtoEmployee(EmployeeDTO dto);
}

"Quick Guide to MapStruct" has more information.




回答2:


The form needed to include a few things to persist the data collected in registerFormDTO. The first was: 1. In the form tag, add the th:action="@{/register}"and th:object="registerFormDTO" 2. In the input tags add type="text" to each input field and change where type="password", type="firstName" etc... to id="password" , and id="firstName" etc..

Doing these things allow Thymeleaf to wire up and persist the data that is collected.

Here is the full code.

<form th:action="@{/register}" th:object="${registerFormDTO}" method="post">
    <div class="form-group">
        <label>Username
            <input class="form-control" type="text" th:field="${registerFormDTO.username}" id="username" />
        </label>
        <p class="error" th:errors="${registerFormDTO.username}"></p>
    </div>
    <div class="form-group">
        <label>Password
            <input class="form-control" type="text" th:field="${registerFormDTO.password}" id="password" />
        </label>
        <p class="error" th:errors="${registerFormDTO.password}"></p>
    </div>
    <div class="form-group">
        <label>Verify Password
            <input class="form-control" type="text" th:field="${registerFormDTO.verifyPassword}" id="password" />
        </label>
    </div>
    <div class="form-group">
        <label>First Name
            <input class="form-control" type="text" th:field="${registerFormDTO.firstName}" id="firstName" />
        </label>
    </div>
    <div class="form-group">
        <label>Last Name
            <input class="form-control" type="text" th:field="${registerFormDTO.lastName}" id="lastName" />
        </label>
    </div>
    <div class="form-group">
        <label>Email
            <input class="form-control" type="text" th:field="${registerFormDTO.email}" id="email" />
        </label>
    </div>
    <div class="form-group">
        <label>Phone Number
            <input class="form-control" type="text" th:field="${registerFormDTO.phoneNumber}" id="phoneNumber" />
        </label>
    </div>

    <input type="submit" class="btn btn-primary" value="Register" />
</form>


来源:https://stackoverflow.com/questions/61965394/how-to-persist-data-from-the-entity-class-and-combined-with-data-transfer-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!