Search code examples
javahibernatejpahibernate-annotations

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


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 .


Solution

  • 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;
    
    }