4

我想注册一个使用 Spring MVC 3、Hibernate 和 PostgresQL 的用户。这是我要提交的表格:

<form:form name="registerForm" method="post"
        action="registerNewUser.html" commandName="user">

        <table>

            <tr>
                <td><spring:message code="label.userName" /></td>
                <td><form:input path="userName" /></td>
                <td><form:errors path="userName" cssClass="error" /></td>
            </tr>

            <tr>
                <td><spring:message code="label.password" /></td>
                <td><form:password path="password" /></td>
                <td><form:errors path="password" cssClass="error" /></td>
            </tr>


            <tr>
                <td><spring:message code="label.password" /></td>
                <td><form:password path="retypePassword" /></td>
                <td><form:errors path="retypePassword" cssClass="error" /></td>
            </tr>

            <tr>
                <td colspan="2"><input type="submit"
                    value="<spring:message code="register.label" />" /></td>
            </tr>
        </table>

    </form:form>

这是我要保存的 POJO:

@Entity
@Table(name = "user_table")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "user_name", nullable = false, length = 50)
    private String userName;

    @Column(name = "password", nullable = false, length = 50)
    private String password;

    private String retypePassword;
        // getters setters

这是控制器的相关部分:

@RequestMapping(value = "/registerNewUser", method = RequestMethod.POST)
public String saveNewUser(@ModelAttribute User user, BindingResult result, Model model, HttpSession session) {

    UserValidator validator = new UserValidator();
    validator.validateUser(user, result, userService.existingUser(user));
    String ret = REGISTER_USER;
    if (!result.hasErrors()) {
        user.setPassword(PasswordEncripter.md5(user.getPassword()));
        userService.save(user);
        ret = goToPractice(user, model, session);
    }
    return ret;
}

因为我觉得将 retypePassword 的值存储在数据库中很浪费,所以我没有为此创建列。当我提交表单时,这导致了以下异常:

org.postgresql.util.PSQLException: ERROR: column user0_.retypepassword does not exist

我可以通过将“retypePassword”列添加到表中来轻松修复此异常,但我仍然觉得这会很浪费。有没有什么聪明的方法可以解决问题而不在数据库中添加重复数据?

4

1 回答 1

13

您可以在实体中使用 标记 retypePassword @Transient,这将指示 hibernate 不要在表中创建列,但您仍然可以使用此 pojo 与 spring mvc 绑定以进行验证。

@Entity
@Table(name = "user_table")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "user_name", nullable = false, length = 50)
    private String userName;

    @Column(name = "password", nullable = false, length = 50)
    private String password;

    @Transient
    private String retypePassword;
        // getters setters
于 2012-10-04T07:49:28.433 回答