Nowak Adam
Nowak Adam

Reputation: 31

Hibernate Create OneToMany instead of OneToOne

I don't understand why this code create OneToMany instead of OneToOne Can somebody tell where i made mistake. I have got 2 class:

@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;

Second class:

@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;

Here is image, how it end in MySQLWOrkbench enter image description here

Thanks for help.

Upvotes: 2

Views: 234

Answers (1)

Eklavya
Eklavya

Reputation: 18480

Use @JoinColumn with the foreign key in UserProfile as your Database design

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

And your primary key for both table confusing. If you need both table use same primary key then map this way. Here both table primary key is id. You don't need user_login column then in UserProfile table.

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;
}

Upvotes: 1

Related Questions