0
我正在使用Google App Engine並將Google的數據存儲接口用於數據庫。 我的問題是這樣的,我有以下代碼:我有一個網絡對象,如果它存在數據庫上,我想更新它,或者如果它是第一次創建。 。爲此,我必須捕捉一個異常並重復相同的代碼兩次 - 它看起來很醜陋,多餘,讓我覺得我做錯了什麼。 第二件讓我感到奇怪的事情是,我沒有辦法想到將對象複製到實體中,反之亦然。我希望自己實現這個嗎?對每個屬性使用setProperty或getProperty是非常不容易的......我只是想知道爲什麼沒有objectToEntity方法或類似的東西。Google App Engine數據存儲困難
這是我的代碼目前的樣子......
try {
Entity network=datastore.get(KeyFactory.stringToKey(networks.get(i)._ipDigits));
//If I get here no exception was thrown - entity already exists on db.
Network contextNet= //fetch the network object from servlet context ...
network.setProperty("ip", contextNet._ip); //update the fields using setProperty - no better way??
network.setProperty("offlineUsers",contextNet._offlineUsers);
datastore.put(network);
}
//Entity doesn't exist , create a new entity and save it (while repeating the same code)...
catch (EntityNotFoundException e) {
Entity network=new Entity("network",Long.parseLong(networks.get(i)._ipDigits));
Network contextNet= // ...fetch the network object from servlet context
network.setProperty("ip", contextNet._ip);
network.setProperty("offlineUsers",contextNet._offlineUsers);
datastore.put(network);
}
謝謝彼得! – 2012-01-16 05:55:44