Hibernate JPA IdentifierGenerationException: null id generated for class with @embeddedid

匆匆过客 提交于 2019-12-05 09:32:32

Put those guys

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "day_idday", nullable = false, insertable = false, updatable = false)
private Day day;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "timeslot_idtimeslot", nullable = false, insertable = false, updatable = false)
private Timeslot timeslot;

inside the PeriodId class and throw away those ints. I have done a mapping similar to yours this way and it works.

I was able to create the following mapping for my case (scala code) and could totally throw away the @Embeddable class:

@Entity
@Table(name = "payment_order_item", schema = "pg")
@IdClass(classOf[PaymentOrderItem])
final class PaymentOrderItem extends Serializable{

  @Id
  @ManyToOne
  @JoinColumn(name = "order_item_id", referencedColumnName = "id")
  var orderItem: OrderItem = _

  @Id
  @ManyToOne
  @JoinColumn(name = "payment_id", referencedColumnName = "id")
  var payment: Payment = _
}

So the following should work for you then

@Entity
@Table(name = "period")
@IdClass(Period.class)
public class Period extends Serializable{

    @Id
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "day_idday", referencedColumnName = "id", nullable = false)
    private Day day;

    @Id
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "timeslot_idtimeslot", referencedColumnName = "id", nullable = false)
    private Timeslot timeslot;

    //constructors, getters, setters, hashcode, and equals
}

On a first glance, You're missing the generated value annotation in the embedded id class.

@Embeddable
public class PeriodId implements Serializable {

    @GeneratedValue
    @Column(name = "timeslot_idtimeslot")
    private int timeslotId;

    @GeneratedValue    
    @Column(name = "day_idday")
    private int dayId;

    //constructors, getters, setters, hashcode, and equals
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!