时间:2021-07-01 10:21:17 帮助过:39人阅读
Morphia配合mongoDB就如同Hibernate配合关系型数据库.所以可以认为Morphia在MongoDB的基础上面调用mongoDB的语法. 在java中直接调用Morphia的api会显得比较简单快捷. 1.加入mongoDB和Morphia的Jar包. //创建连接源Mongo mongo = null;try {mongo = new Mongo
Morphia配合mongoDB就如同Hibernate配合关系型数据库.所以可以认为Morphia在MongoDB的基础上面调用mongoDB的语法.
在java中直接调用Morphia的api会显得比较简单快捷.
1.加入mongoDB和Morphia的Jar包.
//创建连接源 Mongo mongo = null; try { mongo = new Mongo(); } catch (UnknownHostException e) { e.printStackTrace(); } Morphia morphia = new Morphia(); Datastore ds = morphia.createDatastore(mongo, "test"); //查找 for(User user:ds.find(User.class, "password", "admin")){ System.out.println(user); } System.out.println(ds.find(User.class, "password", "admin").get()); //插入 User user1 = new User("00018", "hello1", "hello1"); User user2 = new User("00019", "hello2", "hello2"); Listlist = new ArrayList<>(); list.add(user1); list.add(user2); ds.save(list); // 修改 Query query = ds.createQuery(User.class).field("uid").equal("00013"); UpdateOperations uo = ds.createUpdateOperations(User.class).set("password", "IDONTKONW").set("userName", "IDONTKONW"); ds.update(query, uo); /** * 删除 * */ // ds.delete(User.class, "00018"); Query query = ds.createQuery(User.class).field("userName").contains("t"); ds.delete(query);