user2558093
user2558093

Reputation: 33

Spring cache on create new item

I'm using item ID to identify caching data like this:

@CachePut(value = "users", key = "#p0.id")
@RequestMapping(value = "/user", method = RequestMethod.PUT)
public User updateUser(@RequestBody User user);

Function create new Item return item ID after created. How can I save item into cache after create new Item?

@Cacheable(value = "users", key = "???")
@RequestMapping(value = "/user", method = RequestMethod.POST)
public User createUser(@RequestBody User user);

Upvotes: 2

Views: 1193

Answers (3)

TheIronHead
TheIronHead

Reputation: 51

Use @CachePut on creating new items.

You may refer this for differences between @CachePut and @Cacheable: Spring Cacheable vs CachePut?

Upvotes: 1

Heril Muratovic
Heril Muratovic

Reputation: 2028

I suggest to create service class and put all those methods in it. Also on store method (in your case createUser method) you should put annotation @CachePut(value = "user", key = "#user.id").

Something like this:

@CachePut(value = "user", key = "#user.id")
public User createUser(User user) { 
   // store user in db...
}

Try code above.

Upvotes: 1

Aditya Narayan Dixit
Aditya Narayan Dixit

Reputation: 2119

Use @CachePut

@CachePut(value = "users", key = "#result.id"")
@RequestMapping(value = "/user", method = RequestMethod.POST)
public User createUser(@RequestBody User user);

Upvotes: 1

Related Questions