0

I want to model an optional one to one mapping with JPA.

tableA has a column (flag) and when that is true I need to select additional data from an other tableB to get a string.

tableB has a fk to the pk of tableA.

So far I tiered this mapping but hibernates makes additional selects for tableB per default. I only want those when I access the mapping to tableB.

Class TableA

@OneToOne(mappedBy= tableA_id, fetch = FetchType.LAZY, optional = true)
private TableB tableB;

Class TableB

@OneToOne(mappedBy= tableA_id, fetch = FetchType.LAZY, optional = true)
@JoinColumn(name = "TABLEA_ID"
private TableA tableA

The result is that I get selects on tableB just from a em.createQuery("from TableA") before even accessing getTableB().

kiatra
  • 116
  • 8
  • Sure, just model your dependency as a (optional) @OneToOne relationship - you tried this? – Smutje Nov 05 '19 at 14:05
  • @Smutje what is an optional OneToOne relationship? You mean a lazy init OneToOne? And then call the getter for that inside the EntityA. Hmm that could work I have not thought about that simple solution. – kiatra Nov 05 '19 at 14:25
  • No, it can be EAGER or LAZY, as long as it is optional (which it is by default for @OneToOne) - from the doc: `(Optional) Whether the association is optional. If set to false then a non-null relationship must always exist.` – Smutje Nov 05 '19 at 14:28
  • @Smutje optional = true Does not work. Maybe because of https://stackoverflow.com/questions/1444227/making-a-onetoone-relation-lazy – kiatra Nov 09 '19 at 13:51

0 Answers0