mongo多态保存
博客专区 > go4it 的博客 > 博客详情
mongo多态保存
go4it 发表于1年前
mongo多态保存
  • 发表于 1年前
  • 阅读 16
  • 收藏 0
  • 点赞 0
  • 评论 0

##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.patterncat.demo.model.Org",
    "name" : "tech",
    "employees" : [ 
        {
            "mobile" : "15909898989",
            "name" : "worker",
            "_class" : "com.patterncat.demo.model.Worker"
        }, 
        {
            "address" : "fj",
            "title" : "vp",
            "name" : "leader",
            "_class" : "com.patterncat.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

标签: MongoDB
共有 人打赏支持
粉丝 15
博文 428
码字总数 215856
×
go4it
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: