Spring data - inheritance of domain objects and common methods

I have some domain objects:

@Entity public class Log { } @Entity public class LogLetter extends Log { } @Entity public class LogAction extends Log { } 

and I want to have only one repository that allows me to get children of the journal.

Can I do something like this?

 public interface LogRepository extends CrudRepository<Log, Long> { @Query("select from ?1) public <T> List<T> getLog(Class<T> clazz); } 

and call this method:

 List<LogLetter> logLetters = getLog(LogLetters.class); 

Are there any other approaches to what I described?

+6
source share
2 answers

I do not think this is possible out of the box (especially considering the fact that you cannot use parameters in from ), but you can implement it as a custom method (see 1.4. Custom Implementations ):

 public <T> List<T> getLog(Class<T> clazz) { return em.createQuery("from " + clazz.getSimpleName()).getResultList(); } 
+2
source

You can also implement it with #{#entityName} :

 @Query("SELECT o FROM #{#entityName} o where o.attribute1=:attribute1") Page<T> findByAttribute1Custom(@Param("attribute1") String attribute1, Pageable pageable); 
+1
source

Source: https://habr.com/ru/post/920020/


All Articles