Fix delete()function

Let’s have a look on the code in DataStore class (in the core).

 /**
         * Deletes the given object and returns the object if successful
         * @param The object to be deleted
         * @return The object being deleted
         */
        public <T> T delete(T aTNG){
                // Please see Wiki for more information on the ServerConfiguration.
                ClientConfiguration config = Db4oClientServer.newClientConfiguration();
                config.common().reflectWith(new JdkReflector(Thread.currentThread().getContextClassLoader()));

                logger.log(Level.FINE, "Database Delete Attempt...");
                //ObjectContainer client = server.openClient();
                ObjectSet<T> result = theDB.queryByExample(aTNG);
                T found = (T) result.next(); //<--- will send out exception:java.lang.IllegalStateException
                                                             //if "result" is empty.
                theDB.delete(found);
                theDB.commit();

                logger.log(Level.FINE, "Database Delete Success!");
                //return "Deleted "+aTNG;
                return found;

        }

Problem Analysis: 

In this term, many groups used Calendar object to store date information. However, it seems that calendar(or say GregorianCalendar) cannot be parsed and compared in db4o database.This makes queryByExample() method cannot locate the data we find. So if we pass a commitment, which we wanna delete from the database, to this method the  ObjectSet<T> result = theDB.queryByExample(aTNG);, it cannot find the one in the database and return an empty result collection. Then when we use .next() method on an empty collection, we will get errors. This is the reason why we pass the thing we wanna delete to the database, and the database can’t delete it and give us an error.

Solution: 

Since CalendarItem have a unique id. We just make a null CalendarItem(eg. CalendarItem(null,null,null)) and set it’s id to the one we wanna delete, and pass it to the delete method in the DataStore.

e.g:

public boolean deleteEntity(Session s, String id) throws WPISuiteException{

ensureRole(s, Role.ADMIN);

Commitment oldComm = new Commitment(null,null,null);

oldComm.setId(Integer.parseInt(id));

Commitment deletedComm = db.delete(oldComm);

if (deletedComm != null){

System.out.println("Here is deletEntity method. ---> delete Succesfull");

return true; // the deletion was successful

}   

System.out.println("Here is deletEntity method. ---> delete Fail");

return false; // The deletion was unsuccessful

}

 

Details:

1.queryByExample is the same as get() (deprecated) method  in the db4o.

Reference: http://www.db4o.com/about/productinformation/resources/db4o-6.3-tutorial-java.pdf

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注