Reputation: 2388
I'm following this example: http://viralpatel.net/blogs/hibernate-one-to-many-xml-mapping-tutorial/
In the case of the example: it's a one-to-many relationship between departments vs employees (assuming employes can only work in 1 department).
In the example, the a new department is created every time and then new employees were attached to it.
what changes needs to happen if the department is already existing? like perhaps I ran the example again and want to add more employees to an existing department.
I searched the net but all examples/guides I came across assumes a new department is created every time.
My guess is that I need to setup a DAO function that searches the DB and returns a department datatype?
Thanks! :)
Here's the code as mentioned in viralpatel.net
public static void main(String[] args) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
Department department = new Department();
department.setDepartmentName("Sales");
session.save(department);
Employee emp1 = new Employee("Nina", "Mayers", "1212");
Employee emp2 = new Employee("Tony", "Almeida", "4343");
emp1.setDepartment(department);
emp2.setDepartment(department);
session.save(emp1);
session.save(emp2);
session.getTransaction().commit();
session.close();
}
Upvotes: 0
Views: 381
Reputation: 1164
that was the same question i asked a while ago, you can add People to existing Department simply by load/get Department from database first
Department department = session.get(Department.class,new Long(10)); // i assume you are using Long for primary key
Employee emp1 = new Employee("Nina", "Mayers", "1212");
Employee emp2 = new Employee("Tony", "Almeida", "4343");
emp1.setDepartment(department);
emp2.setDepartment(department);
Upvotes: 1
Reputation: 7985
You can use the method get
of the Session object to get the object from databse:
session.get(Department.class, id);
You can see the full documentation in the following ling: http://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/Session.html
Upvotes: 1