Search code examples
databasehibernatejpajpa-2.0entity-relationship

JPA Entity that uses join for a username but transparently uses an integer id


Suppose I have an entity class that stores a username:

class Profile {
   private String userName;
   ...
}

Then in the database I have two tables:

--- USERS ---
-> username (varchar)
-> uid (int)

--- PROFILES ---
-> uid

There is a one to one relationship between the USERS and PROFILES tables joining on uid. I want my Profile entity class to have all the fields of the PROFILES table but swap out the uid for the username in the class instead. I just want to use the uid for joins and to conserve space in the database. Note I am using Spring's HibernateTemplate() to execute the named queries I created.

Is there a way I can use JPA to map the userName field of another table into the Profiles entity? When I save a Profile entity, how will it know it was just a joined field?


Solution

  • I believe you can do this with a @SecondaryTable annotation.

    I think you'll have to have the uid in a field in the entity class, but i imagine that won't be a problem.