这是什么意思< S延伸T>保存(S实体);在Spring Repository中? [英] What does it mean <S extends T> save (S entity); in Spring Repository?
问题描述
public interface CrudRepository< T,ID扩展了Serializable>
扩充知识库< T,ID> {
< S延伸T> S保存(S实体);
T findOne(ID primaryKey);
可重用< T>找到所有();
Long count();
void delete(T entity);
布尔值存在(ID primaryKey);
// ...省略了更多功能。
}
一般而言,我知道S延伸T的含义,即S ,保存操作的返回类型,必须是T的子类型。为什么需要添加如约束?我认为可以这样做:
T save(T entity);
与
void delete(T entity);
我已经搜索到了更多的帮助,并且我已经找到了以下关于stackoverflow本身的问题,但它对我来说不是很清楚:
Spring CrudRepository:为什么要发明一个新的泛型类型S
谢谢。
如果您将其作为
T保存(T实体);
然后,您可以分配结果的唯一变量必须是 T
。
因此,如果您有 CrudRepository< Animal,AnimalID> repository
,并且你有
Dog dog = getDog();
Dog savedDog = repository.save(dog);
你会得到一个编译错误 - 你不能将结果赋给狗
,因为它必须是 T
类型,在这种情况下, Animal
。
你需要检查返回的值是否确实是 Dog
类型,如果是这样,cast它将 Dog
放入 savedDog
。
如果是这样的声明,就意味着你可以将它分配给一个与原始参数类型相同的变量,因为类型解析会允许这样做。
声明本身并没有说明如何保存狗的非动物部分。如果它最初是 Dog
。
Dog
b $ bIn 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.
}
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);
As in
void delete(T entity);
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: why to invent a new generic type S
thank you.
If you were to have it as
T save (T entity);
Then the only variable you could assign the result to would have to be of type T
.
So, if you have a CrudRepository<Animal,AnimalID> repository
, and you have
Dog dog = getDog();
Dog savedDog = repository.save(dog);
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
.
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.
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
.
这篇关于这是什么意思< S延伸T>保存(S实体);在Spring Repository中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!