我不明白为什么这段代码会创建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中的结尾enter image description here
感谢您的帮助。
将@JoinColumn
与UserProfile
中的外键一起用作数据库设计
public class UserProfile {
...
@OneToOne
@JoinColumn(name = "user_login")
private User user;
}
并且您的主键对两个表都造成混淆。如果您需要两个表都使用相同的主键,则可以使用这种方式进行映射。这两个表的主键均为id
。您不需要user_login
表中的UserProfile
列。
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;
}