[英]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. FK在B表中。
Runnig the following query does not work: Runnig以下查询不起作用:
SELECT A1 FROM A A1 LEFT JOIN FETCH A1.b WHERE A1.id = 6;
I don't get B. 我没有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. 另外,如果我让休眠生成数据库,它将在A表中设置FK,但我希望在B表中设置它。 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. 我认为一个潜在的解决方案是将B类设置为关系的所有者。 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
并带有外键,请尝试使用此方法
@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. insertable = false, updateable = false
应该指示休眠在目标表中查找联接列。
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. 我把A边的mapedBy放进去,然后将@JoinColumn放到B类的A属性上。
Thanks all for your help. 感谢你的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.