Making a composite natural key looks like that: (example from Manning book for JPA/Hibernate):
public class UserId implements Serializable {
private String username;
private String departmentNr;
...
}
private String username;
private String departmentNr;
...
}
And using it:
class SomeClass {
...
@EmbeddedId
private UserId userId;
...
}
...
@EmbeddedId
private UserId userId;
...
}
The column names in SomeClass are id_username and id_departmentNr.
So one can't do the following
@SuppressWarnings( "unchecked" )
List<SomeClass> old = (List<SomeClass>) em.createQuery(
"from someClass sc where sc.userId.username = :username and sc.userId.entityType = :departmentNr")
.setParameter(...).getResultList();
List<SomeClass> old = (List<SomeClass>) em.createQuery(
"from someClass sc where sc.userId.username = :username and sc.userId.entityType = :departmentNr")
.setParameter(...).getResultList();
Because Hibernate wouldn't recognize the column names - it would say something like "someclass0._username - cannot find it".
So one has to do column names rewriting:
class SomeClass {
...
@EmbeddedId
@AttributeOverrides( {
@AttributeOverride( name = "username", column = @Column( name = "username" ) ),
@AttributeOverride( name = "departmentNr", column = @Column( name = "departmentNr" ) ) } )
private UserId userId;
...
}
...
@EmbeddedId
@AttributeOverrides( {
@AttributeOverride( name = "username", column = @Column( name = "username" ) ),
@AttributeOverride( name = "departmentNr", column = @Column( name = "departmentNr" ) ) } )
private UserId userId;
...
}
Which sucks 🙁