GenerationType.IDENTITY导致插入时反射异常

时间:2018-08-03 13:37:52

标签: hibernate jpa spring-data-jpa spring-data

我有两个表:Route和Stop。模式看起来像这样:

Route (routeId)

Stop (routeId, stopId)

停止是一个脆弱的实体,它使用routeId作为其PK的一部分。

现在,我尝试像这样建模:

@Entity
@IdClass(StopPK.class)
public class Stop {

    @Id
    @Column(name = "stopId")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private short stopId;

    @Id
    @Column(name = "routeId")
    private short routeId;

    @ManyToOne
    @JoinColumn(name = "routeId", insertable = false, updatable = false)
    private Route route;

    // Getters, Setters, No Args Constructor...

}

@Entity
public class Route {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "routeId")
    private short routeId;

    @OneToMany(mappedBy = "route", cascade = {CascadeType.PERSIST, CascadeType.MERGE}, orphanRemoval = true, fetch = FetchType.EAGER)
    private List<Stop> stops = new ArrayList<>();

    // Getters, Setters, No Args Constructor...

}

public class StopPK  implements Serializable {

    public short routeId;
    public short stopId;

    // Getters, Setters, No Args Constructor...
}

现在,当我尝试插入新的止损时,可以看到奇怪的行为。 使用GenerationType.IDENTITY我得到以下错误:

"Could not set field value [POST_INSERT_INDICATOR] value by reflection : [class caselight.tenant.entities.routes.StopPK.stopId] setter of caselight.tenant.entities.routes.StopPK.stopId"

但是对于GenerationType.AUTO(或未指定类型),我没有问题。

有什么原因吗?我使用Hibernate作为JPA,而MySQL是数据库。

如果没有特殊原因,是否有我不应该使用GenerationType.SEQUENCE或TABLE的原因?

插入的路由很好,所以问题不是GenerationType.IDENTITY固有的

干杯!

0 个答案:

没有答案