简体   繁体   中英

One to many mapping on same table in hibernate

I'm not good in hibernate. I have a bad database design in which things are put together into one table. I want do one to many mapping on the same table.

My schema is as follows.

---------------------------------------------------------------------------------------
svc_id | svc_status| contract_no| contract_detail1| contract_detail2| contract_detail3
--------------------------------------------------------------------------------------
svc100 | enabled   | a1         | a1-pro1         | a1-pro2         | a1-pro3             
svc100 | enabled   | b1         | b1-pro1         | b1-pro2         | b1-pro3             
svc100 | enabled   | c1         | d1-pro1         | c1-pro2         | d1-pro3             
svc100 | enabled   | d1         | d1-pro1         | d1-pro2         | d1-pro3             
svc400 | disabled  | y1         | yyy-pro1        | yyy-pro2        | yyy-pro3           
svc400 | disabled  | z1         | z1-pro1         | z1-pro2         | z1-pro3      

The svc_status is always unique per svc_id. I want to have an 1-to-many hibernate mapping in which I can store the values into following (or similar) java bean.

 Class Service {
     serviceId; //svc100
     serviceStatus; //enabled
     Set<Contract> contracts; //list of all 'svc100' contracts
 }

 Class Contract {
     contract_no;
     contract_detail1;
     contract_detail2;
     contract_detail3;
 }

Please help.

Since you have a single table, having more than one mapped entity class doesn't make sense. You have two option here:

  1. Re-design your database schema in order to have two tables: service(svc_id, svc_status) and contract(contract_no, contract_detail1, contract_detail2, contract_detail3) .

  2. If 1. is not possible (I'm not sure which are the considerations for which you're tied to the poor design), you should create Service instances at the application level, based on the set of Contract instances (without making Service a mapped entity!!).

One-to-many relationships on the same table are allowed (so-called self-referencing tables) and can be easily mapped, but I don't see how they can serve your purpose.

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