简体   繁体   English

如何在外键与联接表和单向休眠状态下进行一对一关联

[英]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) A(A_id,D_id,A_Data)
  2. B (A_id, C_id) // Join table just contain relation between A and C B(A_id,C_id)//连接表仅包含A和C之间的关系
  3. C (C_id, C_Data) 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. 我在jpa 2.0中使用了休眠模式。 Entity D is not important in the model hence ignored. 实体D在模型中不重要,因此被忽略。 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. 我省略了referencedColumnName ,因此hibernate会将其映射到实体主键。

Note also that A_id column of B table will be the primary key. 另请注意, B表的A_id列将为主键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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