Hibernate创建OneToMany而不是OneToOne



我不明白为什么这段代码创建OneToMany而不是OneToOne 有人能说出我哪里犯了错误吗? 我有2节课:

@Entity
@Table(name = "user")
public class User {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique=true)
@Id
private String login;
private String password;
private String firstName;
private String lastName;
private String city;
private int age;
private Sex sex ;
@OneToOne(fetch = FetchType.LAZY, mappedBy = "user", cascade = CascadeType.ALL)
//@JoinColumn(name= "user_details")
private UserProfile userProfile;

二等舱:

@Entity
@Table(name = "user_profile")
public class UserProfile {
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long Id;
@Id
private String user_login;
private String user_interestings;
@OneToOne//mappedBy= "userProfile")
@MapsId
private User user;

这是图像,它如何在MySQLWOrkbench中结束 在此处输入图像描述

感谢您的帮助。

@JoinColumnUserProfile中的外键一起使用作为数据库设计

public class UserProfile {
...
@OneToOne
@JoinColumn(name = "user_login")
private User user;
}

和你的主键两个表混淆。如果您需要两个表使用相同的主键,则以这种方式映射。这里两个表的主键都是id。您不需要user_loginUserProfile表中。

public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
...
@OneToOne(fetch = FetchType.LAZY, mappedBy = "user", cascade = CascadeType.ALL)
private UserProfile userProfile;
}
public class UserProfile {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long Id;
...
@OneToOne
@MapsId
private User user;
}

最新更新