java - Spring CrudRepository : why to invent a new generic type S

标签 java spring generics

您能否给我一个提示为什么在 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/

相关文章:

java - 混淆 Java 泛型错误与 Map 和 Collector

c# - 具有不同类型 : Cleaner, 非字符串方法名称的委托(delegate)的 Dictionary<T,Delegate>?

java - 如何找到整数数组中每个元素的等级

java - 调整可绘制问题的大小(未传递引用?)

java - 错误: No operations allowed after connection closed

java - tomcat配置导致@Service的2个副本运行

java - 在不知 Prop 体类型的情况下实例化对象

java - Spring MVC3 + Apachetiles + Thymeleaf 集成问题

java - Spring Cloud : Ribbon and HTTPS WITHOUT Eureka

java - Hibernate 和 Spring 事务管理器 : Transaction Not Successfully Started