2017-07-26 54 views
0

由于某些原因,我的Mongo DB只是创建一个属于这些文档的ID,而不是其他属性。刚刚保存的Java MongoDB ID

我有一个Spring @Repository:

@Repository 
public class BeerRepository { 

    public void createBeer(final BeerDTO beerDTO) { 

     Mongo mongo = new Mongo("localhost", 27017); 
     DB db = mongo.getDB("beers"); 

     DBCollection beerCollection = db.getCollection(BeerDTO.COLLECTION_NAME); 

     beerCollection.insert(beerDTO); 
//  System.err.println(beerCollection.findOne()); 
    } 
} 

和一个简单的POJO,没有别的:

@Document 
public class BeerDTO extends BasicDBObject { 

    private static final long serialVersionUID = 1235041607375829595L; 
    public static final String COLLECTION_NAME = "Beers"; 

    @Field("id") 
    private String id; 

    @Field("name") 
    private String name; 

    @Field("abv") 
    private int abv; //alcohol by volume 

    public BeerDTO(String id, String name, int abv) { 
     this.id = id; 
     this.name = name; 
     this.abv = abv; 
    } 

}

然而,这是蒙戈越来越唯一:

enter image description here

非常感谢!

+0

也许它可以为你明显,但是,你有没有设置插入之前beerDTO所有领域?那些字段不是null? – MinMiguelM

+0

感谢您的评论,但的确,这是我检查的第一件事。 DTO包含数据。 – dev

回答

0

我改变了做法为createBeer在回购和它的工作:

public void createBeer(final BeerDTO beerDTO) { 

     MongoClient mongoClient = new MongoClient(); 
     DB database = mongoClient.getDB("beers"); 
     DBCollection beerCollection = database.getCollection(BeerDTO.COLLECTION_NAME); 

     DBObject beer = new BasicDBObject("id", beerDTO.getId()) 
       .append("name", beerDTO.getName()) 
       .append("abv", beerDTO.getAbv()); 

     beerCollection.insert(beer); 
    }