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.