Create a hibernate collection on two columns

I am trying to create an address book application with one table for People, one for companies and one for phones. The "Phones" table will contain data for people and companies with a field indicating where it came from. Let's assume these are simple tables:

CREATE TABLE `Person` {
  `id` int(11) NOT NULL auto_increment,
  `firstName` varchar(80) NOT NULL,
  `lastName` varchar(80) NOT NULL
}

CREATE TABLE `Company` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(80) NOT NULL
}

CREATE TABLE `ContactPhone` (
  `id` int(11) NOT NULL auto_increment,
  `contactType` char(1) NOT NULL, -- either 'P' or 'C'
  `contactId` int(11) NOT NULL, -- the id of the Person or Company
  `number` varchar(40) NOT NULL
}

      

I have created the relevant java classes which are a very simple representation:

public class Person {
  private Integer id;
  private String firstName;
  private String lastName;
  private Collection<Phone> phones;
  // ...
}

public class Company {
  private Integer id;
  private String name;
  private Collection<Phone> phones;
  // ...
}

public class Phone {
  private Integer id;
  private String number;
  // ...
}

      

In simple SQL, I can easily get the person and the corresponding phones. I need to create a mapping between Person and Phone and between Company and Phone using simple hibernate (no annotations) but cannot get it to work. Not even sure if it should be unidirectional or bidirectional. I've searched the documentation but didn't find anything to help. Anyone?

+1


a source to share


4 answers


If you are asking how to map them via a mapping table in a config file, it will look something like this:

<bag name="Phone" table="CompanyPhoneMapping" lazy="true" cascade="all">

<key column="CompanyId" />



<one-to-many class=<insert namespace>.Phone, <insert dll> />

</bag>

I am only familiar with nhibernate, but I assume the hibernate Java solution will be similar.

0


a source


Finally I managed to get this to work. I was looking for hibernate polymorphism elements. As a result, I created a Contact class like this:

public class Contact {
  private Integer id;
  private Collection<Phone> phones;
  ...
}

      



and a derivative of a person and a company. With Hibernate polymorphism, it is possible to store Person and Company in different tables and connect a phone to a contact in a bidirectional way.

+1


a source


You can achieve this using Filter Properties in Hibernate

0


a source


Taken with the model, it is like a one-way link to the join table in classes Person

and Company

. How this is achieved depends exactly on the specifics of your model. Online documentation here .

0


a source







All Articles