删除继承的类JPA

时间:2015-11-09 07:53:14

标签: java mysql hibernate jpa inheritance

我有一个表定义如下:

@Entity
@Inheritance(strategy=InheritanceType.JOINED)
@DiscriminatorColumn(name = "EVENT_TYPE")
public abstract class Event implements Serializable {
    @Id
    @GeneratedValue
    private Long id;
...
}

然后我有这个继承的表:

@Entity
@DiscriminatorValue("BOOLEANVALUE")
public class BooleanValueEvent extends Event {
    ...
}

@Entity
@DiscriminatorValue("EXACTVALUE")
public class ExactValueEvent extends Event {
    ...
}

Hibernate在数据库中创建了两个表,但是当我尝试在JPA上删除一个继承的对象时,它返回外键约束违规错误,因为它试图删除第一个Event类。当我删除superClass以避免键约束违规错误时,如何首先删除继承的类?

谢谢。

2 个答案:

答案 0 :(得分:1)

使用级联删除,删除SubTable实体将成功,它将删除subTable和parentTable行。

@Entity
@DiscriminatorValue("BOOLEANVALUE")
@OnDelete(action = OnDeleteAction.CASCADE)
public class BooleanValueEvent extends Event {
    ...
}

@Entity
@DiscriminatorValue("EXACTVALUE")
@OnDelete(action = OnDeleteAction.CASCADE)
public class ExactValueEvent extends Event {
    ...
}

答案 1 :(得分:0)

最后我解决了它。

@JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME,
        include = JsonTypeInfo.As.PROPERTY,
        property = "typeName")
@JsonSubTypes({
        @Type(value = BooleanValueEvent.class),
        @Type(value = ExactValueEvent.class)
})
@Entity
@Inheritance(strategy=InheritanceType.JOINED)
@DiscriminatorColumn(name = "EVENT_TYPE")
public abstract class Event implements Cloneable, Serializable {
    @Id
    @GeneratedValue
    private Long id;
...
}

@Entity
@DiscriminatorValue("BOOLEANVALUE")
public class BooleanValueEvent extends Event {
    ...
}

@Entity
@DiscriminatorValue("EXACTVALUE")
public class ExactValueEvent extends Event {
    ...
}