Issue
I am new to JPA/Hibernate, I am creating a simple join for getting some data in different table Let's see like this:
src="https://i.stack.imgur.com/vVJ1b.png" alt="enter image description here">
The purpose is getting the M_PROFILE data based on M_USER.username column, but clearly you see that there is no foreign key in M_PROFILE table.
I just try to use below code but have no results and always got error.
User Entity Class
@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;
}
}
Profile Entity Class
@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;
}
}
I got different error when calling
User user = userRepository.findByUsername("aswzen");
String phone = user.getProfile().getPhone();
for example this one.
"USER0_"."PROFILE_USERNAME": invalid identifier
Need help, thanks in advance,
NB : i don't have privilege to alter the table..
Solution
Try to specify a join column:
@OneToOne
@JoinColumn(name = "username", referencedColumnName = "username")
private profile profile;
You do not really need the @MapsId
here.
Answered By - Maciej Kowalski
Answer Checked By - Willingham (JavaFixing Volunteer)