I wanted to introduce caching in my enterprise app, so I configured everything and made simple unit test to check if it works.
And it did work, log file proved everything, I saw entities being cached and later picked up from cache.
This was a unit test and hibernate was configured with JPA RESOURCE_LOCAL DS. (i think this may be important)
So I proceeded to deploy entire app to JBoss5.1 and log showed that cache is configured properly just like standalone unit test.
HOWEVER, entity I was looking for is fetched from cache but when i navigate to its ManyToOne assoc, i get lazy exception. I spent days debugging this but I still don't realize why it works with unit test and not within container (same entities, same session beans)
I logged everything and I saw that associated entity is placed in cache but it is not fetched from cache, lazy exception is thrown instead.
I don't know if it is important but I use named query to load entity and query cache is properly configured. The same ehcache.xml is used for both unit test and EAR application (only data source is different).
Entity looks like this:
Code:
@Entity
@Table(name = "EMP")
@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
public class Employee implements Serializable {
@Id
@Column(name = "EMP_ID")
private Long id;
@JoinColumn(name ............)
@ManyToOne(optional = false, fetch = FetchType.LAZY)
private Department dept;
I get employees with named query which explicitly joins with departments and department is loaded and shown first time. I can observe in the log file that both employee and department are put in cache.
When I access employee second time, I can see it is found in cache but when i access it's department I get lazy exception. Hibernate didn't even try to check the cache, even though department IS cached.
But, why does it work in unit test???
Thanks.