您能否给我一个提示为什么在 CrudRepository 接口(interface)的“save”方法中发明了一个新的泛型类型“S”。 (参见org.springframework.data.repository.CrudRepository)
这是 CrudRepository 类的提取:
public interface CrudRepository<T, ID extends Serializable>
extends Repository<T, ID> {
/**
* Saves a given entity. Use the returned instance for further
* operations as the save operation might have changed the
* entity instance completely.
*
* @param entity
* @return the saved entity
*/
<S extends T> S save(S entity);
...
/**
* Deletes a given entity.
*
* @param entity
* @throws IllegalArgumentException in case the given entity is (@literal null}.
*/
void delete(T entity);
}
请注意,在第二种方法“删除”中,同一实体的类型为 T。 “save”方法表示它返回一个“S”类型的对象。所以这是不可能实现像这样的“保存”方法:
@Override
public <S extends MyType> S save(S entity) {
save(entity);
return findOne(entity.getMyTypeId()); // Type mismatch: cannot convert from MyType to S
}
另一个问题是如何更好地实现“保存”方法?
最佳答案
目的是,一般来说,Spring *Repository
接口(interface)是由 Spring Data 自动实现的,而不是手动实现的,并且很方便地知道您将从中获取相同类型的对象。您输入的 save
操作。特别是对于面向文档的数据存储,子类与父类(super class)保留在同一存储库中并不罕见,并且使用 S extends T
作为参数和返回类型确保您可以继续使用保存前具有相同接口(interface)的持久化对象。
关于java - Spring CrudRepository : why to invent a new generic type S,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26346036/