Reputation: 5142
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?
Upvotes: 0
Views: 172
Reputation: 5142
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.
Upvotes: 0
Reputation: 1303
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 | |
+-------+---------+------+-----+---------+-------+
Upvotes: 1
Reputation: 24433
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.
Upvotes: 0