Krutarth Vora
Krutarth Vora

Reputation: 53

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

I have 2 tables

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

Answers (3)

Mustahsan
Mustahsan

Reputation: 3862

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

Upvotes: 0

fdreger
fdreger

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

Simon Martinelli
Simon Martinelli

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

Related Questions