I practice using Hibernate with the example of the site
http://www7b.software.ibm.com/dmdd/libr ... hogal.html
When I save a department, the employees are not saved automatically. Why not?
Used Hibernate v. 2.0.3 and MySQL 4.0.15.
Here is all the code so that you can understand it:
Code:
package com.ibm.hibernate_article;
import java.sql.SQLException;
import java.util.List;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
public class Test {
SessionFactory sessionFactory;
public Test() throws HibernateException {
Configuration cfg = new Configuration()
.addClass(com.ibm.hibernate_article.Department.class)
.addClass(com.ibm.hibernate_article.Employee.class);
sessionFactory = cfg.buildSessionFactory();
}
public static void main(String[] args) throws HibernateException, SQLException {
Test test = new Test();
Department department = new Department();
department.setDepartmentID(211);
department.setCity("Austin");
department.setState("TX");
department.setName("IBM Global Services");
Employee manager = new Employee();
manager.setEmployeeId(422);
manager.setDepartment(department);
manager.setEmail("bill.gates@yahoo.com");
manager.setFirstName("Bill");
manager.setLastName("Gates");
Employee worker = new Employee();
worker.setEmployeeId(844);
worker.setDepartment(department);
worker.setEmail("john.smith@yahoo.com");
worker.setFirstName("John");
worker.setLastName("Smith");
worker.setManager(manager);
test.save(department);
}
private void save(Object object) throws HibernateException, SQLException {
Session session = sessionFactory.openSession();
session.save(object);
session.flush();
session.connection().commit();
session.close();
// sessionFactory.close();
System.out.println("Saving finished!");
}
}
Quote:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping.dtd">
<hibernate-mapping>
<class name="com.ibm.hibernate_article.Department" table="department">
<id name="departmentID" column="DepartmentID">
<generator class="assigned"/>
</id>
<property name="city" column="City"/>
<property name="name" column="Name"/>
<property name="state" column="State"/>
</class>
</hibernate-mapping>
Quote:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping.dtd">
<hibernate-mapping>
<class name="com.ibm.hibernate_article.Employee" table="employee">
<id name="employeeId" column="EID">
<generator class="assigned"/>
</id>
<property name="email" column="Email"/>
<property name="firstName" column="FirstName"/>
<property name="lastName" column="LastName"/>
<many-to-one name="department" column="departmentID"/>
<many-to-one name="manager" column="managerEID"/>
</class>
</hibernate-mapping>