我是JPA /休眠的新手, 我正在创建一个简单的联接以在不同的表中获取一些数据 让我们这样看:
目的是基于M_USER.username列获取M_PROFILE数据,但是很明显,您看到M_PROFILE表中没有外键。
我只是尝试使用下面的代码,但没有结果,总是出现错误。
用户实体类
@Entity
@Table(name = "M_USER")
public class User {
@Id
@Column(name = "id")
private String uuid;
@Column(name = "email")
private String email;
@Column(name = "username")
private String username;
@OneToOne(fetch = FetchType.LAZY)
@MapsId("username")
private Profile profile;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Profile getProfile() {
return profile;
}
public void setProfile(Profile profile) {
this.profile = profile;
}
}
配置文件实体类
@Entity
@Table(name = "M_PROFILE")
public class Profile {
private String username;
private String phone;
private String address;
@Id
@Column(name = "username", nullable = false)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Basic
@Column(name = "phone")
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Basic
@Column(name = "address")
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
致电
时出现不同的错误User user = userRepository.findByUsername("aswzen");
String phone = user.getProfile().getPhone();
例如这个。
“ USER0 _”。“ PROFILE_USERNAME”:无效的标识符
需要帮助,在此先感谢
注意:我没有更改表的权限。
答案 0 :(得分:1)
尝试指定联接列:
@OneToOne
@JoinColumn(name = "username", referencedColumnName = "username")
private profile profile;
您在这里并不需要@MapsId
。
答案 1 :(得分:1)
我建议创建具有表关系的第三张表
@Entity
@Table(name = "M_USER")
public class User {
@OneToOne(fetch = FetchType.LAZY)
@JoinTable(
name = "user_profile",
joinColumns = @JoinColumn(name="user_id"),
inverseJoinColumns = @JoinColumn(name="profile_username")
)
private Profile profile;
UPDATE user_profile
SET user_id = (
SELECT id
FROM M_USER
);
UPDATE user_profile
SET profile_username = (
SELECT username
FROM M_USER
);