使用Hibernate Validators保存实体

时间:2018-07-26 18:59:44

标签: spring hibernate spring-boot

我的休眠验证器有问题。

我有用户实体

@Entity
public class User extends AbstractJpaEntityImpl {

    public static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder();

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @NotNull
    private String username;

    @NotNull
    @Email
    @Valid
    @NotEmpty
    private String email;

    @NotNull
    private String password;

    @ElementCollection
    @Size(min=1)
    private List<String> roles;

    public User() {}

    public User(String username, String email, String password, List<String> roles) {
        super();
        this.username = username;
        this.email = email;
        this.password = PASSWORD_ENCODER.encode(password);
        this.roles = roles;
    }
}

电子邮件列已用@ NotNull,@ Email,@ Valid和@NotEmpty注释,当尝试保存一个空或空电子邮件休眠用户的尝试不会失败时。

@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
public class UserTest {

    @Autowired private UserRepository userRepository;

    @Test
    public void notNull() {
        Objects.requireNonNull(this.userRepository);
    }

    @Test
    public void save() {
        User user = this.userRepository.save(new User("david",null,"prueba",Arrays.asList("ROLE_ADMIN")));

        Objects.requireNonNull(user);
    }

}

Hibernate Pom依赖项是

<!-- org.hibernate -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-java8</artifactId>
</dependency>
<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-validator</artifactId>
</dependency>

非常感谢您=)。

0 个答案:

没有答案