Hibernate one to zero or one mapping

前端 未结 3 978
广开言路
广开言路 2020-12-30 07:11

I\'m trying to map a one to \"zero or one\" relationship in Hibernate. I think I may have found a way using a many-to-one.

class A {
  private B b;
  // .         


        
相关标签:
3条回答
  • Like Boden said, the answer is to add not-found="ignore" to the many-to-one statement in A. Doing this with annotation:

    In Class A:

    @ManyToOne
    @Cascade({ CascadeType.ALL })
    @JoinColumn(name = "Id")
    @NotFound(action=NotFoundAction.IGNORE)
    private B b
    

    in Class B:

    @Id
    @GeneratedValue(generator = "myForeignGenerator")
    @org.hibernate.annotations.GenericGenerator(
        name = "myForeignGenerator",
        strategy = "foreign",
        parameters = @Parameter(name = "property", value = "a")
    )
    private Long subscriberId;
    
    @OneToOne(mappedBy="b")
    @PrimaryKeyJoinColumn
    @NotFound(action=NotFoundAction.IGNORE)
    private A a;
    
    0 讨论(0)
  • 2020-12-30 07:40

    The answer was to add not-found="ignore" to the many-to-one statement in A:

    <many-to-one name="b" class="B" not-found="ignore" insert="false" update="false" column="id" unique="true"/>
    

    I tried simply adding lazy="false" to B as Rob H recommended, but that resulted in a HibernateObjectRetrievalFailureException everytime I loaded an A that had no B.

    See this thread for more information:

    https://forum.hibernate.org/viewtopic.php?p=2269784&sid=5e1cba6e2698ba4a548288bd2fd3ca4e

    0 讨论(0)
  • 2020-12-30 07:41

    Try setting lazy="false" on the many-to-one element. That should force Hibernate to try to fetch the association ("B") when the first object ("A") is loaded. The property in "A" will either be initialized with a real instance of "B" or null.

    0 讨论(0)
提交回复
热议问题