Cory Foy

Thursday, September 14, 2006

Mapping a Hibernate object using joined tables

My pair and I searched around and around today for this problem. We have an object whose definition comes from one table, but has one or two fields that need to come from a joined table. Something like:

TableSecurity ( int userId, varchar username, varchar password, bit isActive )
TableUser ( int userId, bit isPreferred )


public class User {

  private int userId;
  private String userName;
  private boolean active;
  private boolean preferred;

  //...getters and setters

}


We'd normally have a Hibernate mapping like:

<class name="com.cornetdesign.User"
    table="TableSecurity" mutable="false">
  <id name="id" column="userId"/>
  <property name="userName" column="username"/>
  <property name="preferred" column="isPreferred"/>
  <property name="active" column="isActive"/>
</class>


But because we need to get those values from the TableUser table, we need to join them. It's as simple as:

<class name="com.cornetdesign.User" mutable="false">
  <subselect>
    SELECT sec.userId, sec.username, sec.isActive, user.isPreferred
    FROM TableSecurity sec
    LEFT JOIN TableUser user
      ON user.userId = sec.userId
  </subselect>
  <id name="id" column="userId"/>
  <property name="userName" column="username"/>
  <property name="preferred" column="isPreferred"/>
  <property name="active" column="isActive"/>
</class>

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home