Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making many to many relationship cacheable in JPA

Tags:

hibernate

jpa

I have many-to-many relationship between User and Role. There is a third table called UserRole mapped as a join-table.

In JPA I can cache User and Role using @Cachable; however when I try to fetch the Roles associated to the User which is defined EAGER, a database query is executed to fetch the values from the join-table.

How can I cache the join-table between User and Role?

like image 237
Sagar Avatar asked Feb 07 '14 19:02

Sagar


1 Answers

Decide your caching concurrency strategy based on here and use @Cache on top of your association:

    @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = "user_roles")

Make sure to mark the both entities (in this case User and Role) with @Cacheable too.

like image 169
Youness Avatar answered Oct 04 '22 01:10

Youness