简体   繁体   中英

JPA/Hibernate ManyToMany not nullable contstraint

I have a parent entity that has a Many-to-Many relation with its children. However I have a constraint that a Parent must at least have 1 Child. How can we describe this with JPA/Hibernate annotations?

@Entity
public class Parent {
    //parent must have at least 1 Child
    @ManyToMany
    private Set<Child> children    
}

At the moment I'm thinking of just using interceptors as follows:

@PrePersist
@PreUpdate
private validate() {
    if(children.size() < 1) 
      throw new PersistenceException()
}

Or possibly handle this at service layer.

Try using the Hibernate Validator, that uses JSR 303 and is interpreted as database validation also. Therefore you can use the @NotEmpty annotation for validation like this:

 @ManyToMany
 @NotEmpty
    private Set<Child> children    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM