如何将现有Id设置为另一个表,将其添加为外键

时间:2015-01-12 13:26:37

标签: java hibernate

大家好我有以下表格


root(id,fromCity,toCity ) id-primary

Vehicle(id,number,rootId) id-prim , rootId-foreign(id in root table)

在Html页面中,我有“CityFrom”和“CityTo”的下拉列表,车辆的文本框 所以在servlet中我得到CityFrom CityTo Vehicle详细信息..

for every new request i have to see 
1. the route exist already in route table set rootId to vehicle table ..
2.If root not exist I have to add root to Root table then set that id in vehicle table

所以每次我检查root存在并使用Hibernate将该id添加到车辆中时我觉得这很难编码

Hibernate 中是否有任何替代方法会自动在根表中搜索rootId并将其设置为Vehicle table

1 个答案:

答案 0 :(得分:0)

使用hibernate无法做到这一点,但是你正走在正确的道路上。

我假设在joincolumns上使用 cascade = ALL

Query query = session.createQuery("from Root where fromCity = :from and toCity =:to ");
query.setParameter("from", "7277");
query.setParameter("to", "7277");

Root r = query.uniqueResult();

if(r==null){
     r = new Root(from,to);
}

vehicle.setRoot(r);
session.saveOrUpdate(r); //this will create vehicleId and root id if not present and sets the foreign key also for you