Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First off, some clarifications to <strong>KLE</strong>'s answer:</p> <ol> <li><p>Unconstrained (nullable) one-to-one association is the only one that can not be proxied without bytecode instrumentation. The reason for this is that owner entity MUST know whether association property should contain a proxy object or NULL and it can't determine that by looking at its base table's columns due to one-to-one normally being mapped via shared PK, so it has to be eagerly fetched anyway making proxy pointless. Here's a <a href="https://www.hibernate.org/162.html" rel="noreferrer">more detailed</a> explanation.</p></li> <li><p>many-to-one associations (and one-to-many, obviously) do not suffer from this issue. Owner entity can easily check its own FK (and in case of one-to-many, empty collection proxy is created initially and populated on demand), so the association can be lazy.</p></li> <li><p>Replacing one-to-one with one-to-many is pretty much never a good idea. You can replace it with unique many-to-one but there are other (possibly better) options.</p></li> </ol> <p><strong>Rob H.</strong> has a valid point, however you may not be able to implement it depending on your model (e.g. if your one-to-one association <em>is</em> nullable).</p> <p>Now, as far as original question goes:</p> <p>A) <code>@ManyToOne(fetch=FetchType.LAZY)</code> should work just fine. Are you sure it's not being overwritten in the query itself? It's possible to specify <code>join fetch</code> in HQL and / or explicitly set fetch mode via Criteria API which would take precedence over class annotation. If that's not the case and you're still having problems, please post your classes, query and resulting SQL for more to-the-point conversation.</p> <p>B) <code>@OneToOne</code> is trickier. If it's definitely not nullable, go with Rob H.'s suggestion and specify it as such:</p> <pre><code>@OneToOne(optional = false, fetch = FetchType.LAZY) </code></pre> <p>Otherwise, if you can change your database (add a foreign key column to owner table), do so and map it as "joined":</p> <pre><code>@OneToOne(fetch = FetchType.LAZY) @JoinColumn(name="other_entity_fk") public OtherEntity getOther() </code></pre> <p>and in OtherEntity:</p> <pre><code>@OneToOne(mappedBy = "other") public OwnerEntity getOwner() </code></pre> <p>If you can't do that (and can't live with eager fetching) bytecode instrumentation is your only option. I have to agree with <strong>CPerkins</strong>, however - if you have <strong>80!!!</strong> joins due to eager OneToOne associations, you've got bigger problems then this :-)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload