0

I have 2 entities with one to many relationship as follow:

public class A {

  @ID
  private String id;

  @OneToMany(mappedBy = "a",cascade = CascadeType.ALL, orphanRemoval = true)
  private Set<B> bSet;
  //getters setters and constructors
}

public class B {

  @ID 
  private String name

  @ManyToOne
  @JoinColumn(name = "id",nullable = false)
  private A a;

  //getters setters and constructors
}

I also have 2 corresponding repositories for A and B as follow:

@Repository
public interface BRepository extends JpaRepository<B,String> {

  @Cacheable(value = "bCache", key = "#p0")
  B findOneByName(String name);

  Set<B> findAllByNameIn(Set<String> names);

  @Override
  @CacheEvict(value = "bCache", key = "#p0")
  void delete(String name);
}

@Repository
public interface ARepository extends JpaRepository<A,String> {

}

When I do:

A a = new A("id1");
B b1 = new B("name1", a);
B b2 = new B("name2", a);
a.getbSet().add(b1);
a.getbSet().add(b2);

aRepository.save(a);

then all B objects are inserted into the B table in the repository. Afterwards I want my bCache to be populated with each element in a.getbSet()with the key being b.name and the value being the B instance.

How can I get this functionality to work?

-------------------------UPDATE---------------------------

In order to answer my needs I want the cache to look like:

KEY   |   VALUE
name1 | B(name1)
name2 | B(name2)

How can i use SPEL to define the key for cachePut if i want to save it to the cache when i perform save to A (remember A contains set of B instances)? is it possible?

Thanks.

NetaliG
  • 56
  • 6
  • This question is not unlike past questions of the same nature. See here for instance... https://stackoverflow.com/questions/47803120/spring-caching-not-working-for-findall-method – John Blum May 03 '18 at 20:18
  • @JohnBlum thank you for the links and the answer , i updated my question , is it possible to do what i want? – NetaliG May 04 '18 at 12:04
  • Yes, this is possible, but you need to extend Spring's `Cache` and `CacheManager` abstraction for you provider to enable that capability. The custom `CacheManager` will return an instance of your custom `Cache` instance to handle the nested aggregate, not unlike what my previous posts related to this problem demonstrates. – John Blum May 04 '18 at 17:09
  • @JohnBlum Thank you , I used [your example](https://github.com/jxblum/spring-gemfire-tests/blob/master/src/test/java/org/spring/cache/CachingCollectionElementsIndividuallyWithConcurrentMapTest.java) here to solve my problem. – NetaliG May 05 '18 at 18:20

0 Answers0