Can we have @Column and @OneToOne both annotation for one of the variable?

598 Views Asked by At

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 .

3

There are 3 best solutions below

2
Simon Martinelli On BEST ANSWER

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;

}
0
fdreger On

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.

0
Mustahsan On

use @JoinColumn Annotation instead of @Column for Mapped fields. Read more about JoinColumn at this link