[英]how can i retrive jpa-repository instance from class in spring 2.2.4.RELEASE
i need to retrieve specific instance of jpa-repository from an entity class to call findAll, findOne ecc...我需要从实体类中检索 jpa-repository 的特定实例以调用 findAll、findOne ecc ...
Entity entity = getRepository(EntityClass).findOne(uriParamValue);
In the previous spring version (1.5.X) i was doing it this way:在之前的 spring 版本 (1.5.X) 中,我是这样做的:
public JpaRepository<Entity, Serializable> getRepository(Class<?> javaClass) {
return (JpaRepository<Entity, Serializable>) repositories.getRepositoryFor(javaClass);
}
but in spring 2.2.X the Repository class interfaces has been changed from:但是在 spring 2.2.X 中,Repository 类接口已从:
public Object getRepositoryFor(Class<?> domainClass) {
to:到:
public Optional<Object> getRepositoryFor(Class<?> domainClass) {
and i can't cast "Optional getRepositoryFor(X)" to JpaRepository instance to able to call JpaRepository methods.并且我无法将“可选的 getRepositoryFor(X)”转换为 JpaRepository 实例以能够调用 JpaRepository 方法。
Where am I doing wrong?我哪里做错了?
thanks谢谢
I'm not familiar with the getRepositoryFor
method, but Optional is a standard Java class intruduced in Java SE 8. You can check if the value is present and get the actual value from the Optional if it is present.我不熟悉getRepositoryFor
方法,但Optional是 Java SE 8 中getRepositoryFor
的标准 Java 类。您可以检查该值是否存在,如果存在,则可以从 Optional 获取实际值。 Here is a sample using orElseThrow , but there are also other variants.这是使用orElseThrow的示例,但也有其他变体。 Checkout the Javadoc.查看 Javadoc。
public JpaRepository<Entity, Serializable> getRepository(Class<?> javaClass) {
return (JpaRepository<Entity, Serializable>) repositories.getRepositoryFor(javaClass)
.orElseThrow(() -> new MyException());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.