2016-05-12 64 views
0

我想要做一個簡單的findOne()使用嗎啡。我的代碼如下:Morphia映射與我的JAVA類

public static void main(String[] args) 
{ 
    MongoClient client = new MongoClient(); 
    Morphia morphia = new Morphia(); 
    morphia.map(Restaurant_M.class); 
    Datastore ds = morphia.createDatastore(client, "test"); 
    System.out.println(ds.find(Restaurant_M.class).get()); 
    client.close(); 
} 

我得到一個null打印出來。我無法找到發生了什麼問題。有人能指引我朝着正確的方向嗎?謝謝。

編輯 採集格式

{ 
    "_id" : ObjectId("572eb5df1d739cc73c21f953"), 
    "address" : { 
      "building" : "469", 
      "coord" : [ 
        -73.961704, 
        40.662942 
      ], 
      "street" : "Flatbush Avenue", 
      "zipcode" : "11225" 
    }, 
    "borough" : "Brooklyn", 
    "cuisine" : "Hamburgers", 
    "grades" : [ 
      { 
        "date" : ISODate("2014-12-30T00:00:00Z"), 
        "grade" : "A", 
        "score" : 8 
      }, 
      { 
        "date" : ISODate("2014-07-01T00:00:00Z"), 
        "grade" : "B", 
        "score" : 23 
      }, 
      { 
        "date" : ISODate("2013-04-30T00:00:00Z"), 
        "grade" : "A", 
        "score" : 12 
      }, 
      { 
        "date" : ISODate("2012-05-08T00:00:00Z"), 
        "grade" : "A", 
        "score" : 12 
      } 
    ], 
    "name" : "Wendy'S", 
    "restaurant_id" : "30112340" 
} 

@Entity類

@Entity("restaurants") 
public class Restaurant_M 
{ 
    @Id 
    public ObjectId _id; 
    @Property("borough") 
    public String town; 
    public String cuisine; 
    public String name; 
    @Property("restaurant_id") 
    public String r_id; 

回答

0

我犯了一個DBO執行如下命令:

public Restaurant_M getByID (String id) 
{ 
    Query<Restaurant_M> query = createQuery().field("cuisine").equal(id); 
    return query.get(); 
} 

和更新的主要方法如下,它的工作

public static void main(String[] args) 
{ 
    MongoClient client = new MongoClient("127.0.0.1:27017"); 
    Morphia morphia = new Morphia(); 
    Datastore ds = morphia.createDatastore(client, "test"); 
    RestaurantDAO rdao = new RestaurantDAOImpl(Restaurant_M.class, ds); 
    Restaurant_M r = rdao.getByID("Hamburgers"); 
    System.out.println(r); 

    r = ds.find(Restaurant_M.class).get(); 
    System.out.println (r); 

} 
0

的問題是,你不給大約需要實體 你可以使用映射到實體的所有信息: dt.getCollection(Restaurant_M.class);然後使用DBObject 或 dt.createQuery(Restaurant_M.class).field(「」)。equal(「to specify」)。get;

+0

我已經編輯附加信息的問題。我想我提供了有關該實體的完整映射信息 – Newton