简体   繁体   中英

JPA - Assign different unique constrains for two subclass of a SINGLE_TABLE hierarchy abstract class

I have 3 classes that are:

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
public abstract class Tag {
    @Id
    private String id;
    private String name;
}

@Entity
@Table(uniqueConstraints=
        @UniqueConstraint(columnNames={"name"}))
public class SystemTag extends Tag {

}

@Entity
@Table(uniqueConstraints=
        @UniqueConstraint(columnNames = {"name", "user"}))
public class CustomTag extends Tag{
    @ManyToOne
    private User user;
}

so I want to use unique name for system tags, and unique name-user pair for custom tags (multiple users can create same tags) But I get two warnings as below:

<timestamp> WARN  AnnotationBinder:601 - HHH000139: Illegal use of @Table in a subclass of a SINGLE_TABLE hierarchy: <domain>.CustomTag
<timestamp> WARN  AnnotationBinder:601 - HHH000139: Illegal use of @Table in a subclass of a SINGLE_TABLE hierarchy: <domain>.SystemTag

And it allows me to create two system tags with same name and two custom tags with same name for same user.

How can I handle this?

If you are using a single table that is obviously not going to work.

Switch to using JOINED strategy

@Entity
@Inheritance(strategy=InheritanceType.JOINED)
public abstract class Tag {
    @Id
    private String id;
    private String name;
}

and you will then have a table for CustomTag and table for SystemTag with unique constraints as expected.

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