How to remove Entity from Hibernate cache - spring

I am using hibernate, spring, jpa.
In a workflow I update an entity; but these updates are not available in another workflow. When I restart the server it works fine.
Is there a way so that when I update an entity; I ask hibernate to remove it from whatever cache it has.. So that when that object is needed by any other workflow a fresh query is made ?

This sounds like you have two separate sessions for the same app, thus, having two 1st level caches. The first level cache is the one that Hibernate uses for itself, in the context of a session. So, if you don't close/clear your session, this will keep growing, possibly conflicting with other 1st level caches (in other threads or in other VMs). It's hard to say if that's the case, as you didn't specify your environment, but you can't change another session's first level cache.
The best solution to avoid this is to use a managed EntityManager (from your application server) to deal with entities. It's then the server's role to deal with this kind of scenario. But it seems that you are doing it the "spring way", so, you'll have to do it manually: either clear the session after you use it, or do a refresh before reading/updating your data. You'll then need some sort of locking (pessimistic/optimistic) to not lose information that might have been changed from another thread.

Related

Ehcache to refresh when an update take place in a database

I am new to Ehcache, My Rest API cache works
<cache name="com.a.b.c.model.Act"
maxElementsInMemory="10000" overflowToDisk="false" statistics="true" />
If I do any update in Database through query, the cache won't update those changes.
If I do update through REST API the cache will get refreshed.
What change I have to make if I have to get cache refresh when a change happens in Database
Is it good to go with timeToLiveSeconds or any other configurations can be done?
Updating the cache when the underlying system of record changes, and not through the service methods on which caching is performed, is the classical problem with caching.
Ehcache does not provide an out of the box solution there as it would mean supporting ALL the technologies that can act as a system of record. Not only databases but also web services and really anything a programmer can come up with.
However, if your application can live with having outdated data in cache for a small period of time, then expiry can be helpful. It effectively mark cache entries as valid for a period of time - time to live.
If your application cannot support stale data in cache, you will have to make sure the process to update the system of record takes care of invalidating the cache as well.
If the code that is upadating the database can access Ehcache manager (same VM or distributed persistence) the best solution is to break the cache
CacheManager.getInstance().getEhcache("mycache").remove(key);
and let the cache refresh autonomously.
If you already dispose of the updated object you could also skip one step with put
CacheManager.getInstance().getEhcache("mycache").put(key, updatedObject);
If your code has CacheEntryFactories I would let the factory do the business (entry creation is centralized, you can add more logic there)

Can I use the Grails session to store entire domain objects?

If I have a number of Grails domain objects that I do not want to save just yet, but still access them throughout my application, is it wise to store them in the Grails / Hibernate session (especially as regards peformance)? If not, what is the alternative?
What do you mean by the grails / hibernate session?
If you really mean the Hibernate session, adding an object to it will provoke the object to be saved automatically when the session is flushed (unless the object doesn't validate, in that case it will be lost once the session is discarded). A session is created and discared per request.
If you mean the session object that gets automatically injected into controllers and views, it's nor grails neither Hibernate specific, but just the old, plain HttpSession from the Servlet specification (see http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletRequest.html).
You can use that to store any kind of object if you need to access them across multiple requests of the same client. Meaning the session is private to a given client (who identifies it throught the jsessionid cookie) and survives multiple requests. If you don't need the multiple request bit, adding them as a request attribute would suffice.
Putting things in the session is generally fine and fast (since by default is based on memory), but it will increase the memory footprint of the application if abused, and will prevent horizontal scaling (i.e deploying the same application in multiple instances) unless sticky session mechanisms are used (or the session is persisted).
Bear in mind though that grails uses a new Hibernate session per request (not an Http session :), so if you add objects that are attached to a Hibernate session to the Http session, and then the Hibernate session is closed, you might encounter problems. This shouldn't affect non-saved objects (they don't come from a Hibernate session), but it might affect their associations (other domain classes that do come from the database and therefore a Hibernate session). If that's the case, you might need to re-attach them. See https://grails.github.io/grails-doc/latest/ref/Domain%20Classes/attach.html
Also, if the session is invalidated (because the user logs out, or the server is re-deployed) everything that was stored in there will be gone.
If you don't want to rely on sessions at all, you can create your own a MemoryBasedStoreService service and use a ConcurrentHashMap or a similar mechanism to store and retrieve the objects. Since services are singleton in Grails, you can use it across the whole application, regardless of requests or clients - as long as your application is deployed in a single instance of course :).

Grails Cache Restart

I am using the grails cache plugin to cache a collection of gorm objects. This method is in a service
#Cacheable('allBooks')
List<Book> getAllFictionBooks() {
log.info("Looking up all books and adding them to a cache")
Book.findAllByIsFiction(true)
}
However on server restart I get this error and often have to restart my server a second time
failed to lazily initialize a collection of role: com.Book.applyTo, no session or session was closed
I added
grails.cache.clearAtStartup = true
to Config.groovy but that didn't seem to help. I am probably doing something stupid. Any help is much appreciated.
I am using Grails 2.2.1. Plugin: cache:1.1.1
You don't want to cache GORM query results with the cache plugin - Hibernate already has support for this with the query cache. And it's a lot more robust, specifically with invalidation. For example If your query returns 4 books, but at some point in the future a new fiction book is added, you need to manually remove this result. But Hibernate does this already - any new, deleted, or even modified book will cause all cached results with books to be removed.
But the issue you're seeing is that apparently you have a lazy-loaded applyTo collection. Once the query runs and you store the values in the Spring-managed cache and then the web request ends, the Hibernate Session is closed and the instances become disconnected. Later accessing any uninitialized lazy properties will trigger the exception you're seeing unless you reattach the instance to the current session, e.g. with merge(). But Hibernate would have done that for you if you used the 2nd-level cache.
The 2nd-level cache is also easily clusterable. Once you add a 2nd web server, you need to ensure that you don't have 2 independent caches, but rather 2 caches that update each other to stay in sync. This is obviously doable with the Spring caching, but it's more straightforward with Hibernate/GORM.

Java JPA: How to keep sessions alive across HTTP requests?

In a web application, I'm using JPA entities to persist (and retrieve) my domain objects to (and from) an underlying database.
These JPA entities are kept "hot" in an in-memory cache structure (think of a Map<UniqueID, Entity>) for the whole running time of the web application.
So I'm doing a request to my web application, an entity gets loaded from the repository. This entity gets put into the in-memory cache structure. For the whole lifetime of this request, I can happily access any fields of this entity. During this first request, also lazily-loading relationships to other entities works fine, even in my View: I'm successfully using the Open-Session-in-View pattern (via Spring's OpenEntityManagerInViewInterceptor).
The first request has ended.
I'm doing the next request to my web application. This request asks for another entity. This entity is already in the in-memory cache structure, so it gets loaded from there. From this entity, I try to access a field that should lazily-load relationships to other entities. This unfortunately causes the obnoxious org.hibernate.LazyInitializationException: could not initialize proxy - no Session (I'm using Hibernate as my underlying JPA implementation)
To my understanding, this exception stems from the fact that after the first request has ended, JPA/Hibernate has ended any JPA sessions, yet entities in my in-memory cache structure still expect any of these sessions to exist; at the moment that the next request causes to fire the mechanism for lazily-loading entities, the lazily-loading mechanism can't find any no-longer existing session.
What are solutions to my problem?
One of solutions is to reattach the entity to session at the beginning of the second request using Session.update().
Another solution is to use the second level cache in Hibernate instead of your own solution. It should be much more reliable than any home-grown caching mechanism.
Basically, you cannot keep sessions alive across HTTP requests because this would mean to keep the transaction open between requests.
I think the only solution (apart detecting yourself what is loaded and what is not) is to fetch the whole entity before putting it in your cache. IMHO you shouldn't put partially loaded objects in a cache. If you don't want to load the whole object the first time, you might use separate caches for the objects relationships.
If you want, you might also consider enabling Hibernate cache as proposed by #Adam, but I don't think it would work well with lady-loaded fields.
You are getting this exception because your object is detached from current session. You have to re-attach this object to current session before assessing it
session.update(object);
You can read details here

Is Terracotta used professionally?

Today at work I had a discussion with my co-workers and my boss about stateless / stateful beans (we just finished a project using JSF, it was the first time anyone at this company did something JSF related) and my boss said that he doesn't really like Session scoped beans (or even conversation / KeepAlive scoped ones). One of his arguments was that if we have for example 4 Tomcats and there is a request from the user then we aren't really sure that it will be "captured" by the same Tomcat every single time and the problem is that if during the first time a request comes and a session bean is created it's created only on that one Tomcat and the others don't know about it.
One of the solutions he mentioned was a so called "sticky session" which enforces requests from a given user to be handled by the same Tomcat every time. A second solution according to him would be storing all the data in the "view", but that would mean storing the whole state in the POST, somehow I don't really like that idea. Then he mentioned storing the state in the DB and querying it if a request that requires it arrives. I thought that it would be a really huge performance hit, but he said that it really wouldn't be a concern since the DBs should be prepared for such tasks.
The last solution which I'm interested in was the Terracotta Server which, from what he told us, is supposed to store the session bean for all Tomcats (which are synchronized with it and then if a requests comes in they look for session beans inside Terracotta). Seems kinda cool and scalable, but he said that he didn't really see it ever used in large professional systems, is that right? I tried some info on it but failed, is there something wrong with Terracotta that stops people from using it?
It is used by professionals, just look a their customers page.
http://www.terracotta.org/company/customers?src=/index.html

Resources