简体   繁体   中英

How to do One to One association in hibernate with foreign key and join table and unidirectional

I wish to have a one to one association with a join table in unidirectional way. -

Tables :

  1. A (A_id, D_id, A_Data)
  2. B (A_id, C_id) // Join table just contain relation between A and C
  3. C (C_id, C_Data)

     Class A { . . @OneToOne(cascade = CascadeType.ALL) @JoinTable(name = "B", joinColumns = @JoinColumn(name = "A_id", referencedColumnName = "A_id"), inverseJoinColumns = @JoinColumn(name = "C_id", referencedColumnName = "C_id")) private C c; } 

I am using hibernate with jpa 2.0. Entity D is not important in the model hence ignored. I only wish to read data ,hence insert/update/delete use cases should not be concern, but one can suggest best practice in that case also.

This setup does not work. Can some one suggest how to do it in correct way?

It gives following exception

org.hibernate.MappingException: Unable to find column with logical name: A_id in org.hibernate.mapping.Table(A) and its related supertables and secondary tables

In order to get your desired schema:

    // Given the following C entity
    @Entity
    public class C {

        @Id
        @Column(name = "C_ID")
        private long id;

        private String C_Data;

        //...
    }


    // A Entity should be 
    @Entity
    public class A {

        @Id
        @Column(name = "A_ID")
        private long id;

        private String A_Data;

        @OneToOne(cascade = CascadeType.ALL )
        @JoinTable(name = "B", joinColumns = @JoinColumn(name = "A_id"), inverseJoinColumns = @JoinColumn(name = "C_id", unique = true))
        private C c;

        //...

    }

I've omitted referencedColumnName , so hibernate will map it to the entity primary key.

Note also that A_id column of B table will be the primary key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM