我想存储birthdate
所以我在MySQL选择date
,当我在我的数据库中创建实体时,结果如下:
import java.util.Date;
// ..code
@NotNull(message="fill you birthdate")
@Temporal(TemporalType.DATE)
private Date birthdate;
但是当我试图坚持它时,它给了我这个错误:
在回调事件上执行自动Bean验证时违反了Bean验证约束:'prePersist'。有关详细信息,请参阅嵌入式ConstraintViolations。
我在这里做错了什么? 我正在阅读有关谷歌定义时区的内容,我来自巴西,我应该怎么做?
修改
package entity;
import java.io.Serializable;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import java.util.Date;
import java.util.List;
/**
* The persistent class for the user database table.
*
*/
@Entity
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@Temporal(TemporalType.DATE)
private Date birthdate;
@NotNull(message="informe seu e-mail")
@Email(message="e-mail inválido")
private String email;
@NotNull(message="informe seu gênero")
private String gender;
private String image;
@NotNull(message="informe seu nome completo")
private String name;
@Size(min=6,max=16, message="senha com no mínimo: 6 dígitos e no máximo 16 dígitos")
@NotNull(message="informe sua senha")
private String password;
//bi-directional many-to-one association to Document
@OneToMany(mappedBy="user")
private List<Document> documents;
//bi-directional many-to-one association to QuestionQuery
@OneToMany(mappedBy="user")
private List<QuestionQuery> questionQueries;
//bi-directional many-to-one association to Team
@OneToMany(mappedBy="user")
private List<Team> teams;
public User() {
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getBirthdate() {
return this.birthdate;
}
public void setBirthdate(Date birthdate) {
this.birthdate = birthdate;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getImage() {
return this.image;
}
public void setImage(String image) {
this.image = image;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Document> getDocuments() {
return this.documents;
}
public void setDocuments(List<Document> documents) {
this.documents = documents;
}
public List<QuestionQuery> getQuestionQueries() {
return this.questionQueries;
}
public void setQuestionQueries(List<QuestionQuery> questionQueries) {
this.questionQueries = questionQueries;
}
public List<Team> getTeams() {
return this.teams;
}
public void setTeams(List<Team> teams) {
this.teams = teams;
}
public void print() {
System.out.println("User [id=" + id + ", birthdate=" + birthdate + ", email="
+ email + ", gender=" + gender + ", image=" + image + ", name="
+ name + ", password=" + password + "]");
}
}
答案 0 :(得分:30)
我遇到了同样的问题,但是经过几个小时的寻找答案,最后我发现了......你应该编辑 AbstractFacade.java 类并添加这个代码
public void create(T entity) {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<T>> constraintViolations = validator.validate(entity);
if(constraintViolations.size() > 0){
Iterator<ConstraintViolation<T>> iterator = constraintViolations.iterator();
while(iterator.hasNext()){
ConstraintViolation<T> cv = iterator.next();
System.err.println(cv.getRootBeanClass().getName()+"."+cv.getPropertyPath() + " " +cv.getMessage());
JsfUtil.addErrorMessage(cv.getRootBeanClass().getSimpleName()+"."+cv.getPropertyPath() + " " +cv.getMessage());
}
}else{
getEntityManager().persist(entity);
}
}
现在,此方法将提醒您哪个属性及其验证失败的原因。 我希望这对你有用,就像对我一样。
答案 1 :(得分:13)
我有一个快捷方式,在您持久保存实体时捕获以下异常。就我而言,它在EJB add方法中。我在做什么em.persist()
。然后检查服务器日志,您将看到哪个属性具有约束违规。
catch (ConstraintViolationException e) {
log.log(Level.SEVERE,"Exception: ");
e.getConstraintViolations().forEach(err->log.log(Level.SEVERE,err.toString()));
}
答案 2 :(得分:5)
错误显示您尝试保留的实体失败 数据库约束,因此在实际插入之前,请尝试确定要插入数据库的确切值。
并通过评论/省略@NotNull
注释来试用。
答案 3 :(得分:5)
我为解决问题所做的是颠倒订单@Size
和@NotNull
之前:
@Size(min=6,max=16, message="senha com no mínimo: 6 dígitos e no máximo 16 dígitos")
@NotNull(message="informe sua senha")
private String password;
后:
@NotNull(message="informe sua senha")
@Size(min=6,max=16, message="senha com no mínimo: 6 dígitos e no máximo 16 dígitos")
private String password;
我不知道为什么这个命令这么重要,但它确实=] 谢谢大家!
答案 4 :(得分:4)
当然,Iomanip的答案是完全正确的!我刚刚扩展了一点。也许这也有帮助:
private boolean constraintValidationsDetected(T entity) {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<T>> constraintViolations = validator.validate(entity);
if (constraintViolations.size() > 0) {
Iterator<ConstraintViolation<T>> iterator = constraintViolations.iterator();
while (iterator.hasNext()) {
ConstraintViolation<T> cv = iterator.next();
System.err.println(cv.getRootBeanClass().getName() + "." + cv.getPropertyPath() + " " + cv.getMessage());
JsfUtil.addErrorMessage(cv.getRootBeanClass().getSimpleName() + "." + cv.getPropertyPath() + " " + cv.getMessage());
}
return true;
}
else {
return false;
}
}
public void create(T entity) {
if (!constraintValidationsDetected(entity)) {
getEntityManager().persist(entity);
}
}
public T edit(T entity) {
if (!constraintValidationsDetected(entity)) {
return getEntityManager().merge(entity);
}
else {
return entity;
}
}
public void remove(T entity) {
if (!constraintValidationsDetected(entity)) {
getEntityManager().remove(getEntityManager().merge(entity));
}
}
答案 5 :(得分:2)
我有类似的问题。在我的例子中,引用的PK和FK的大小不同(参见示例)。
实体A:
some_pk INTEGER NOT NULL,
fk_b VARCHAR2(5 CHAR)
...
fk_b引用了实体B的ID字段
实体B:
id VARCHAR2(4 CHAR)
...
id在这里是PK。
请注意ID( 4 )和FK_B( 5 )的大小。将B的ID更改为 5 CHAR 后,错误消失了。
答案 6 :(得分:1)
当我试图坚持一个实体时,我花了几个小时来解决这个错误。
Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'preUpdate'. Please refer to embedded ConstraintViolations for details.
此错误消息无效,令人困惑......
无论如何,在我的情况下,错误的原因是 - Enity中的注释
之间的差异@Size(min = 1, max = 10)
@Column(name = Utilizator.JPA_DISCRIMINATOR)
private String jpaDiscriminator;
DataBase列定义:
jpaDiscriminator
VARCHAR(15)NOT NULL,