3
votes

I have a situation where few tables (TableA & TableB) have one-to-one relationship with a same table (TableC). TableA and TableB are unrelated. I have designed the tables as below.

TableA
- key
- something
- c_ref_key

TableB
- key
- something
- c_ref_key

TableC
- key
- something

When I generate JPA entity from this database using hibernate reverse-engineering, it create many-to-one relation in TableA and TableB for TableC. Normally to create one-to-one relationship I would have TableA primary key as primary key of TableC but since I have other tables (TableB) which also have one-to-one relationship with TableC , I cant do that. Hence I had to use TableC's foreign key in TableA and TableB (which resulted in many-to-one relationship in JPA). Is there any other way to design to keep the relationships one-to-one ? or atleast in generated JPA entities can have one-to-one relationship ?

1

1 Answers

0
votes

You can use @OneToOne hibernate mapping with @JoinColumn to create foreign key. Below is the very basic implementation for schema, You can extend it as per your requirements.

TableA.java

    @Entity(name = "TABLE_A")
    public class TableA {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long key_a;

        private String something;

        @OneToOne
        @JoinColumn(name = "c_ref_key", referencedColumnName = "key_c")
        private TableC c_ref_key;
    }

TableB.java

@Entity(name = "TABLE_B")
public class TableB {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long key_b;

    private String something;

    @OneToOne
    @JoinColumn(name = "c_ref_key", referencedColumnName = "key_c")
    private TableC c_ref_key;
}

TableC.java

@Entity(name = "TABLE_C")
public class TableC {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long key_c;

    private String something;
}

I tested this schema on MySql database and It works fine.