5. Structured objects


It's time to extend our business domain with another class and see how db4o handles object interrelations. Let's give our pilot a vehicle.

package com.db4odoc.f1.chapter2;
public class Car {   
    private String model;
    private Pilot pilot;
    
    public Car(String model) {
        this.model=model;
        this.pilot=null;
    }
      
    public Pilot getPilot() {
        return pilot;
    }
    
    public void setPilot(Pilot pilot) {
        this.pilot = pilot;
    }
    
    public String getModel() {
        return model;
    }
    
    public String toString() {
        return model+"["+pilot+"]";
    }
}



    5.1. Storing structured objects


    To store a car with its pilot, we just call #store() on our top level object, the car. The pilot will be stored implicitly.

    // storeFirstCar
    Car car1 = new Car("Ferrari");
    Pilot pilot1 = new Pilot("Michael Schumacher", 100);
    car1.setPilot(pilot1);
    db.store(car1);


    Of course, we need some competition here. This time we explicitly store the pilot before entering the car - this makes no difference.

    // storeSecondCar
    Pilot pilot2 = new Pilot("Rubens Barrichello", 99);
    db.store(pilot2);
    Car car2 = new Car("BMW");
    car2.setPilot(pilot2);
    db.store(car2);



    5.2. Retrieving structured objects



      5.2.1. QBE


      To retrieve all cars, we simply provide a 'blank' prototype.

      // retrieveAllCarsQBE
      Car proto = new Car(null);
      ObjectSet result = db.queryByExample(proto);
      listResult(result);


      We can also query for all pilots, of course.

      // retrieveAllPilotsQBE
      Pilot proto = new Pilot(null, 0);
      ObjectSet result = db.queryByExample(proto);
      listResult(result);


      Now let's initialize our prototype to specify all cars driven by Rubens Barrichello.

      // retrieveCarByPilotQBE
      Pilot pilotproto = new Pilot("Rubens Barrichello", 0);
      Car carproto = new Car(null);
      carproto.setPilot(pilotproto);
      ObjectSet result = db.queryByExample(carproto);
      listResult(result);


      What about retrieving a pilot by car? We simply don't need that - if we already know the car, we can simply access the pilot field directly.


      5.2.2. Native Queries


      Using native queries with constraints on deep structured objects is straightforward, you can do it just like you would in plain other code.

      Let's constrain our query to only those cars driven by a Pilot with a specific name:


      // retrieveCarsByPilotNameNative
      final String pilotName = "Rubens Barrichello";
      List<Car> results = db.query(new Predicate<Car>() {
          public boolean match(Car car) {
              return car.getPilot().getName().equals(pilotName);
          }
      });
      listResult(results);






      5.2.3. SODA Query API


      In order to use SODA for querying for a car given its pilot's name we have to descend two levels into our query.

      // retrieveCarByPilotNameQuery
      Query query = db.query();
      query.constrain(Car.class);
      query.descend("pilot").descend("name").constrain("Rubens Barrichello");
      ObjectSet result = query.execute();
      listResult(result);


      We can also constrain the pilot field with a prototype to achieve the same result.

      // retrieveCarByPilotProtoQuery
      Query query = db.query();
      query.constrain(Car.class);
      Pilot proto = new Pilot("Rubens Barrichello", 0);
      query.descend("pilot").constrain(proto);
      ObjectSet result = query.execute();
      listResult(result);


      We have seen that descending into a query provides us with another query. Starting out from a query root we can descend in multiple directions. In practice this is the same as ascending from one child to a parent and descending to another child. We can conclude that queries turn one-directional references in our objects into true relations. Here is an example that queries for "a Pilot that is being referenced by a Car, where the Car model is 'Ferrari'":

      // retrievePilotByCarModelQuery
      Query carquery = db.query();
      carquery.constrain(Car.class);
      carquery.descend("model").constrain("Ferrari");
      Query pilotquery = carquery.descend("pilot");
      ObjectSet result = pilotquery.execute();
      listResult(result);






    5.3. Updating structured objects


    To update structured objects in db4o, we simply call #store() on them again.

    // updateCar
    List<Car> result = db.query(new Predicate<Car>() {
        public boolean match(Car car) {
            return car.getModel().equals("Ferrari");
        }
    });
    Car found = (Car) result.get(0);
    found.setPilot(new Pilot("Somebody else", 0));
    db.store(found);
    result = db.query(new Predicate<Car>() {
        public boolean match(Car car) {
            return car.getModel().equals("Ferrari");
        }
    });
    listResult(result);


    Let's modify the pilot, too.

    // updatePilotSingleSession
    List<Car> result = db.query(new Predicate<Car>() {
        public boolean match(Car car) {
            return car.getModel().equals("Ferrari");
        }
    });
    Car found = result.get(0);
    found.getPilot().addPoints(1);
    db.store(found);
    result = db.query(new Predicate<Car>() {
        public boolean match(Car car) {
            return car.getModel().equals("Ferrari");
        }
    });
    listResult(result);


    Nice and easy, isn't it? But wait, there's something evil lurking right behind the corner. Let's see what happens if we split this task in two separate db4o sessions: In the first we modify our pilot and update his car:

    // updatePilotSeparateSessionsPart1
    List<Car> result = db.query(new Predicate<Car>() {
        public boolean match(Car car) {
            return car.getModel().equals("Ferrari");
        }
    });
    Car found = result.get(0);
    found.getPilot().addPoints(1);
    db.store(found);


    And in the second, we'll double-check our modification:

    // updatePilotSeparateSessionsPart2
    List<Car> result = db.query(new Predicate<Car>() {
        public boolean match(Car car) {
            return car.getModel().equals("Ferrari");
        }
    });
    listResult(result);


    Looks like we're in trouble: Why did the Pilot's points not change? What's happening here and what can we do to fix it?


      5.3.1. Update depth


      Imagine a complex object with many members that have many members themselves. When updating this object, db4o would have to update all its children, grandchildren, etc. This poses a severe performance penalty and will not be necessary in most cases - sometimes, however, it will.

      So, in our previous update example, we were modifying the Pilot child of a Car object. When we saved the change, we told db4o to save our Car object and assumed that the modified Pilot would be updated. But we were modifying and saving in the same manner as we were in the first update sample, so why did it work before? The first time we made the modification, db4o never actually had to retrieve the modified Pilot it returned the same one that was still in memory that we modified, but it never actually updated the database. The fact that we saw the modified value was, in fact, a bug. Restarting the application would show that the value was unchanged.

      To be able to handle this dilemma as flexible as possible, db4o introduces the concept of update depth to control how deep an object's member tree will be traversed on update. The default update depth for all objects is 1, meaning that only primitive and String members will be updated, but changes in object members will not be reflected.

      db4o provides means to control update depth with very fine granularity. For our current problem we'll advise db4o to update the full graph for Car objects by setting  #cascadeOnUpdate()  for this class accordingly.

      // updatePilotSeparateSessionsImprovedPart1
      EmbeddedConfiguration config = Db4oEmbedded.newConfiguration();
      config.common().objectClass(Car.class).cascadeOnUpdate(true);
      ObjectContainer db = Db4oEmbedded.openFile(config, DB4OFILENAME);
      List<Car> result = db.query(new Predicate<Car>() {
          public boolean match(Car car) {
              return car.getModel().equals("Ferrari");
          }
      });
      if (result.size() > 0) {
          Car found = result.get(0);
          found.getPilot().addPoints(1);
          db.store(found);
      }
      db.close();


      // updatePilotSeparateSessionsImprovedPart2
      ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded
              .newConfiguration(), DB4OFILENAME);
      List<Car> result = db.query(new Predicate<Car>() {
          public boolean match(Car car) {
              return car.getModel().equals("Ferrari");
          }
      });
      Car car = result.get(0);
      listResult(result);
      db.close();


      This looks much better.

      Note that container configuration must be passed when the container is opened.

      We'll cover update depth as well as other issues with complex object graphs and the respective db4o configuration options in more detail in a later chapter.


    5.4. Deleting structured objects


    As we have already seen, we call #delete() on objects to get rid of them.

    // deleteFlat
    List<Car> result = db.query(new Predicate<Car>() {
        public boolean match(Car car) {
            return car.getModel().equals("Ferrari");
        }
    });
    Car found = result.get(0);
    db.delete(found);
    result = db.queryByExample(new Car(null));
    listResult(result);


    Fine, the car is gone. What about the pilots?

    // retrieveAllPilotsQBE
    Pilot proto = new Pilot(null, 0);
    ObjectSet result = db.queryByExample(proto);
    listResult(result);


    Ok, this is no real surprise - we don't expect a pilot to vanish when his car is disposed of in real life, too. But what if we want an object's children to be thrown away on deletion, too?


      5.4.1. Recursive deletion


      You may already suspect that the problem of recursive deletion (and perhaps its solution, too) is quite similar to our little update problem, and you're right. Let's configure db4o to delete a car's pilot, too, when the car is deleted.

      // deleteDeep
      EmbeddedConfiguration config = Db4oEmbedded.newConfiguration();
      config.common().objectClass(Car.class).cascadeOnDelete(true);
      ObjectContainer db = Db4oEmbedded.openFile(config, DB4OFILENAME);
      List<Car> result = db.query(new Predicate<Car>() {
          public boolean match(Car car) {
              return car.getModel().equals("BMW");
          }
      });
      if (result.size() > 0) {
          Car found = result.get(0);
          db.delete(found);
      }
      result = db.query(new Predicate<Car>() {
          public boolean match(Car car) {
              return true;
          }
      });
      listResult(result);
      db.close();


      Again: Note that configuration should be passed to the call opening ObjectContainer.

      Let's have a look at our pilots again.

      // retrieveAllPilots
      Pilot proto = new Pilot(null, 0);
      ObjectSet result = db.queryByExample(proto);
      listResult(result);



      5.4.2. Recursive deletion revisited


      But wait - what happens if the children of a removed object are still referenced by other objects?

      // deleteDeepRevisited
      EmbeddedConfiguration config = Db4oEmbedded.newConfiguration();
      config.common().objectClass(Car.class).cascadeOnDelete(true);
      ObjectContainer db = Db4oEmbedded.openFile(config, DB4OFILENAME);
      ObjectSet<Pilot> result = db.query(new Predicate<Pilot>() {
          public boolean match(Pilot pilot) {
              return pilot.getName().equals("Michael Schumacher");
          }
      });
      if (!result.hasNext()) {
          System.out.println("Pilot not found!");
          db.close();
          return;
      }
      Pilot pilot = (Pilot) result.next();
      Car car1 = new Car("Ferrari");
      Car car2 = new Car("BMW");
      car1.setPilot(pilot);
      car2.setPilot(pilot);
      db.store(car1);
      db.store(car2);
      db.delete(car2);
      List<Car> cars = db.query(new Predicate<Car>() {
          public boolean match(Car car) {
              return true;
          }
      });
      listResult(cars);
      db.close();


      // retrieveAllPilots
      Pilot proto = new Pilot(null, 0);
      ObjectSet result = db.queryByExample(proto);
      listResult(result);


      Houston, we have a problem - and there's no simple solution at hand. Currently db4o does not check whether objects to be deleted are referenced anywhere else, so please be very careful when using this feature.

      Let's clear our database for the next chapter.

      // deleteAll
      ObjectSet result=db.queryByExample(new Object());
      while(result.hasNext()) {
          db.delete(result.next());
      }



    5.5. Conclusion


    So much for object associations: We can hook into a root object and climb down its reference graph to specify queries. But what about multi-valued objects like arrays and collections? We will cover this in the next chapter .


    5.6. Full source


    package com.db4odoc.f1.chapter2;
    import com.db4o.Db4oEmbedded;
    import com.db4o.ObjectContainer;
    import com.db4o.ObjectSet;
    import com.db4o.config.EmbeddedConfiguration;
    import com.db4o.query.Predicate;
    import com.db4o.query.Query;
    import com.db4odoc.f1.Util;
    import java.io.File;
    import java.util.List;
    public class StructuredExample extends Util {
        final static String DB4OFILENAME = System.getProperty("user.home") + "/formula1.db4o";
        public static void main(String[] args) {
            new File(DB4OFILENAME).delete();
            ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded
                    .newConfiguration(), DB4OFILENAME);
            storeFirstCar(db);
            storeSecondCar(db);
            retrieveAllCarsQBE(db);
            retrieveAllPilotsQBE(db);
            retrieveCarByPilotQBE(db);
            retrieveCarByPilotNameQuery(db);
            retrieveCarByPilotProtoQuery(db);
            retrievePilotByCarModelQuery(db);
            updateCar(db);
            updatePilotSingleSession(db);
            updatePilotSeparateSessionsPart1(db);
            db.close();
            db = Db4oEmbedded.openFile(Db4oEmbedded
                    .newConfiguration(), DB4OFILENAME);
            updatePilotSeparateSessionsPart2(db);
            db.close();
            updatePilotSeparateSessionsImprovedPart1();
            updatePilotSeparateSessionsImprovedPart2();
            db = Db4oEmbedded.openFile(Db4oEmbedded
                    .newConfiguration(), DB4OFILENAME);
            deleteFlat(db);
            db.close();
            deleteDeep();
            deleteDeepRevisited();
        }
        public static void storeFirstCar(ObjectContainer db) {
            Car car1 = new Car("Ferrari");
            Pilot pilot1 = new Pilot("Michael Schumacher", 100);
            car1.setPilot(pilot1);
            db.store(car1);
        }
        public static void storeSecondCar(ObjectContainer db) {
            Pilot pilot2 = new Pilot("Rubens Barrichello", 99);
            db.store(pilot2);
            Car car2 = new Car("BMW");
            car2.setPilot(pilot2);
            db.store(car2);
        }
        public static void retrieveAllCarsQBE(ObjectContainer db) {
            Car proto = new Car(null);
            ObjectSet result = db.queryByExample(proto);
            listResult(result);
        }
        public static void retrieveAllPilotsQBE(ObjectContainer db) {
            Pilot proto = new Pilot(null, 0);
            ObjectSet result = db.queryByExample(proto);
            listResult(result);
        }
        public static void retrieveAllPilots(ObjectContainer db) {
            ObjectSet result = db.queryByExample(Pilot.class);
            listResult(result);
        }
        public static void retrieveCarByPilotQBE(ObjectContainer db) {
            Pilot pilotproto = new Pilot("Rubens Barrichello", 0);
            Car carproto = new Car(null);
            carproto.setPilot(pilotproto);
            ObjectSet result = db.queryByExample(carproto);
            listResult(result);
        }
        public static void retrieveCarByPilotNameQuery(ObjectContainer db) {
            Query query = db.query();
            query.constrain(Car.class);
            query.descend("pilot").descend("name").constrain("Rubens Barrichello");
            ObjectSet result = query.execute();
            listResult(result);
        }
        public static void retrieveCarByPilotProtoQuery(ObjectContainer db) {
            Query query = db.query();
            query.constrain(Car.class);
            Pilot proto = new Pilot("Rubens Barrichello", 0);
            query.descend("pilot").constrain(proto);
            ObjectSet result = query.execute();
            listResult(result);
        }
        public static void retrievePilotByCarModelQuery(ObjectContainer db) {
            Query carquery = db.query();
            carquery.constrain(Car.class);
            carquery.descend("model").constrain("Ferrari");
            Query pilotquery = carquery.descend("pilot");
            ObjectSet result = pilotquery.execute();
            listResult(result);
        }
        public static void retrieveAllPilotsNative(ObjectContainer db) {
            List<Pilot> results = db.query(new Predicate<Pilot>() {
                public boolean match(Pilot pilot) {
                    return true;
                }
            });
            listResult(results);
        }
        public static void retrieveAllCars(ObjectContainer db) {
            ObjectSet results = db.queryByExample(Car.class);
            listResult(results);
        }
        public static void retrieveCarsByPilotNameNative(ObjectContainer db) {
            final String pilotName = "Rubens Barrichello";
            List<Car> results = db.query(new Predicate<Car>() {
                public boolean match(Car car) {
                    return car.getPilot().getName().equals(pilotName);
                }
            });
            listResult(results);
        }
        public static void updateCar(ObjectContainer db) {
            List<Car> result = db.query(new Predicate<Car>() {
                public boolean match(Car car) {
                    return car.getModel().equals("Ferrari");
                }
            });
            Car found = (Car) result.get(0);
            found.setPilot(new Pilot("Somebody else", 0));
            db.store(found);
            result = db.query(new Predicate<Car>() {
                public boolean match(Car car) {
                    return car.getModel().equals("Ferrari");
                }
            });
            listResult(result);
        }
        public static void updatePilotSingleSession(ObjectContainer db) {
            List<Car> result = db.query(new Predicate<Car>() {
                public boolean match(Car car) {
                    return car.getModel().equals("Ferrari");
                }
            });
            Car found = result.get(0);
            found.getPilot().addPoints(1);
            db.store(found);
            result = db.query(new Predicate<Car>() {
                public boolean match(Car car) {
                    return car.getModel().equals("Ferrari");
                }
            });
            listResult(result);
        }
        public static void updatePilotSeparateSessionsPart1(ObjectContainer db) {
            List<Car> result = db.query(new Predicate<Car>() {
                public boolean match(Car car) {
                    return car.getModel().equals("Ferrari");
                }
            });
            Car found = result.get(0);
            found.getPilot().addPoints(1);
            db.store(found);
        }
        public static void updatePilotSeparateSessionsPart2(ObjectContainer db) {
            List<Car> result = db.query(new Predicate<Car>() {
                public boolean match(Car car) {
                    return car.getModel().equals("Ferrari");
                }
            });
            listResult(result);
        }
        public static void updatePilotSeparateSessionsImprovedPart1() {
            EmbeddedConfiguration config = Db4oEmbedded.newConfiguration();
            config.common().objectClass(Car.class).cascadeOnUpdate(true);
            ObjectContainer db = Db4oEmbedded.openFile(config, DB4OFILENAME);
            List<Car> result = db.query(new Predicate<Car>() {
                public boolean match(Car car) {
                    return car.getModel().equals("Ferrari");
                }
            });
            if (result.size() > 0) {
                Car found = result.get(0);
                found.getPilot().addPoints(1);
                db.store(found);
            }
            db.close();
        }
        public static void updatePilotSeparateSessionsImprovedPart2() {
            ObjectContainer db = Db4oEmbedded.openFile(Db4oEmbedded
                    .newConfiguration(), DB4OFILENAME);
            List<Car> result = db.query(new Predicate<Car>() {
                public boolean match(Car car) {
                    return car.getModel().equals("Ferrari");
                }
            });
            Car car = result.get(0);
            listResult(result);
            db.close();
        }
        public static void deleteFlat(ObjectContainer db) {
            List<Car> result = db.query(new Predicate<Car>() {
                public boolean match(Car car) {
                    return car.getModel().equals("Ferrari");
                }
            });
            Car found = result.get(0);
            db.delete(found);
            result = db.queryByExample(new Car(null));
            listResult(result);
        }
        public static void deleteDeep() {
            EmbeddedConfiguration config = Db4oEmbedded.newConfiguration();
            config.common().objectClass(Car.class).cascadeOnDelete(true);
            ObjectContainer db = Db4oEmbedded.openFile(config, DB4OFILENAME);
            List<Car> result = db.query(new Predicate<Car>() {
                public boolean match(Car car) {
                    return car.getModel().equals("BMW");
                }
            });
            if (result.size() > 0) {
                Car found = result.get(0);
                db.delete(found);
            }
            result = db.query(new Predicate<Car>() {
                public boolean match(Car car) {
                    return true;
                }
            });
            listResult(result);
            db.close();
        }
        public static void deleteDeepRevisited() {
            EmbeddedConfiguration config = Db4oEmbedded.newConfiguration();
            config.common().objectClass(Car.class).cascadeOnDelete(true);
            ObjectContainer db = Db4oEmbedded.openFile(config, DB4OFILENAME);
            ObjectSet<Pilot> result = db.query(new Predicate<Pilot>() {
                public boolean match(Pilot pilot) {
                    return pilot.getName().equals("Michael Schumacher");
                }
            });
            if (!result.hasNext()) {
                System.out.println("Pilot not found!");
                db.close();
                return;
            }
            Pilot pilot = (Pilot) result.next();
            Car car1 = new Car("Ferrari");
            Car car2 = new Car("BMW");
            car1.setPilot(pilot);
            car2.setPilot(pilot);
            db.store(car1);
            db.store(car2);
            db.delete(car2);
            List<Car> cars = db.query(new Predicate<Car>() {
                public boolean match(Car car) {
                    return true;
                }
            });
            listResult(cars);
            db.close();
        }
    }