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
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。