Reputation: 53
I have 2 tables
Table a - id,b_id,name
Table b - id , name
when I have to make POJO Entity, I wanted to have b_id as a column and as well as foreign key to fetch values from b .
Upvotes: -1
Views: 782
Reputation: 3862
use @JoinColumn
Annotation instead of @Column
for Mapped
fields. Read more about JoinColumn
at this link
Upvotes: 0
Reputation: 12505
The cleanest way would be to just map the foreign key and access the id on the instance of B:
A a = em.find(A.class, 1L);
Long bid = a.getB().getBid();
This shouldn't cause any performance issues, but for specific cases where it does - there are specific solutions available.
Other approaches are possible, but you will end up having a single piece of data encoded in two places and keeping them in sync will be a constant source of problems and subtle bugs.
Upvotes: 0
Reputation: 36223
That's no problem. But you have to mark the column read-only either on the b_id column or in the relationship.
Example 1 Column read only:
public class A {
@Column(insertable = false, updateable = false)
private Integer bId;
@ManyToOne
private B b;
}
Example 2 Relationship read only:
public class A {
private Integer bId;
@JoinColumn(name="b_id", insertable = false, updatable = false)
@ManyToOne
private B b;
}
Upvotes: 1