Reputation: 55
I am new to Hibernate. I have a OneToMany
relationship with bidirectional mapping between Account and Transaction. I am not using @JoinColumn
in either class and using @mappedBy
in the non owning Account class. And everything is working fine. Using H2 in memory database, new join column is created in Transaction table. Then what is the use of @JoinColumn
in OneToMany
relationships? Is it for unidirectional mapping only? Below is the code. I also read for reference JPA JoinColumn vs mappedBy
public class Account {
@OneToMany( mappedBy="account", cascade=CascadeType.ALL)
List<Transaction> list= new ArrayList<Transaction>();
}
public class Transaction {
@ManyToOne
Account account;
}
Application class :
Account a = new Account("savings");
Transaction t1 = new Transaction("shoe purchase", 45);
t1.setAccount(a);
a.getList().add(t1);
accountRepository.save(a);
output:
Transaction table has an entry with foreign key which is account number in that one row in Account table. ACCOUNT_ID column in created in Transaction table.
There are no extra tables created.
Upvotes: 3
Views: 2531
Reputation: 185
MappedBy
intructs Hibernate that the key used for the association is on the other side of the association.Like in this case ACCOUNT_ID is being created on Account table.
That means that although you associate two tables together, only one table is having foreign key constraint to the other one.
MappedBy
lets you to still associate from the table not having foreign key constraint to the other table.
Upvotes: 0
Reputation: 8354
Jpa works on the idea of configuration by convention. So, it will perform configuration on your behalf whenever it can. Think of the @Column
annotation, you don't have to apply it on every entity attribute, you would need it only when you have to change something about the attributes.
It's the same with @JoinColumn
, when you added @ManyToOne
, Jpa already knows that you will need the join column and thus was added for you and the default naming convention for the foreign key was applied (attributename_primarykeyoftheothertype
).
Upvotes: 1
Reputation: 350
Use of
mappedBy
is instruct framework to enable bi-directional relationship. Because of @ManyToOne on Transaction class you Your Transaction Table will have foreign key referring to Account table primary key. By default, Hibernate generates the name of the foreign key column based on the name of the relationship mapping attribute and the name of the primary key attribute. In this example, Hibernate would use a column with the name account_id to store the foreign key to the Account entity.
@JoinColum
can be used If you would like override default foreign key name like @JoinColum(name="acc_id")
Upvotes: 1