I'm working with this tutorial to handle entities inheritance. I have person and company entities that extends the User entity.
@Entity
@Inheritance
public abstract class User {
@Id
private long id;
@NotNull
private String email;
// getters and settres
}
@Entity
public class Person extends User {
private int age;
// getters and settres and other attributs
}
@Entity
public class Company extends User {
private String companyName;
// getters and settres and other attribut
}
then UserRpository ,PersonRepository and Company Repository that extends the UserBaseRepository.
@NoRepositoryBean
public interface UserBaseRepository<T extends User>
extends CrudRepository<T, Long> {
public T findByEmail(String email);
}
@Transactional
public interface UserRepository extends UserBaseRepository<User> { }
@Transactional
public interface PersonRepository extends UserBaseRepository<Person> { }
@Transactional
public interface CompanyRepository extends UserBaseRepository<Company> { }
the probleme is when calling personRepository.findAll() to get all persons , in result i got also companies.
Your issue is with the "Discriminator" column that JPA requires. You are using the
@Inheritance
annotation and by default that will use theInheritanceType.SINGLE_TABLE
strategy. That means the following:Person
andCompany
will go into a single table.I did the following to make it work for your use case:
Entities:
DB Schema:
Some test data:
Repositories:
JUnit Tests:
The above tests pass. That indicates JPA now utilizes the discriminator correctly to retrieve the required records.
For JPA related theory for your question, see this link.