Saturday, 6 July 2013

Hibernate Many to One Mapping example

In this post, I will show you a simple example of many to one relationship in Hibernate mapping. In this example, one user is belong to a group. A group contains many user
package com.easyinfogeek.hibernate;  
public class Group {  
    private int id;  
    private  String name;  
    .....
    // setting and getter is ignore here

}  
package com.easyinfogeek.hibernate;  
public class User {  
    private int id;  
    private String name;  
    private Group group;  
    .....
    // setting and getter is ignore here
 }
 <!DOCTYPE hibernate-mapping PUBLIC   
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
<hibernate-mapping>  
    <class name="com.easyinfogeek.hibernate.Group" table="t_group">  
        <id name="id">  
            <generator class="native" />  
        </id>  
        <property name="name" />  
    </class>  
</hibernate-mapping> 
<?xml version="1.0"?>  
<!DOCTYPE hibernate-mapping PUBLIC   
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
<hibernate-mapping>  
    <class name="com.easyinfogeek.hibernate.User" table="t_user">  
        <id name="id">  
            <generator class="native" />  
        </id>  
        <property name="name" />  
                <!-- many-to-one groupid-->  
                <many-to-one name="group" column="groupid" cascade="save-update" />  
    </class>  
</hibernate-mapping> 

0 comments:

Post a Comment