What does it mean save (S entity); in Spring Repository?

后端 未结 1 1271
青春惊慌失措
青春惊慌失措 2020-12-16 14:40

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

public interface CrudReposito         


        
相关标签:
1条回答
  • 2020-12-16 15:21

    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.

    0 讨论(0)
提交回复
热议问题