Reputation:
I have defined roles in my database role_template
.
@Entity
@Table(name = "role_template")
@Cacheable
public class Role {
@Id
private int id;
private String name;
@Transient
private final int identity = new Random().nextInt(1000000) + 1;
}
I have one role at this moment with id=1 and name="admin"
My entity User
has a list of roles defined as follow
@Entity
@Table(name = "app_user")
public class User {
[...]
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "role_assign",
joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
private Set<Role> roles;
}
Roles
are joined to users with my association table
[Table `role_assign`]
int user_id
int role_id
My problem is predictable, @Cacheable
does not work.
I tried with 2 users, they have the same Role
template, but not the same instance
. The transient variable identity
isn't equals for the role of the two users.. My app configuration is good, I think I forgot something to make it working for @JoinTable
Upvotes: 2
Views: 7627
Reputation: 81882
Is this the javax.persistence.Cacheable
annotation? Because it should.
I think your understanding of how caching works with JPA is wrong and your observations is not sufficient to decide if caching takes place or not.
@Cacheable
is about the 2nd level cache. If an entity is pulled from the cache it is instantiated from information stored in the cache, and not actually the same instance. The latter wouldn't work. Entities can always only be attached to a single session, but the 2nd level cache lives across sessions.
Two representations of an entity should be the same instance exactly if they belong to the same session.
In order to decide if the cache is used or not you have two good options:
Log the SQL statements issued against the database and see if the data for the entity is selected over and over again, or only once.
Log the cache interaction and see what is going on directly.
How you do that depends on the JPA provider you use. Here are instructions for Hibernate.
Upvotes: 2