I have code like:
@Entity
@Table(name = "A")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class A
{
@OneToOne(cascade={CascadeType.ALL}, fetch=FetchType.EAGER, mappedBy="a")
public B getB() {};
}
@Entity
@Table(name = "B")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class B
{
@OneToOne(cascade={}, fetch=FetchType.LAZY)
@JoinColumn(name="A_ID")
public A getA() {};
}
each time when A
is loaded there is query for B
. Why is A.getB()
not cached after A
is loaded and is it possible to cache it?
To use the query cache, you must first activate it using the hibernate. cache. use_query_cache="true" property in the configuration file. By setting this property to true, you make Hibernate create the necessary caches in memory to hold the query and identifier sets.
L1 Cache is the cache that exists per Hibernate session, and this cache is not shared among threads. This cache makes use of Hibernate's own caching. L2 Cache is a cache that survives beyond a Hibernate session, and can be shared among threads.
The First level cache is by default enabled by Hibernate itself. The session object maintains the first-level cache.
Caching is one of the strengths of the Hibernate framework, and it is available at multiple levels. The first-level cache is the first place that Hibernate checks for cached data. It is built in and active by default to reduce the number of SQL queries directly to the database.
Workaround that work for me is create additional method with @OneToMany
@OneToMany(cascade={}, fetch=FetchType.EAGER, mappedBy="a")
public Set<B> getBSet() {};
@Transient
public B getB() { return b.iterator().next(); }
I'm not very happy with this solutions, but it works and I can't find other way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With