Добрый день.
При обновлении сущности, выпадает ошибка что поле не прошло валидацию, хотя оно не нулевое!!! как это и почему!?
Проблема с этим полем repeatPassword - так как это поле не сохраняется в базе но проверка стоит на НОТНУЛЛ , оно должно быть не нулевое, ниже я сделал для него заглушку, просто вставил туда левую строку что бы нулл небыло. Но при сохранении бросает ошибку по не известной мне причине, помогите разобраться...
Класс сущности
@Entity
@Table(name = "customer", schema = "dev_schema", uniqueConstraints = {@UniqueConstraint(columnNames = "customerId")})
public class Customer implements Serializable {
@Id
@SequenceGenerator(name = "cust_idcust_seq", schema = "test_schema", sequenceName = "cust_idcust_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "cust_idcust_seq")
@Column(name = "customerId")
private Integer id;
@NotNull
@Size(min = 3, max = 30, message = "{customer.name.Size}")
@Column(name = "name", nullable = false)
private String name;
@NotNull
@Size(min = 3, max = 30, message = "{customer.patronymic.Size}")
@Column(name = "patronymic", nullable = false)
private String patronymic;
@NotNull
@Size(min = 3, max = 30, message = "{customer.lastName.Size}")
@Column(name = "lastName", nullable = false)
private String lastName;
@NotNull
@Column(name = "age", nullable = false)
private Integer age;
@NotNull
@DateTimeFormat(pattern = "yyyy-MM-dd")
@Column(name = "birthData", nullable = false)
private LocalDate birthDate;
@NotNull
@Email
@Column(name = "email", nullable = false, unique = true)
private String email;
@NotNull
@Size(min = 5, max = 30, message = "{customer.login.Size}")
@Column(name = "login", nullable = false, unique = true)
private String login;
@NotNull
@Size(min = 8, max = 256, message = "{customer.password.Size}")
@Column(name = "password", nullable = false)
private String password;
@NotNull
@Size(min = 8, max = 256, message = "{customer.repeatPassword.Size}")
@Transient
private String repeatPassword;
@Column(name = "status", nullable = false)
private boolean statusAccount = true;
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
@JoinColumn(name = "role", nullable = false)
private Role role;
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "passport")
private Passport passport;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "address")
private Address address;
обновляю таблицу
@Controller(value = "ControlController")
public class ControlController {
@RequestMapping(value = "/control", method = RequestMethod.POST)
@ResponseBody
public CustomerTransferModel blockCustomer (@RequestBody CustomerTransferModel ctm) {
blockUser(ctm);
return customerTransferModel;
}
private Customer blockUser(CustomerTransferModel ctm) {
Customer customer = customerService.findByLogin(ctm.getLogin()); //так как поля repeatPassword в базе нет, тут вернет нулл
customer.setStatusAccount(!ctm.isStatusAccount());
customer.setRepeatPassword("qweasdzxcrtyDSAv231xzX"); // вот тут сделана заглушка...
customerService.update(customer);
}
}
Сам метод обновления
@Override
public void update(Customer entity) {
Customer customer = findById(entity.getId());
if(customer.getId() == null) {
getEntityManager().persist(entity);
logger.debug(" update : - " + entity);
} else {
logger.debug(entity.getRepeatPassword() + " update merge : - " + entity); // ВОТ ТУТ ПОЛЕ repeatPassword NOT NULL тогда почему падает ошибка???
getEntityManager().merge(entity);
}
}
СТЕК весь не влез, поэтому самый сок скинул, если нужен то залью в коммент весь...
Caused by: javax.persistence.RollbackException: Error while committing the transaction
at org.hibernate.internal.ExceptionConverterImpl.convertCommitException(ExceptionConverterImpl.java:75)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:71)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:536)
... 107 more
Caused by: javax.validation.ConstraintViolationException: Validation failed for classes [com.InternationalPassport.businessLayer.model.Customer] during update time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='должно быть задано', propertyPath=repeatPassword, rootBeanClass=class com.InternationalPassport.businessLayer.model.Customer, messageTemplate='{javax.validation.constraints.NotNull.message}'}
]
at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:140)
at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.onPreUpdate(BeanValidationEventListener.java:88)
at org.hibernate.action.internal.EntityUpdateAction.preUpdate(EntityUpdateAction.java:244)
at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:118)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:589)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1435)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:491)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3201)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2411)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:467)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:146)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:220)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
... 108 more