I have one-to-one mapping JPA table in my springboot application which works fine.
The Users
is the parent table and in the account_no
column, it stores the foreign key. Which is, child's primary key. The child is Account
table.
However, when the application is started, I can see that there is one additional column (user_id
) that has been created in H2 DB. I think it is something wrong with my JPA mapping. Pls help to figure it out. Below are the two classes.
@Entity
public class User extends AbstractEntity {
// Other fields related to user entity go here ..
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "account_no", referencedColumnName = "account_num")
private Account account;
}
@Entity
public class Account extends AbstractEntity{
// fields like account#, balance etc goes here..
@Column(name="account_num", unique = true)
@NotNull
private long accountNo;
@OneToOne (fetch = FetchType.LAZY)
private User user;
}
Startup log.
create table account (id bigint not null, account_num bigint not null, bal float not null, user_id bigint, primary key (id))
2021-12-22 00:09:28.765 DEBUG 25380 --- [ main] org.hibernate.SQL :
CodePudding user response:
Decide which side should contain the extra column and use the mappedBy
attribute. Then JPA will do what's needed
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false, mappedBy = "user")
private Account account;
Considering that you have bidirectional mapping you don't need the @JoinColumn
that you have used.
Just both @OneToOne
annotations and the decision which would be owner entity of the relation by using the mappedBy attribute on one of those annotations.
CodePudding user response:
It depends on you in which side you store the extra column which was a foreign key.Because When You started to established oneToOne relationship between two table it is mandatory to store user's primary key in account table as a foreign key, or account table primary key in user table as foreign key.You should be need to declare mappedBy and your tables reference name.for example if you declare mappedBy="user" in account table it create an extra account_id column in user table as a foreign key, Same as for account
@OneToOne(optional = false, mappedBy = "user")
private Account account;
Don't need to declare these things in side OneToOne annotation cascade = CascadeType.ALL, fetch = FetchType.LAZY, By default it always support lazy fetch
.