Hibernate - Foreign keys instead of Entities

前端 未结 4 2109
名媛妹妹
名媛妹妹 2020-11-27 17:17

Currently, Hibernate allows me to load objects defined by *-to-one relationships directly with

entity1.getEntity2()

Is it possible to get

4条回答
  •  臣服心动
    2020-11-27 17:32

    Long fk = entity1.getEntity2().getId();
    

    This should work. It would only not work if you have composite, primary keys being referenced as foreign keys but your solution wouldn't work either in that case. Considering my solution, even a composite key wouldn't look that ugly.

    Long fkField1 = entity1.getEntity2().getCol1();
    String fkField2 = entity1.getEntity2().getCol2();
    

    Something like that will work.

    EDIT: Thinking about your proposed solution more, it wouldn't work anyway because Hibernate already tries to automatically create a FK field for a Mapped relationship, so defining another @Column would simply try to bind to a second column with the same name.

提交回复
热议问题