Hibernate, @EmbeddedId and renaming columns

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;
    ...
}

And using it:

class SomeClass {
    ...
    @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();

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;
    ...
}

Which sucks 🙁

Leave a Reply

Your email address will not be published.

Notify me of followup comments via e-mail. You can also subscribe without commenting.

This site uses Akismet to reduce spam. Learn how your comment data is processed.