【发布时间】:2021-01-05 10:17:37
【问题描述】:
我有 3 个实体 - 课程、模块、时间线 在时间线实体中 - 我想提供 2 个键作为主键,即复合键。我该怎么给。请告诉我在下面的代码中要进行的更改:
课程:
@Id
@Column(name = "id")
Integer courseId;
@Column(name = "course_name")
String course_name;
模块:
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "module_id")
Integer module_id;
@Column(name = "module_type")
String module_type;
@Column(name = "module_name")
String module_name;
@Column(name = "duration")
Integer duration;
@OneToOne( cascade = CascadeType.ALL)
private Course course;
时间线:
@Id
@Column(name = "timeline_id")
Integer timeline_id;
@ManyToOne( cascade=CascadeType.ALL )
private Module module;
@ManyToOne( cascade = CascadeType.ALL)
private Course course;
现在在时间轴中,我希望将 course_id 和 timeline_id 作为主键。请帮忙。 提前谢谢你。
更新: 我尝试使用 Embeddable 和 EmbeddedId:
@Embeddable
public class TimelineId implements Serializable{
private Integer course_id;
private Integer timelineId;
getters and setters
hashcode and equals
}
模块:
@Entity
@Table (name = "timeline")
public class Timeline {
@EmbeddedId
private TimelineId timelinepk;
@ManyToOne( cascade=CascadeType.ALL )
private Module module;
@ManyToOne( cascade = CascadeType.ALL)
private Course course;
}
但这给出了一个错误:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: com.scb.axess.playbook.model.Timeline
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1762) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
【问题讨论】:
-
我会建议你不要使用复合主键,与简单的合成主键相比,它会让以后的事情变得更加困难。在某些情况下复合键是合理的,但在我看来,这种情况不在其中。 BR
-
您的
timeline实体中是否需要timeline_id?所以:主键应该是(timeline_id, module, course)还是只是(module, course)? -
@ApoorvaOjha 看看休眠状态documentation。您可以在此处找到大量示例。
标签: spring-boot hibernate jpa spring-data-jpa