as a follow on from hibernate optional join
Many existing queries in the system rely on there being a mapped relationship between EntityOne and EntityTwo and changing this is not an attactive option, however I now need to start storing and retrieving values in tbl_one.two_id
which do not exist in the joined table. On the way in, this works fine with the following mapping:
@Entity
@Table(name="tbl_one")
public class EntityOne
{
....
@ManyToOne
@NotFound(action = NotFoundAction.IGNORE)
@JoinColumn(name = "two_id")
private EntityTwo two;
....
}
.. However when querying, if a result has a value for two_id
which does not exist in the joined table, the value for the field two
is null and I have no way of telling what the value for tbl_one.two_id
actually is. I was hoping hibernate would create a dummy EntityTwo
object and populate it's id field only if the relationship did not exist.
I've also tried mapping two_id
to another field without a join:
@Entity
@Table(name="tbl_one")
public class EntityOne
{
....
@ManyToOne
@NotFound(action = NotFoundAction.IGNORE)
@JoinColumn(name = "two_id", insertable = false, updatable = false)
private EntityTwo two;
@Column(name = "two_id")
private String twoId;
....
}
... but then the two
field is never populated, even when the corresponding record exists.
Essentially I need some way of inserting/updating a value for tbl_one.two_id
and retrieving a joined entity for EntityTwo
if the relationship exists, or just the value for tbl_one.two_id
if the relationship does not exist.
I'm hoping to be able to solve this without creating two mappings for the same table.
thanks.
EDIT: more info
public class EntityTwo
{
...
@Id
@Column(name = "site_id")
private String id;
...
}
This should work :
@ManyToOne
@NotFound(action = NotFoundAction.IGNORE)
@JoinColumn(name = "two_id", insertable = false, updatable = false)
private EntityTwo two;
@Formula("two_id")
private String twoId;
Hibernate will select the two_id column twice : once to populate the two relationship, and once to populate the twoId. The twoId property is read-only, though.
You could also do the reverse, but then it's the two property which will become read-only:
@ManyToOne
@NotFound(action = NotFoundAction.IGNORE)
@JoinFormula("two_id")
private EntityTwo two;
@Column("two_id")
private String twoId;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With