Completing the Morphia/MongoDB example code

hegsie picture hegsie · Aug 24, 2013 · Viewed 9.2k times · Source

I've been trying to get the example code from the Morphia Website working with very little success, I was wondering why the following code snippet fails?

public class DBUtil {
    private static Mongo mongo;
    private static Datastore ds;
    private static Morphia morphia;

    public static void main(String[] args) {
        try {
            mongo = new MongoClient(new ServerAddress(Consts.DatabaseHost,
                    Consts.DatabasePort));

            morphia = new Morphia();

            morphia.map(Employee.class);

            ds = morphia.createDatastore(mongo, Consts.DatabaseName);

            DB db = Mongo.connect(new DBAddress(Consts.DatabaseHost,
                    Consts.DatabasePort, Consts.DatabaseName));

            ds.save(new Employee("Mister", "GOD", null, 0));

            // get an employee without a manager
            Employee boss = ds.find(Employee.class).field("manager")
                    .equal(null).get();

            Key<Employee> scottsKey = ds.save(new Employee("Scott",
                    "Hernandez", ds.getKey(boss), 150 * 1000));

            // add Scott as an employee of his manager
            UpdateResults<Employee> res = ds.update(
                    boss,
                    ds.createUpdateOperations(Employee.class).add("underlings",
                            scottsKey));

            // get Scott's boss; the same as the one above.
            Employee scottsBoss = ds.find(Employee.class)
                    .filter("underlings", scottsKey).get();

            for (Employee e : ds.find(Employee.class, "manager", boss))
                    System.out.println(e);

            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            }
        }
    }

when using the following for the employee class?

@Entity("employees")
class Employee {
  public Employee(String firstName, String lastName, Object object, int i) {
      this.firstName = firstName;
      this.lastName = lastName;
      manager = new Key<Employee>(Employee.class, object);
    }

  // auto-generated, if not set (see ObjectId)
  @Id ObjectId id;

  // value types are automatically persisted
  String firstName, lastName;

  // only non-null values are stored
  Long salary = null;

  // by default fields are @Embedded
  Address address;

  //references can be saved without automatic loading
  Key<Employee> manager;

  //refs are stored**, and loaded automatically
  @Reference List<Employee> underlings = new ArrayList<Employee>();

  // stored in one binary field
  //@Serialized EncryptedReviews;

  //fields can be renamed
  @Property("started") Date startDate;
  @Property("left") Date endDate;

  //fields can be indexed for better performance
  @Indexed boolean active = false;

  //fields can loaded, but not saved
  @NotSaved String readButNotStored;

  //fields can be ignored (no load/save)
  @Transient int notStored;

  //not @Transient, will be ignored by Serialization/GWT for example.
  transient boolean stored = true;
}

However when use the above code, the 'get an employee without a manager' line fails to locate anything and the update operation throws an exception. Any help would be appreciated?

Answer

xeraa picture xeraa · Aug 24, 2013
  1. I think it should be Employee boss = ds.find(Employee.class).field("manager").doesNotExist().get();

  2. If I'm not mistaken, entities should have a no-args constructor.

PS: If you want to get started with a complete project quickly, you might want to take a look at https://github.com/xeraa/mongouk2011