Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have foreign key enforced without object-to-object mapping?

Assuming the following mappings are provided:

<class name="A" table="a_table">
  <id name="id"/>
  <many-to-one name="entityB" column="fk_B" not-null="false" unique="true"/>
</class>

<class name="B" table="b_table">
  <id name="id"/>
</class>

Java class:

public class A {
   private long id;
   private B entityB;
   // getters and setters skipped
}

Is it possible to change the Hibernate mapping so that foreign key is still enforced and created by Hibernate upon startup, but class A would look like as the following:

public class A {
   private long id;
   private long idOfB;
   // getters and setters skipped
}

I understand that if I convert <many-to-one... into a <property... this would work, but foreign key would not be enforced by the database.

I need to do this because object B might (or might not) be initialized separately which sometimes causes org.hibernate.LazyInitializationException: could not initialize proxy - no Session exceptions to occur when a.getB() is called. I would prefer to have it as a long idOfB and load whole object whenever is necessary; this would also make loading of object A quicker.

I believe my question is very similar to this one, yet the offered solution (to use lazy loading) is not appropriate in my case as even if I call a.getB().getId(), I'd get LazyInitializationException whereas if I call a.getIdOfB() I wouldn't.

Thanks very much in advance.

like image 922
mindas Avatar asked Jan 21 '10 17:01

mindas


1 Answers

As said

I understand that if I convert <many-to-one... into a <property... this would work, but foreign key would not be enforced by the database.

So my advice is: use both

public class EntityA {

    private Integer idOfB;

    private EntityB entityB;

    // getter's and setter's

}

And

<class name="A" table="a_table">
    <id name="id"/>
    <property name="idOfB" column="fk_B" not-null="false" unique="true"/>
    <many-to-one name="entityB" update="false" insert="false" column="fk_B"/>
</class>

Notice when two properties share the same column, you have to put settings about it in just one property. Otherwise, Hibernate will complain some errors. It explains why i define update="false" and insert="false" in entityB property.

regards,

like image 169
Arthur Ronald Avatar answered Sep 19 '22 15:09

Arthur Ronald