Here's the DB design (DDL):
Code:
CREATE TABLE Countries
(
iso_code CHAR(2) NOT NULL,
name VARCHAR(50) NOT NULL,
PRIMARY KEY (iso_code)
);
CREATE TABLE Zips
(
country_code CHAR(2) NOT NULL,
code VARCHAR(10) NOT NULL,
PRIMARY KEY (country_code, code),
FOREIGN KEY (country_code) REFERENCES Countries (iso_code)
);
Here's the Zip class + composite primary key class:
Code:
@Entity
@Table(name = "Zips")
public class Zip implements Serializable
{
@EmbeddedId
private ZipId embeddedId;
@ManyToOne
@JoinColumn(name = "country_code", referencedColumnName = "iso_code")
private Country country = null;
...
}
@Embeddable
public class ZipId implements Serializable
{
@Column(name = "country_code", insertable = false, updatable = false)
private String countryCode;
@Column(name = "code")
private String code;
...
}
Hibernate stack trace:
Code:
Exception in thread "main" javax.persistence.PersistenceException: [PersistenceUnit: zips] Unable to build EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:911)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:57)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:48)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:32)
at tld.zips.Main.main(Main.java:27)
Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: tld.zips.model.Zip column: country_code (should be mapped with insert="false" update="false")
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:675)
at org.hibernate.mapping.PersistentClass.checkPropertyColumnDuplication(PersistentClass.java:697)
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:719)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:473)
at org.hibernate.mapping.RootClass.validate(RootClass.java:235)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1332)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1835)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:902)
... 4 more
What's this? country_code is mapped as read-only (insertable = false, updatable = false) in the composite primary key class. This works perfectly with EclipseLink! IIRC @Embeddable classes allow @Basic, @Column, @Enumerated, @Temporal, @Lob, and @Embedded on its columns, so this should work. Note the code is JPA 1.0 compatible.
The exception vanishes when putting the insertable = false, updatable = false on the @JoinColumn, but this is not what I want. I prefer my associations to be writable...
Is this a Hibernate bug? I'm using Hibernate 3.6 stable.
Karsten