Org

public class Org {

    @Id
    private String id;

    private String name;

    private Set<Employee> employees;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Set<Employee> getEmployees() {
        return employees;
    }

    public void setEmployees(Set<Employee> employees) {
        this.employees = employees;
    }
}

employee

public abstract class Employee {

    protected String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

leader

public class Leader extends Employee{

    private String address;

    private String title;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

worker

public class Worker extends Employee{

    private String mobile;

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
}

保存实例

@Test
    public void testPolymorphic() {
        Org org = new Org();
        org.setName("tech");

        Leader leader = new Leader();
        leader.setName("leader");
        leader.setAddress("fj");
        leader.setTitle("vp");

        Worker worker = new Worker();
        worker.setName("worker");
        worker.setMobile("15909898989");

        Set<Employee> employees = new HashSet<>();
        employees.add(leader);
        employees.add(worker);

        org.setEmployees(employees);
        orgDao.save(org);
    }

mongo里的数据保存了class

{
    "_id" : ObjectId("57f635e0af7b3807e8101884"),
    "_class" : "com.codecraft.demo.model.Org",
    "name" : "tech",
    "employees" : [ 
        {
            "mobile" : "15909898989",
            "name" : "worker",
            "_class" : "com.codecraft.demo.model.Worker"
        }, 
        {
            "address" : "fj",
            "title" : "vp",
            "name" : "leader",
            "_class" : "com.codecraft.demo.model.Leader"
        }
    ]
}

取数据

@Test
    public void testFind(){
        Org org = orgDao.findOne("57f635e0af7b3807e8101884");
        Set<Employee> employees = org.getEmployees();
        for(Employee emp : employees){
            if(emp instanceof Leader){
                System.out.println(emp);
            }else if(emp instanceof Worker){
                System.out.println(emp);
            }
        }
    }

docs


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...