I have an abstract class annotated with @MappedSuperClass
. There are around 15 entities that extend this abstract class (having 15 corresponding tables in the database). The 15 entities all have the same attributes that are inherited from the abstract super class.
I have created a repository as below for the abstract class:
@NoRepositoryBean
public interface AbstractRepository <T extends AbstractClass, E extends Serializable>
extends PagingAndSortingRepository<T, Serializable> {
.....some methods here
}
The 15 entities/tables store some data (data pertaining to 15 separate equipment). Based on the equipment selected, the data from that table is to be retrieved. Will I have to create 15 separate repositories for the 15 concrete entities or is there any way to get the specific entity for the equipment selected using only the abstract repository? If repositories need to be created for each concrete entity, how to get the right repository for the specific equipment call? (store the table name and repository class in a map that gets created on startup of the application perhaps?)
JPA Inheritence Overview Inheritence is a key feature of object-oriented programming language in which a child class can acquire the properties of its parent class. This feature enhances reusability of the code. The relational database doesn't support the mechanism of inheritance.
Crud Repository doesn't provide methods for implementing pagination and sorting. JpaRepository ties your repositories to the JPA persistence technology so it should be avoided. We should use CrudRepository or PagingAndSortingRepository depending on whether you need sorting and paging or not.
Single Table. The single table strategy maps all entities of the inheritance structure to the same database table. This approach makes polymorphic queries very efficient and provides the best performance.
There are three inheritance strategies defined from the InheritanceType enum, SINGLE_TABLE , TABLE_PER_CLASS and JOINED . Single table inheritance is the default, and table per class is an optional feature of the JPA spec, so not all providers may support it.
You will have to create repository for each class. However you can keep your methods in the abstract. You'll need to provide @Query
on each of the methods and use SpeL(Spring Expression Language) to add the type to the queries.
@NoRepositoryBean
public interface AbstractRepository<T extends AbstractEquipment>
extends CrudRepository<T, Long>{
@Query("select e from #{#entityName} as e from equipment where e.name = equipmentName")
T findEquipmentByName(String equipmentName);
}
Then extend like the following
@Transactional
public interface SpecialEquipmentRepo extends AbstractRepository<SpecialEquipment,Long>{
}
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