<S 扩展 T> 是什么意思保存(S实体);在 Spring 存储库中?

2022-01-18 00:00:00 spring repository java spring-data generics

在 Spring Data 项目中,CrudRepository 为正在管理的实体类提供复杂的 CRUD 功能.

In Spring Data project the CrudRepository provides sophisticated CRUD functionality for the entity class that is being managed.

public interface CrudRepository<T, ID extends Serializable>
extends Repository<T, ID> {

    <S extends T> S save(S entity);

    T findOne(ID primaryKey);

    Iterable<T> findAll();

    Long count();

    void delete(T entity);

    boolean exists(ID primaryKey);

    // … more functionality omitted.
}

一般来说,我知道S extends T"是什么意思,即save操作的返回类型S必须是T的子类型.为什么要加上这样的约束?我认为这样做会很好:

In general, I know what "S extends T" means, i.e. that S, the return type of save operation, must be subtype of T. Why is it necessary to add such as constraint? I think that would be fine doing something like this:

T save (T entity);

void delete(T entity);

我在谷歌上搜索以寻求更多帮助,我发现了关于 stackoverflow 本身的以下问题,但对我来说并不是很清楚:

I've googled to find more help and I've figured out following question on stackoverflow itself but it isn't really clear for me:

Spring CrudRepository:为什么要发明一个新的泛型S型

谢谢.

推荐答案

如果你想拥有它

T save (T entity);

那么您可以将结果分配给的唯一变量必须是 T 类型.

Then the only variable you could assign the result to would have to be of type T.

所以,如果你有一个 CrudRepository<Animal,AnimalID>存储库,你有

So, if you have a CrudRepository<Animal,AnimalID> repository, and you have

Dog dog = getDog();
Dog savedDog = repository.save(dog);

你会得到一个编译错误 - 你不能将结果分配给 Dog,因为它必须是 T 类型,在这种情况下,动物.

You'd get a compile error - you can't assign the result to Dog, as it has to be of type T, in this case, Animal.

您需要检查返回的值是否确实是 Dog 类型,如果是,则将其转换为 Dog 以将其放入 savedDog.

You'd need to check if the returned value was indeed of type Dog, and if so, cast it to Dog to put it in savedDog.

按照原样声明,这意味着您可以将其分配给与原始参数相同类型的变量,因为类型解析将允许这样做.

With the declaration as it is, it means that you can assign it to a variable of the same type as the original argument, as type resolution will allow that.

声明本身并没有具体说明如何保存狗的非动物部分(如果有的话).它所做的只是允许将结果分配回 Dog 如果它最初是 Dog.

The declaration itself doesn't specify how the non-animal parts of the dog are saved if at all. All it does is allow assigning the result back to a Dog if it was originally a Dog.

相关文章