GeT_RiGhT
GeT_RiGhT

Reputation: 47

POJO data with one to many / many to one relationship(JDBC)

For example I have two entities : Enterprise, Department. Enterprise has many departments, department has one enterprise, so there is a column - Enterprise_ID in Department table. I have a function for saving Department object

void save(Department department);

To add Enterprise_ID in the table I need to have either reference on Enterprise object or enterprise's id.

Which way is more suitable?

However I prefer do not have such information in department object but on this way how can I save Enterprise_ID in the table ? It seems to me Hibernate somehow doing it.

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;
...
}

Department does not have any information about Enterprise in which it exists. So using only department object I can't insert Enterprise_ID(FK) in department table. But hibernate's save method somehow doing it. How can I do it without hibernate using entities above;

I use JDBC.

Upvotes: 3

Views: 2612

Answers (2)

Maarten Winkels
Maarten Winkels

Reputation: 2417

To do it the same way as hibernate does, you would have a save(Enterprise) method that would persist the enterprise object to the db and also insert/update the foreign key association.

Hibernate supports both nullable and non-nullable foreign key. In the latter case, it will first insert the enterprise, obtaining its primary key value, and then insert the department's along with the correct foreign key value.

You could do the same. But the save(Department) method would only be able to do updates on the department table and not change the association to the enterprise table. To do that, you would have to change the collection in enterprise and save/update that to the db.

Upvotes: 1

GeertPt
GeertPt

Reputation: 17846

Hibernate will only save/update the foreign key if you change something in the Enterprise.departments collection. It's the only way to do it if you don't have the reverse relation.

In your code, you'll have to use the Enterprise object to update the foreign keys in the Department table.

You could create a bidirectional association, by putting a field 'enterprise' in your Department class, but then you need to keep both relations in synch manually...

Upvotes: 1

Related Questions