Fabio Cepeda

Making persistent collections of integers Hibernate where both fields are primary keys in the table

Posted on: February 8, 2007

I develop a web application using appfuse, springframework, and hibernate, MySQL . I had the following situation:

I needed to persiste a collection of unique integers for an object. Where the primary Id of the collection table was the primary key of the table mapped by Contacto.

public class Contacto implements java.io.Serializable {

private Integer contactoId; //Primary key of this object
Set private Set beneficiarioTitularDe = new HashSet(); // Collection of unique integers.

//Getters and setters omitted for simplicity

Here is the db table script

CREATE TABLE `beneficiariosprimariosinmuebles` (
`contactoID` int(10) unsigned NOT NULL default ‘0’,
`inmuebleID` int(10) unsigned NOT NULL default ‘0’,
PRIMARY KEY (`contactoID`, inmuebleID),
KEY `beneficiariosprimariosinmuebles_FKIndex1` (`contactoID`)

# Foreign keys for table propietariosinmuebles

ALTER TABLE `beneficiariosprimariosinmuebles`
ADD FOREIGN KEY (`contactoID`) REFERENCES `contactos` (`contactoID`) ON UPDATE NO ACTION;

Here is the mapping file of hibernate:

Trying to persist this kind of collection was a challenge in the case where the field inmuebleID was null because it was a primay key of my collection table in the database. Reason why I did this in the database was to assure unique integers in the DB. However, for some reason hibernate was not able to delete the record from the database because the inmuebleID was the primary key in the DB table.

The solution I came up with was to assure the Set did not have null values before calling the save method on the onBind method of my contoller.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s



%d bloggers like this: