简体   繁体   中英

Mapping hierarchial objects in MongoDB using Morphia

Let's say I have an entity in MongoDB which stores a list of employees.

@Entitiy
public class EmployeeList{
    @Embedded
    List<Employee> employeeList;
}

Employee is an abstract class with some properties.

public abstract class Employee{
    String name;
    String emailId;
}

There are different types of employees - Developer, Designer, HumanResource

class Developer extends Employee{
    String githubProfile;
}


class Designer extends Employee{
   String portfolio;
}


class HumanResource extends Employee{
   String department; 
}

If mongo contains a list of developers, designers and humanResource people, can Morphia map them to their corresponding classes? For example, if the db has the following data -

[{'name':'p1', 'emailId':'p1@x1", 'portfolio':'http://abc.co'},
{'name':'p2', 'emailId':'p2@x1", 'department':'finance'},
{'name':'p3', 'emailId':'p3@x1", 'githubProfile':'http://github.com/p3'}]

When this collections is mapped by Morphia onto EmployeeList entity, how do I make sure they are mapped to their corresponding classes?

When you are adding employees to the list then probably you would be doing something like below.

employeeList.add(new Developer(...))
employeeList.add(new Designer(...))
employeeList.add(new HumanResource(...))

Then save the entity in morphia and it should work.

PS: I have not tried this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM