2


I have an hibernate entity which contains two dates: start and finish.

@Entity
public class MyEntity{ 

    private Date start
    private Date finish;
    ...
    @Temporal(TemporalType.DATE)
    @Column(name = "start", nullable = false)
    public Date getStart() {
        return start
    }

    @Temporal(TemporalType.DATE)
    @Column(name = "finish", nullable = false)
    public Date getFinish() {
        return finish;
    }
}

I would like to introduce a constraint that says start must be before finish,
can I do this kind of validation/check in the hibernate entities in order to avoid to write invalid data in my table?
If yes, how?
My guess is not, probably I have to write a trigger.. is it right? any better ideas?

2 Answers 2

2

You can use Hibernate Validator to add vlaidation for your entities. You need to introduce your own custom constraint.

Or you can do it manually in your DAO layer:

public class MyEntityDAO{ 

    ....

    protected void save(MyEntity entity) {
      // check dates
      // throw some exception in a case of problems
      getCurrentSession().saveOrUpdate(entity);
    }
}

As a downside this will not work if you save some parent entity and MyEntity entity will be saved by cascade.

An easier to do solution may be using @PrePersist:

@Entity
public class MyEntity{ 

    ....

    @PrePersist
    protected void checkDates() {
      // check dates
      // throw some runtime exception in a case of problems
    }
}

But I am not sure that in this case trnsaction will be rolled back by default.

Sign up to request clarification or add additional context in comments.

Comments

1

+1 to Maksym for @PrePersist suggestion, just taking the idea further.

You can also use @PrePersist with @EntityListeners to handle the entity validations:

public class MyEntityValidationEventListener {
   @PrePersist
   public void validate(Object entity) {....}
}

@Entity
@EntityListeners(MyEntityValidationEventListener.class)
public class MyEntity {...}

1 Comment

+1 thnaks for sharing. It will give you ability to separate your entity (POJO) and validation code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.