gpt4 book ai didi

java - hibernate JPA IdentifierGenerationException : null id generated for class with @embeddedid

转载 作者:搜寻专家 更新时间:2023-10-31 19:54:58 29 4
gpt4 key购买 nike

在一种情况下,我无法将我的数据库域模型映射到程序实体,其中该实体本质上是一个连接表(一个句点),它结合了另外两个实体(一个时间段和一天)。另一个实体(一节课)然后引用这个周期实体,确定它何时发生。

当我尝试使用 saveOrUpdate(lesson) 保存新周期的类(class)时,hibernate 抛出 IdentifierGenerationException

org.hibernate.id.IdentifierGenerationException: null id generated for:class com.trials.domain.Period

数据库如下所示(不是真正的数据库,只是关键表和列)

enter image description here

在 java hibernate 模型中,我使用了一个嵌入式 id 作为周期类的主键,然后类(class)类引用了一个周期。

Period.java

@Entity
@Table(name = "period")
public class Period{
@EmbeddedId
private PeriodId periodId;

@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;

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

嵌入的 id 只有主键列:

PeriodId.java

@Embeddable
public class PeriodId implements Serializable {
@Column(name = "timeslot_idtimeslot")
private int timeslotId;

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

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

然后是使用定义为期间的类(class)类:

类(class).java

@Entity
@Table(name = "lesson")
public class Lesson {
@Id
@Column(name = "idlesson")
private int lessonId;

@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumns({@JoinColumn(name = "period_timeslot_idtimeslot", nullable = false, updatable = false), @JoinColumn(name = "period_day_idday", nullable = false, updatable = false)})
private Period period;
//constructors, getters, setters, hashcode, and equals
}

Timeslot 和 Day 实体类都是非常基本的 pojo,它们的 id 使用 GenerationType.AUTO。所以我的问题是:

  1. 是什么导致了这个 IdentifierGenerationException
  2. 如何在保持相同数据库模型的同时避免它

提前致谢

最佳答案

放那些家伙

@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;

在 PeriodId 类中并丢弃那些整数。我已经通过这种方式完成了与您的映射类似的映射并且它有效。

关于java - hibernate JPA IdentifierGenerationException : null id generated for class with @embeddedid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25295054/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com