gpt4 book ai didi

java - @ManyToOne @OneToMany Mapping ,外键为空

转载 作者:行者123 更新时间:2023-12-01 16:31:00 25 4
gpt4 key购买 nike

@Entity
@Data
@NoArgsConstructor
public class Offer {
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "user_id", referencedColumnName = "id")
private User user;
}

@Data
@EqualsAndHashCode
@Entity
@NoArgsConstructor
public class User {
@OneToMany(mappedBy = "user",cascade = CascadeType.ALL,fetch=FetchType.LAZY)
private Set<Offer> offers = new HashSet<Offer>();
}

请帮忙看看表 User 和 Offer .user_id 列中的映射是否正确......:(

最佳答案

我不确定这些是否只是实体的一部分,但为了使实体拥有一个 ID,您需要为其提供一个 ID,并将相关字段注释为 @Id。我还使用 @GenerateValue(strategy = GenerationType.IDENTITY) 所以每个表都会获得它自己的 id (由 Hibernate 生成,当您保存新实体而不是全局 id 时不提供 id,否则假设您添加一个提供,您获得值为 x 的 id,然后添加新用户,您获得值为 x+1 的 id 等等...

@Entity
@Data
@NoArgsConstructor
public class Offer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "user_id", referencedColumnName = "id")
private User user;

}



@Data
@EqualsAndHashCode
@Entity
@NoArgsConstructor
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@OneToMany(mappedBy = "user",cascade = CascadeType.ALL,fetch=FetchType.LAZY)
private Set<Offer> offers = new HashSet<Offer>();
}`

关于java - @ManyToOne @OneToMany Mapping ,外键为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62044295/

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