What does it mean <S extends T> save (S entity); in Spring Repository?

[亡魂溺海] 提交于 2019-11-27 23:56:33

问题


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.
}

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.


回答1:


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.



来源:https://stackoverflow.com/questions/41960743/what-does-it-mean-s-extends-t-save-s-entity-in-spring-repository

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!