2015-01-12 18 views
0

大家好,我有以下表 如何將現有的ID來將其設置爲另一個表將其添加爲外鍵

 

root(id,fromCity,toCity) id-primary 

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

在Html頁面我有下拉列表「CityFrom」和「 CityTo」,車輛 所以在servlet的我越來越CityFrom CityTo車輛細節的文本框..

 
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

所以每次我檢查了紮根的時間存在,並稱ID車輛ü唱休眠..我覺得這是硬編碼

是否有任何任何其他的Hibernate,它能自動rootId根表搜索,並將其設置在車輛表

回答

0

沒有這樣做,使用Hibernate的方法,但你正走在正確的道路上。

我假設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 
+0

tq @Zeus。我只是試着用你的代碼,這裏有一個問題..根Root pojo類(bean類)我沒有設置任何自動生成的id(即@GeneratedValue)..所以保存新的ROOT,如果我設置null爲ID(主鍵),那麼它不會保存,並給我的錯誤,該ID必須手動分配..你能解決這個問題.. –

+0

你可以發佈你的代碼的問題。即實體和保存的地方? – Zeus

相關問題