简体   繁体   中英

Hibernate one to one with FK mapping

I have this situation:

Class A {

   @Id
   Integer id;

   @OneToOne
   @JoinColumn(name = "b.a_id", referencedColumnName = "id")
   B b;
}

Class B {

   @Id
   Integer id;


   Integer a_id;
}

The FK is in the B table.

Runnig the following query does not work:

SELECT A1 FROM A A1 LEFT JOIN FETCH A1.b WHERE A1.id = 6;

I don't get B.

Also, If I let hibernate generate the DB, it sets a FK in the A table but I want it on the B table. There should not be a bi-directional mapping.

Help please, How can I do this?

I think that the one potential solution is to setup the B class as a owner side of the relation. You can also manage the relation using another external table please see this

@Entity
public class A {
    @Id
    private Integer id;

    @OneToOne(mappedBy = "a")
    private B b;
}

@Entity
public class B {
    @Id
    private Integer id;

    @OneToOne
    @JoinColumn(name = "a_id")
    private A a;

}

mysql> desc A;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | NO   | PRI | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)

mysql> desc B;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | NO   | PRI | NULL    |       |
| a_id  | int(11) | YES  | MUL | NULL    |       |
+-------+---------+------+-----+---------+-------+

If you want to have a unidirectional @OneToOne , with foreign key in target table, try with this

@OneToOne
@JoinColumn(name = "a_id", insertable = false, updateable = false)
B b;

insertable = false, updateable = false should instruct hibernate to look for join column in target table.

OK, after trying almost everything, I had to compromise and decided to go with the bi-directional mapping.

This fixed everything quite easily.

I put in the A side mappedBy, and the I put the @JoinColumn on the A property of B class.

Thanks all for your help.

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