morphia(2)-添加

 

1、简单

@Test
public void add() throws Exception {
    final Employee em = new Employee("遥远2",50000.0);
    Key<Employee> key = datastore.save(em);
    Console.log("主键id={},{}",key.getId(),em.getId());
    
}

存储:

{
"_id" : ObjectId("5bced166dd00712bd429363e"),
"className" : "com.ebc.entity.Employee",
"name" : "遥远2",
"wage" : 50000
}

 


2、添加子集合

@Test
public void add2() throws Exception {
    Employee em = new Employee("zuoys",10000.0);
    
    final Employee e1 = new Employee("小弟1",2000.0);
    datastore.save(e1);
    final Employee e2 = new Employee("小弟2",3000.0);
    datastore.save(e2);
    //集合中的元素必须先保存
    List<Employee> emList = CollUtil.newArrayList();
    emList.add(e1);
    emList.add(e2);
    em.setDirectReports(emList);
    
    datastore.save(em);
    Console.log("主键id={}",em.getId());
}

存储:

/* 1 */
{
    "_id" : ObjectId("5bcef23890c1d9280c07128e"),
    "className" : "com.ebc.entity.Employee",
    "name" : "小弟1",
    "wage" : 2000
}

/* 2 */
{
    "_id" : ObjectId("5bcef23890c1d9280c07128f"),
    "className" : "com.ebc.entity.Employee",
    "name" : "小弟2",
    "wage" : 3000
}

/* 3 */
{
    "_id" : ObjectId("5bcef23890c1d9280c071290"),
    "className" : "com.ebc.entity.Employee",
    "name" : "zuoys",
    "directReports" : [ 
        {
            "$ref" : "employees",
            "$id" : ObjectId("5bcef23890c1d9280c07128e")
        }, 
        {
            "$ref" : "employees",
            "$id" : ObjectId("5bcef23890c1d9280c07128f")
        }
    ],
    "wage" : 10000
}

3、添加父

@Test
public void add3() throws Exception {
    Employee em = datastore.get(Employee.class, new ObjectId("5bcef23890c1d9280c071290"));
    final Employee e3 = new Employee("小弟3有父",22.0);
    e3.setManager(em);
    Key<Employee> key = datastore.save(e3);
    Console.log("主键id={}",key.getId());
}

存储:

/* 4 */
{
    "_id" : ObjectId("5bcef45d90c1d91d509941cd"),
    "className" : "com.ebc.entity.Employee",
    "name" : "小弟3有父",
    "manager" : {
        "$ref" : "employees",
        "$id" : ObjectId("5bcef23890c1d9280c071290")
    },
    "wage" : 22
}

 

posted @ 2018-10-30 09:31  遥远2  阅读(148)  评论(0编辑  收藏  举报