POJO Data with One-to-Many / Many-to-One (JDBC)

For example, I have two objects: Enterprise, Department. An enterprise has many departments, a department has one enterprise, so the Department table has a column - Enterprise_ID. I have a function to save Department object

void save(Department department);

      

To add the Enterprise_ID to the table, I need to have a reference to the Enterprise object or corporate ID.

Which method is more appropriate?

However, I prefer not to have such information in the department object, but along the way, how can I store the Enterprise_ID in the table? It seems to me that Hibernate does it somehow.

public class Department{
private long id;
private String name;
private DepartmentType type;
private List<Employee> employees;
//getters()/setters()
}
public class Enterprise{
...
private List<Department> departments;
...
}

      

The department has no information about the Company in which it exists. Therefore, using only the department object, I cannot insert Enterprise_ID (FK) into the department table. But the hibernation method somehow does it. How can I do this without hibernation using the entities above,

I am using JDBC.

+3


source to share


2 answers


To do this in the same way as hibernate, you will have a method save(Enterprise)

that will persist the enterprise object to db and also insert / update foreign key association.

Hibernate supports both null and invalid foreign keys. In the latter case, it first inserts the enterprise, getting its primary key value, and then inserts the department along with the correct foreign key value.



You can do the same. However, the method save(Department)

could only update the department table and not change the relationship to the enterprise table. To do this, you will have to modify the collection in the enterprise and save / update it to db.

+1


source


Hibernate will keep or update the foreign key if you change something in the Enterprise.departments collection. This is the only way to do it, unless you have a reverse relationship.

In your code, you will need to use an Enterprise object to update foreign keys in the department table.



You can create a bi-directional relationship by putting the "Enterprise" field in your Department class, but then you need to synchronize both relationships manually ...

+1


source







All Articles