P
P
P_Alexander2020-05-02 17:46:03
Java
P_Alexander, 2020-05-02 17:46:03

When updating an entity, an error occurs javax.validation.ConstraintViolationException: Validation failed, why?

Good afternoon.
When updating an entity, an error occurs that the field did not pass validation, although it is not null !!! how is it and why?
The problem with this repeatPassword field is that since this field is not saved in the database, but the check is for NOTNULL , it should not be null, below I made a stub for it, I just inserted the left line there so that it would not be null. But when saving, it throws an error for a reason unknown to me, help me figure it out ...
Entity class

@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;


update table
@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);
   }
}


The update method
@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);
        }
    }


The whole STACK didn’t fit in, so I threw off the juice itself, if I need it, I’ll fill it in the comments ...
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

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question