jantobola
jantobola

Reputation: 688

Spring data - domain object inheritance and generic 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 which allows me to get Log's childs.

Can I do teoretically 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);

Exist any other approaches to do what I described?

Upvotes: 6

Views: 1289

Answers (2)

membersound
membersound

Reputation: 86747

You could also implement it using #{#entityName}:

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

Upvotes: 1

axtavt
axtavt

Reputation: 242686

I don't think it's possible out of the box (especially given 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();
}

Upvotes: 2

Related Questions