Search code examples
javamongodbmavenmorphianosql

Morphia with MongoDB connection


I have running MongoDB server, created test1 database with collection called zips. (taken from http://media.mongodb.org/zips.json). Now I want to read it from my application using Morphia.

following morphia tutorial(https://github.com/mongodb/morphia/wiki/GettingStarted): I created maven project, and upadated dependencies(https://github.com/mongodb/morphia/wiki/Dependencies). now my project contain only entity class and main. Entity class:

package com.mycompany.morphia;

import com.sun.corba.se.spi.ior.ObjectId;
import org.mongodb.morphia.annotationsEntity;
import org.mongodb.morphia.annotations.Id;

@Entity
public class MyEntity {
     @Id String _id; //maybe ObjectId ?
  String city;
  Object loc;
  Integer pop;
  String state;

}

and main class

package com.mycompany.morphia;

import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import java.io.IOException;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;

public class App 
{
    public static void main( String[] args ) throws IOException
    {
        MongoClient m = new MongoClient("localhost", 27017);
        Datastore ds = new Morphia().createDatastore(m, "test1");
        MyEntity e = ds.find(MyEntity.class).get();
        System.out.println( e.city.toString());
        System.in.read();
    }
 }

Still while debugging I got null. I don't know how to check if I'm connected to my db, and how to properly query it.


Solution

  • The problem was in my @Entity

    public Object loc;
    

    Object type caused the problem. I simply removed it.