Hibernate Cross Reference many-to-many Parent/Child Mapping Of Same Class - java

I'm having a major problem getting a parent/child relationship working for a hierarchy of a single class. Basically I have to represent a server tree like thus:
Server A
Server B
Server C
Server D
Server E
Server C
Server D
Server F
Server G
Note that the children of Servers B & E are the same. My original mapping was something like this, which was fine until I needed to have the objects for server C & D being the same instance, so having a single column for PARENT_ID got filled by the last relationship and only one of servers B or E would show the children:
<hibernate-mapping ...>
<class name="Server" ...>
...
<set name="children" cascade="all-delete-orphan" lazy="false">
<key column="PARENT_ID" />
<one-to-many class="Server" />
</set>
</class>
</hibernate-mapping>
I know I need to do some sort of cross reference table to map the fact that a server can have multiple parents, but all the examples I've found on-line contain a separate parent and child class.
Can anyone tell me how to do a cross reference parent/child mapping for the same class...? I.e. something like:
<hibernate-mapping ...>
<class name="Server" ...>
...
<set name="children" cascade="all-delete-orphan" lazy="false">
<key>
<column name="PARENT_ID" />
<column name="CHILD_ID" />
</key>
<many-to-many class="Server">
<column name="???" />
<formula>???</formula>
</many-to-many>
</set>
</class>
</hibernate-mapping>
Thanks,
Bob.

In your many-to-many mapping, set the column name to be CHILD_ID.
<many-to-many class="Server">
<column name="CHILD_ID" />
</many-to-many>
This will cause the relationship to view the child id as the id representing itself. While the one-to-many relationship will use the parent_id as the id representing itself. Should work, I haven't ran it, but I have done a similar thing before.

Doing the following:
...
<set name="children" table="SERVER_XREF" cascade="all-delete-orphan" lazy="false">
<key column="PARENT_ID" />
<many-to-many class="Server" column="CHILD_ID" />
</set>
...
appears to have resulted in the server hierarchy I was after being returned.
Cheers,

Related

Map hibernate many-to-one with the foreign key in subclass joined table

I'm mapping some entities using Hibernate 3 for my project and simply explained I've got kind of this:
Student entity (tstudent table)
UniversityStudent entity (tuniversitystudent table)
University entity (tuniversity table)
UniversityStudent extends from Student and has its own attributes, like the university itself, which is a foreign key into the tuniversitystudent table. It is also mapped like a subclass into the Student class, using a discriminator field:
<class name="mycompany.Student" table="tstudent" discriminator-value="BASIC">
<id name="id" column="id" type="integer">
<generator class="native" />
</id>
<discriminator column="type" />
<property name="name" column="name" />
<property name="surname" column="surname" />
<property name="phoneNumber" column="phone_number" />
<subclass discriminator-value="UNIVERSITY"
name="mycompany.UniversityStudent">
<join table="tuniversitystudent">
<key column="id_student" />
<many-to-one name="university" class="mycompany.University">
<column name="id_university" />
</many-to-one>
</join>
</subclass>
</class>
Well, now I want to have a Set collection with the UniversityStudent entities for each University. So I map it like that:
<class name="mycompany.University" table="tuniversity">
<id name="id" column="id" type="integer">
<generator class="native" />
</id>
<property name="name" column="name" />
<set name="universityStudents" table="tuniversitystudent">
<key>
<column name="id_university" />
</key>
<one-to-many class="mycompany.UniversityStudent" />
</set>
</class>
My problem comes when I want to load a University object, Hibernate complains that id_university doesn't exist in tstudent table. I checked the generated SQL query and it really tries to load it from tstudent.
Unknown column 'student0_.id_university' in 'field list'
It seems that it's recognizing that it is a subclass of the basic Student and tries to join the collection using a field in the parent table, but however the field is actually in the child table, because only university students can have a University assigned.
I tried another workaround which seems to work but it's not valid for me, that's mapping the UniversityStudent as a joined-subclass instead of a subclass with a join inside:
<joined-subclass name="mycompany.UniversityStudent" table="tuniversitystudent">
<key column="id_student" />
<many-to-one name="university" class="mycompany.University">
<column name="id_university" />
</many-to-one>
</joined-subclass>
However, I'm interested in keeping it as a subclass with a discriminator value. Any idea?
I checked out some resources and finally got into this bug: https://hibernate.atlassian.net/browse/HHH-1015, which looks absolutely compatible with your case. Checkout this old question as well, again very similar to your case.
I firstly read the definition of table per sublass given by Hibernate (I know, it is for version 3.3 but I couldn't find the same source for Hibernate 4): joined-subclass seems (to me) to be a custom implementation of subclass using a discriminator provided by Hibernate and that is a good reason to stay away from its usage. However, from what I know, the mappings table per sublass and table per subclass using a discriminator should be equivalent, that's why I believe the bug I pointed you out is really still open.
If you have time and will, you can try to use another JPA provider and check if you still run in the same issue. JPA 2.0 specifications is a thing, provider implementation is another! I recently run into another bug (related to #IdClass) which forced me to try EclipseLink and the configuration which was not working with Hibernate was right with Eclipse Link
Seems you can use Custom SQL (or HQL) for loading. Haven't tried it myself, but looks like, hmm, at least as a last resort, it provides a decent solution.
Define the query in your HBM:
<sql-query name="universityStudents">
<load-collection alias="unistu" role="University.universityStudents"/>
SELECT unistu.*, student.*
FROM tuniversitystudent unistu
JOIN tstudent student
ON unistu.id_student = student.id
WHERE unistu.id_university = :id
</sql-query>
And then use it inside University:
<set name="universityStudents" inverse="true">
<key/>
<one-to-many class="mycompany.UniversityStudent"/>
<loader query-ref="universityStudents"/>
</set>

Hibernate Mapping of Join Table with Meta Data

I'm trying to figure out how to map the relationship between two tables through a join table that has some meta data in it. In short, the three tables represent the page of a form, and each page can contain any number of elements (questions.) For some reason, the original developer decided that elements could be used on multiple forms. This means that the weight column, used to order the elements on the page, is in the join table.
How the heck do I map this in XML? (Annotations aren't an option.)
For the join table, I guess it's like this:
<class name="com.foo.bar.model.db.ApplicationPageElements"
table="APPLICATION_PAGE_ELEMENTS">
<composite-id name="id" class="com.foo.bar.model.db.ApplicationPageElementsKey">
<key-property name="pageId" column="page_id"/>
<key-property name="elementId" column="element_id"/>
</composite-id>
<property name="weight" type="java.lang.Long">
<column name="WEIGHT" precision="0" />
</property>
</class>
My instincts have me wanting to do something like this from the ApplicationPage side of things:
<set name="applicationElements" table="applicationPageElement">
<key column="page_id"/>
<many-to-many column="element_id" unique="true"
class="com.foo.bar.model.db.ApplicationElements" />
</set>
And that's where I get all slack-jawed, stare at the screen, and sob.
We're using .hbm.xml files to map our database. We also made the decision to not change our database.
Any ideas on how to map this in XML?
Instead of thinking of the relationship between application_page and application_element as many to many, think of it as a one to many relationship from application_page to ApplicationPageElements and a one to many relationship from application_element to ApplicationPageElements.
In your application_page xml mapping add this:
<set name="applicationElements" inverse="true">
<key column="page_id"/>
<one-to-many class="ApplicationPageElements"/>
</set>
page_id forms a part of the primary key of the join table. So, mark the collection as inverse.
Your mapping for the join table is correct. But, with the above change current mapping of your join table you can navigate from application_page to ApplicationPageElements. To navigate from application_page to application_element (via ApplicationPageElements) add a many to one relationship in join table mapping.
<class name="com.foo.bar.model.db.ApplicationPageElements"
table="APPLICATION_PAGE_ELEMENTS">
<composite-id name="id" class="com.foo.bar.model.db.ApplicationPageElementsKey">
<key-property name="pageId" column="page_id"/>
<key-property name="elementId" column="element_id"/>
</composite-id>
<property name="weight" type="java.lang.Long">
<column name="WEIGHT" precision="0" />
</property>
<many-to-one name="elements" class="ApplicationElements"
column="element_id" not-null="true" insert="false" update="false"/>
<many-to-one name="page" class="ApplicationPage"
column="page_id" not-null="true" insert="false" update="false"/>
</class>
Note that in the above many-to-one mapping, insert and update attributes are set to false. This is necessary because the columns are mapped twice, once in the composite key (which is responsible for insertion of the values) and again for the many-to-one associations.
The above use case is mentioned in detail in the book: Java Persistence with Hibernate.

Delete child objects/records in one-to-many relationship using Hibernate

I have a parent-child (one-to-many) relationship between product & packages. one product can have multiple packages. In my 'Edit Product' jsp page I am allowing user to edit product & delete/add/edit any package. Now, on submitting the changes I am doing saveOrUpdate(product) in my controller method. What I am observing is that new packages are getting added in DB but the ones that are deleted by user hence not in the packages Set of Product are not getting deleted from DB. My hiberate configurations snippet is below. Am I missing something here?
<hibernate-mapping>
<class name="author.vo.ProductVO" table="Product">
<id name="ProductID" type="long">
<column name="Product_ID" />
<generator class="increment" />
</id>
<set name="packages" inverse="true" cascade="all" lazy="false">
<key column="Product_ID" not-null="true" on-delete="cascade"/>
<one-to-many class="author.vo.PackageVO" />
</set>
Code for adding product
#Autowired
private HibernateTemplate hibernateTemplate;
this.hibernateTemplate.saveOrUpdate(prod);
You should add "cascade delete orphan" to your xml config, also, why dont you try a simple situation first of all.
is a save working with a parent - child.
is a delete working with a parent - child.

Hibernate is updating instead of inserting, why?

I'm starting my adventure with Hibernate, so please be patient :)
I want to make mapping for two tables, for example A and B. The relation beetwen A and B is one-to-many.
I wrote this hbm.xml file:
<hibernate-mapping package="something">
<class name="A" table="A">
<id name="id" type="int" column="ID">
<generator class="native" />
</id>
<set name="setInA" sort="natural" cascade="all" lazy="false">
<key column="ANOTHER_ID"/>
<one-to-many class="B" />
</set>
</class>
<class name="B" table="B">
<id name="anotherId" type="int" column="ANOTHER_ID">
<generator class="native" />
</id>
</class>
</hibernate-mapping>
Of course I made also POJO classes A and B.
And now, when I try to do:
A a = new A();
Set<B> set = new TreeSet<B>();
set.add(new B());
a.setSetInA(set);
session.save(a);
Hibernate inserts new row to table A, but (what is the worst) is not inserting new row to B table, but only makes SQL Update on not existing row in B.
Can tell me anyone why it is happening? What I made wrong?
You should either persist B's objects firstly, or use Cascade option.
You can use Cascade without using annotations:
<set name="setInA" sort="natural" cascade="all" lazy="false" cascade="all">
<key column="ANOTHER_ID"/>
<one-to-many class="B" />
</set>
This will ensure that collection of B instances is inserted when you insert A.
Found this question while searching for causes of the same symptoms in my system. cascade="all" did not help.
In my case I solved this by adding a mapping to the list element, in this example class B.
Please note that the enclosing class (A in this example) also was versioned. Hibernate might require that versioning (used for optimistic locking) must be enabled for all nested elements. I haven't found any documentation to support this theory.

Legacy mapping with hibernate

For my current project I have to map a legacy database using hibernate, but I'm running into some problems.
The database is setup using one 'entity' table, which contains common properties for all domain objects. Properties include (among others) creation date, owner (user), and a primary key which is subsequently used in the tables for the domain objects.
A simple representation of the context is as such:
table entity
- int id
- varchar owner
table account
- int accountid (references entity.id)
table contact
- int contactid (references entity.id)
- int accountid (references account.accountid)
My problem exhibits itself when I try to add a collection mapping to my account mapping, containing all contacts belonging to the account. My attempts boil down to the following:
<hibernate-mapping>
<class name="Contact" table="entity">
<id name="id" column="id">
<generator class="native" />
</id>
<join table="contact">
<key column="contactid"/>
<!-- more stuff -->
</join>
</class>
</hibernate-mapping>
<hibernate-mapping>
<class name="Account" table="entity">
<id name="id" column="id">
<generator class="native" />
</id>
<bag name="contacts" table="contact">
<key column="accountid" />
<one-to-many class="Contact"/>
</bag>
<join table="account">
<key column="accountid"/>
<!-- more stuff -->
</join>
</class>
</hibernate-mapping>
However, when I try to fetch the account I get an SQL error, stating that the entity table does not contain a column called accountid. I see why this is happening: the mapping tries to find the accountid column in the entity table, when I want it to look in the contact table. Am I missing something obvious here, or should I approach this problem from another direction?
This looks to me like you actually need to be mapping an inheritance, using the Table Per Subclass paradigm.
Something like this:
<class name="entity" table="entity">
<id name="id" column="id">
...
</id>
<joined-subclass name="contact" table="contact">
<key column="contactid"/>
</joined-subclass>
<joined-subclass name="account" table="account">
<key column="accountid"/>
</joined-subclass>
</class>
That's approximate by the way - it's described in detail in section 9.1.2 of the Hibernate documentation (just in case you can't find it, it's called "Table per subclass").
Cheers
Rich

Categories