【发布时间】:2014-10-14 02:32:00
【问题描述】:
您能否给我一个提示为什么在 CrudRepository 接口中的“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
}
另一个问题是如何更好地实现“保存”方法?
【问题讨论】: