Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it possible to have foreign key enforced without object-to-object mapping?
    primarykey
    data
    text
    <p>Assuming the following mappings are provided:</p> <pre><code>&lt;class name="A" table="a_table"&gt; &lt;id name="id"/&gt; &lt;many-to-one name="entityB" column="fk_B" not-null="false" unique="true"/&gt; &lt;/class&gt; &lt;class name="B" table="b_table"&gt; &lt;id name="id"/&gt; &lt;/class&gt; </code></pre> <p>Java class:</p> <pre><code>public class A { private long id; private B entityB; // getters and setters skipped } </code></pre> <p>Is it possible to change the Hibernate mapping so that <strong>foreign key is still enforced and created by Hibernate upon startup</strong>, but class <code>A</code> would look like as the following:</p> <pre><code>public class A { private long id; private long idOfB; // getters and setters skipped } </code></pre> <p>I understand that if I convert <code>&lt;many-to-one...</code> into a <code>&lt;property...</code> this would work, but foreign key would not be enforced by the database.</p> <p>I need to do this because object <code>B</code> might (or might not) be initialized separately which sometimes causes <code>org.hibernate.LazyInitializationException: could not initialize proxy - no Session</code> exceptions to occur when <code>a.getB()</code> is called. I would prefer to have it as a <code>long idOfB</code> and load whole object whenever is necessary; this would also make loading of object <code>A</code> quicker.</p> <p>I believe my question is very similar to <a href="https://stackoverflow.com/questions/743434/hibernate-how-declare-foreign-key-without-having-to-code-association-methods-in">this one</a>, yet the offered solution (to use lazy loading) is not appropriate in my case as even if I call <code>a.getB().getId()</code>, I'd get <code>LazyInitializationException</code> whereas if I call <code>a.getIdOfB()</code> I wouldn't.</p> <p>Thanks very much in advance.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

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