Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate not caching my OneToOne relationship on the inverse side

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?

like image 633
Dainius Avatar asked May 20 '11 06:05

Dainius


People also ask

How do I enable caching in Hibernate?

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.

What is L1 and L2 cache in Hibernate?

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.

Is first level caching mandatory in Hibernate?

The First level cache is by default enabled by Hibernate itself. The session object maintains the first-level cache.

Does Hibernate support caching?

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.


1 Answers

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.

like image 57
Dainius Avatar answered Oct 14 '22 02:10

Dainius