When I save a department, the employees are not saved automatically. Why not?
Used Hibernate v. 2.0.3 and MySQL 4.0.15.
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("
[email protected]");
manager.setFirstName("Bill");
manager.setLastName("Gates");
Employee worker = new Employee();
worker.setEmployeeId(844);
worker.setDepartment(department);
worker.setEmail("
[email protected]");
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!");
}
}