I've two entities Person, Employee and Employee1. I want to implement entities inheritance in Spring Data MongoDB. Like in Spring Data JPA, what are the equivalent annotations for @Inheritance and @PrimaryKeyJoinColumn in Spring Data MongoDB. Right now, I've implemented something like this:
interface Person {
String getId();
void setId(String id);
String getName();
void getName(String name);
}
@Document(collection = "person")
class PersonImpl implements Person {
@Id
String id;
// Getters and setters
// Constructors, equals, hashcode and toString methods
}
interface Employee extends Person {
int getNumberOfDependents();
void getNumberOfDependents(int numberOfDependents);
}
@Document(collection = "employee")
class EmployeeImpl extends PersonImpl implements Employee {
// Getters and setters
// Constructors, equals, hashcode and toString methods
}
interface Employee1 extends Person {
int getNumberOfDependents();
void getNumberOfDependents(int numberOfDependents);
}
@Document(collection = "employee1")
class Employee1Impl extends PersonImpl implements Employee1 {
// Getters and setters
// Constructors, equals, hashcode and toString methods
}
Repository structure:
public interface PersonRepository extends MongoRepository<Person, String> {
}
public interface EmployeeRepository extends MongoRepository<Employee, String> {
}
public interface Employee1Repository extends MongoRepository<Employee1, String> {
}
I'm saving the Person object first and then taking the ID of it and creating an Employee object with the same ID and saving it. This creates new object and hence I'm losing all the Person object stuff. I also feel that I've to get the NoRepositoryBean implemented also. I'm confused. Please help.
Here is one approach:
@Document(collection = "person")
class Person {
@Id
String id;
// Getters and setters
// Constructors, equals, hashcode and toString methods
}
Note that the collection field refers to "person" and not to "employee"
@Document(collection = "person")
class Employee extends Person {
String jobTitle;
// Getters and setters
// Constructors, equals, hashcode and toString methods
}
In this method you do not need to create a repository for each derived class
@Repository
public interface PersonRepository extends MongoRepository<Person, String> {}
Code example:
@Autowired
private PersonRepository personRepo;
public void test() {
Employee employee = new Employee("1", "teacher")
personRepo.save(employee)
Optional<Person> optionalPerson = personRepo.findById("1");
Employee employeeFromDb;
if (optionalPerson.isPresent()) {
employeeFromDb = (Employee)optionalPerson.get()
}
else {
// could not find in db
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With