I have two beans namely employee and department.This is one-to-many relationship where in one department many employees are working.department_id is the primary key.
This is Runner class which has main method
package Manytoone;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
public class Runner {
static void main(
String[] args) {
SessionFactory factory=FactoryOneInstance.getInstance();
Session session=factory.openSession();
Transaction trans=session.beginTransaction();
Employee employee=new Employee();
Department dept=new Department();
employee.setName("Kavitha");
dept.setName("Software");
dept.setEmployee(employee);
try
{
trans.begin();
session.save("dept",dept);
trans.commit();
}
catch(HibernateException e)
{
e.printStackTrace();
trans.rollback();
}
}
}
This is employee.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="Manytoone">
<class name="Employee" table="employee" entity-name="emp">
<id name="empid" column="Id">
<generator class="increment"></generator>
</id>
<property name="name"></property>
</class>
</hibernate-mapping>
This is department.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Manytoone.Department" table="department" entity-name="dept">
<id name="department_id" column="deptid">
<generator class="increment"></generator>
</id>
<property name="name"></property>
<many-to-one name="employee" class="Manytoone.Employee" cascade="all" >
<column name="empid"></column>
</many-to-one>
</class>
</hibernate-mapping>