简体   繁体   中英

How to persist a one-to-one relationship ? (no framework)

Right now I have a DAO for each entity.

When I save a certain entity, say Employee, it needs to be linked to corresponding Node entity to show up in a tree.

How can this be done while keeping the code as simple as possible ?

Edit: Here's some added detail. In OO, what I want to achieve is to be able to have a Node refer to an object with the possibility that it could be found under another Node. This way only a Node is necessary to describe a tree while different properties can be fetched from the contained object. Here's how I see things:

Node 1-1 NodeObject 1-1 Employee

A node creating a tree does not really imply a one-to-one relationship, but rather a one-to-many relationship.

In those terms, your Employee table can have a column that represents the ID of the node each entity in it belongs to.

In your DAO, you should then

  • pass the Employee and Node objects you want connected as parameters to your method,
  • look up the Node object's ID in the database by finding its corresponding entity,
  • and create the employee entity using the data from the object and the fetched Node ID.

Indeed, you should be more specific in your question, though.

EDIT based on comment below:

If your Node table represents the tree, and you want each Node to have a one-to-one relationship with Employee , it depends on which references are important to you.

  1. You want to be able to reference the employee that belongs to a node (probably).
  2. You want to find which node the employee belongs to (less likely, but possibly).

If you need only number 1, then you will have the ID of the employee in your Node entity. If you need both, then you can also put the ID of the Node in your Employee entity.

The logic of the DAO method described above is still applicable.

Say you have one to one association between employee and employee details.

Employee(Data Object)------>Employee Table
Employee Detail(Data Object)------>Employee Details Table

Employee Details is having the column employee id which is foreign key to Employee table.

Now you want to persist Employee. First you will persist Employee object and get its primary key. Now populate the property employeeId of Employee Detail with primary key Of Employee table.Now Persist the Employee Detail object.

To load the both the entities in single go, use inner join between Employee and Employee Details Table

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM