简体   繁体   English

Spring数据 - 域对象继承和泛型方法

[英]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. 我想只有一个存储库,它允许我获取Log的孩子。

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? 是否存在任何其他方法来做我所描述的?

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 ): 我不认为它可以开箱即用(特别是考虑到你不能使用from参数),但你可以将它作为自定义方法实现(参见1.4。自定义实现 ):

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

You could also implement it using #{#entityName} : 您也可以使用#{#entityName}实现它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM