简体   繁体   中英

Many-to-many relationship JPA - unique constraint

I have 2 entities, Event and Tag, in a many-to-many relationship. Tags should have unique names, so I placed a constraint on it.

It works like expected for unique tag names, I save a batch of new events and entries are automatically inserted in the tag and join tables.

But the moment I try to save an event that has a tag with a duplicate name, an error is thrown due to it violating the constraint.

Is there a way around this that does not involve having to check and insert all the events/tags manually?

Code below:

Event entity:

@Entity
@Table(name = "event")
class Event {

    @Id long id;
    
    @ManyToMany(cascade = { CascadeType.ALL })
    @JoinTable(name = "event_tag",
            joinColumns = @JoinColumn(name = "event_id"),
            inverseJoinColumns = @JoinColumn(name = "tag_id"))
    private Set<Tag> tags;

    // other properties
}

Tag entity:

@Entity
@Table(name = "tag", uniqueConstraints = @UniqueConstraint(columnNames = "name"))
public class Tag {

    @Id long id;

    @Column(name = "name", unique = true)
    private String name;
    
    @ManyToMany(mappedBy = "tags", cascade = { CascadeType.ALL })
    private Set<Event> events;
}

I'm using JpaRepository 's method saveAll to persist the events. It throws:

java.sql.SQLException: Duplicate entry 'xxxxx' for key 'uq_tag_name'
at org.mariadb.jdbc.internal.protocol.AbstractQueryProtocol.readErrorPacket(AbstractQueryProtocol.java:1694) ~[mariadb-java-client-2.7.3.jar:na]

I have seen a few similar questions but have yet to find a working answer for this.

这是因为 { CascadeType.ALL } 当您设置 CascadeType.ALL 时,休眠会更改标签表,如果需要,请插入标签的数据。您应该删除 CascadeType.ALL,如果您得到(无法插入瞬态对象)应该使用flush for处理那个

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