2014-11-03 81 views
0

我有这种情况:Hibernate的一对一与FK映射

Class A { 

    @Id 
    Integer id; 

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

Class B { 

    @Id 
    Integer id; 


    Integer a_id; 
} 

的FK在B表。

运行过程中出现下面的查询不起作用:

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

我没有得到B.

而且,如果我让Hibernate生成数据库,它设置一个FK在A表,但我想要在B桌上。 不应该有双向映射。

请帮忙,我该怎么做?

回答

1

我认为一个可能的解决方案是将B类设置为关系的所有者一方。您还可以管理使用其他外部表的关系,请参阅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 |  | 
+-------+---------+------+-----+---------+-------+ 
0

如果你想有一个单向@OneToOne,在目标表的外键,尝试用这种

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

insertable = false, updateable = false应指示休眠来寻找目标表联接列。

+0

不,它不起作用。它产生这个连接:左外连接,其中A.a_id = B.id.这是颠倒 – 2014-11-03 12:42:26

+0

@Idob奇怪,根据[文档](http://en.wikibooks.org/wiki/Java_Persistence/OneToOne#Target_Foreign_Keys.2C_Primary_Key_Join_Columns.2C_Cascade_Primary_Keys)和[这个答案](http://stackoverflow.com/ a/26590407/4074715),它应该工作 – 2014-11-03 12:50:53

+0

@Idob你不需要在'B'中有'a_id'作为字段,也许这就是它不起作用的原因。如果没有它,当然,你不需要为其他原因映射它。 – 2014-11-03 13:08:30

0

OK,尝试几乎所有的东西后,我不得不妥协,决定去与双向映射。

这可以很容易地修复一切。

我把A侧放在了mappedBy上,我把@JoinColumn放在B类的A属性上。

谢谢大家的帮助。