Search code examples
javahibernatehibernate-mapping

Hibernate: mapping nested objects -EDITED-


For example, I have the following tables:

USER:

| USERID | USERNAME | USERTYPEID |

USERTYPE:

| USERTYPEID | USERTYPENAME |

So clearly USERTYPEID is a foreign key that a user use to refer to usertype. The JAVA implementation is as such:

I have a class User and a class UserType, where looks like:

public class User {
    private int id;
    private UserType ut;
    ....
}

public class UserType {
    ...
}

In the User.hbm.xml:

<hibernate-mapping>
   <class name="com.pretech.User" table="User">
      <meta attribute="class-description">
         This class contains the employee detail. 
      </meta>
      <id name="id" type="int" column="UserID">
         <generator class="native"/>
      </id>
   </class>
</hibernate-mapping>

So my questions follows:

1) what should I put to map the UserType here and indicate UserType as foreign key?

2) In the case of User includes a list of UserType (may not conceptually true but just want to use as an example), such as:

public class User {
    private int id;
    private List<UserType> uts;
}

what shoud I do about the hibernate mapping?

EDIT: Added explanation about foreign key stuff.


Solution

  • There are so many examples available in net for your example, you can also check the hibernate documentation:

    For example if you want to have a User entity with a set of UserType's then you can use one-to-many relationship and the mapping file will be:

    <class name="User">
        <id name="id" column="id">
            <generator class="native"/>
        </id>
        <set name="uts">
            <key column="userId" 
                not-null="true"/>
            <one-to-many class="UserType"/>
        </set>
    </class>
    
    <class name="UserType">
        <id name="id" column="id">
            <generator class="native"/>
        </id>
    </class>
    

    And here is another example from the documentation that uses annotations and List instead of Set: