gpt4 book ai didi

java - 外键 Hibernate 注释

转载 作者:行者123 更新时间:2023-11-30 06:45:01 28 4
gpt4 key购买 nike

我无法使这个简单的外键约束起作用。

@Entity
@Table(name = "wheel")
@Data
public class WheelEntity {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
...

@Entity
@Table(name = "bike")
@Data
public class BikeEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

@ManyToOne(targetEntity = WheelEntity.class, fetch=FetchType.EAGER, cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
@JoinColumn(name = "wheel_1_id", referencedColumnName = "id")
@NotNull
private Integer wheel_1_id;

@ManyToOne(targetEntity = WheelEntity.class, fetch=FetchType.EAGER, cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
@JoinColumn(name = "wheel_2_id", referencedColumnName = "id")
@NotNull
private Integer wheel_2_id;
...

当我想插入一辆新自行车时,以下是持久保存 BikeEntity 时遇到的错误:

Caused by: java.lang.IllegalArgumentException: Can not set java.lang.Integer field com.xxx.xxx.xxx.storage.WheelEntity.id to java.lang.Integer
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)
at java.lang.reflect.Field.get(Field.java:393)
at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:39)

无法将 java.lang.Integer 设置为 java.lang.Integer。嗯嗯嗯?奇怪!

非常感谢您的帮助

最佳答案

在 Hibernate 中,您可以通过在 Entity2 中引用 Entity1 来创建关系。正确的做法是:

@Entity
@Table(name = "wheel")
@Data
public class WheelEntity {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
...

@Entity
@Table(name = "bike")
@Data
public class BikeEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

@ManyToOne(targetEntity = WheelEntity.class, fetch=FetchType.EAGER, cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
@JoinColumn(name = "wheel_1_id", referencedColumnName = "id")
@NotNull
private WheelEntity wheelEntity;

关于java - 外键 Hibernate 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43820563/

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