How to reduce database query when using stateless framework like Spring MVC - spring

I just moved to Spring MVC for several days. Before that, I used to develop web project using JSF, EJB and JPA.
In EJB, we can use a stateful session bean(SFSB) with extended persistence context so that I can cache the entities in order to reduce database query. But in Spring MVC, once the entity is returned from a #Service bean, it becomes detached and cannot survive the next request. So I have to query database again in next request.
My question is how can I keep an entity managed by Entitymanager during many request?Thanks!

Use a 2nd level cache or session scoped beans, to keep entities in memory. Spring beans have mulplie different possible scopes.
Worth mentioning that keeping everything stateless makes scaling out easier. And adding state to anything http is always counter intuitive, to me at least.

Related

Does it make sense to combine Spring with JSF? [duplicate]

I'm a little confused by the mixed use of JSF2+Spring+EJB3 or any combination of those. I know one of the Spring principal characteristics is dependency injection, but with JSF managed beans I can use #ManagedBean and #ManagedProperty anotations and I get dependency injection functionality. With EJB3 I'm even more confused about when to use it along with JSF or if there is even a reason to use it.
So, in what kind of situation would it be a good idea to use Spring+JSF2 or EJB3+JSF2?
Until now I have created just some small web applications using only JSF2 and never needed to use Spring or EJB3. However, I'm seeing in a lot of places that people are working with all this stuff together.
First of all, Spring and EJB(+JTA) are competing technologies and usually not to be used together in the same application. Choose the one or the other. Spring or EJB(+JTA). I won't tell you which to choose, I will only tell you a bit of history and the facts so that you can easier make the decision.
Main problem they're trying to solve is providing a business service layer API with automatic transaction management. Imagine that you need to fire multiple SQL queries to perform a single business task (e.g. placing an order), and one of them failed, then you would of course like that everything is rolled back, so that the DB is kept in the same state as it was before, as if completely nothing happened. If you didn't make use of transactions, then the DB would be left in an invalid state because the first bunch of the queries actually succeeded.
If you're familiar with basic JDBC, then you should know that this can be achieved by turning off autocommit on the connection, then firing those queries in sequence, then performing commit() in the very same try in whose catch (SQLException) a rollback() is performed. This is however quite tedious to implement everytime.
With Spring and EJB(+JTA), a single (stateless) business service method call counts by default transparently as a single full transaction. This way you don't need to worry about transaction management at all. You do not need to manually create EntityManagerFactory, nor explicitly call em.getTransaction().begin() and such as you would do when you're tight-coupling business service logic into a JSF backing bean class and/or are using RESOURCE_LOCAL instead of JTA in JPA. You could for example have just the following EJB class utilizing JPA:
#Stateless
public class OrderService {
#PersistenceContext
private EntityManager em;
#EJB
private ProductService productService;
public void placeOrder(Order newOrder) {
for (Product orderedproduct : newOrder.getProducts()) {
productService.updateQuantity(orderedproduct);
}
em.persist(newOrder);
}
}
If you have a #EJB private OrderService orderService; in your JSF backing bean and invoke the orderService.placeOrder(newOrder); in the action method, then a single full transaction will be performed. If for example one of the updateQuantity() calls or the persist() call failed with an exception, then it will rollback any so far executed updateQuantity() calls, and leave the DB in a clean and crisp state. Of course, you could catch that exception in your JSF backing bean and display a faces message or so.
Noted should be that "Spring" is a quite large framework which not only competes EJB, but also CDI and JPA. Previously, during the dark J2EE ages, when EJB 2.x was extremely terrible to implement (the above EJB 3.x OrderService example would in EJB 2.x require at least 5 times more code and some XML code). Spring offered a much better alternative which required less Java code (but still many XML code). J2EE/EJB2 learned the lessons from Spring and came with Java EE 5 which offers new EJB3 API which is even more slick than Spring and required no XML at all.
Spring also offers IoC/DI (inversion of control; dependency injection) out the box. This was during the J2EE era configured by XML which can go quite overboard. Nowadays Spring also uses annotations, but still some XML is required. Since Java EE 6, after having learned the lessons from Spring, CDI is offered out the box to provide the same DI functionality, but then without any need for XML. With Spring DI #Component/#Autowired and CDI #Named/#Inject you can achieve the same as JSF does with #ManagedBean/#ManagedProperty, but Spring DI and CDI offers many more advantages around it: you can for example write interceptors to pre-process or post-process managed bean creation/destroy or a managed bean method call, you can create custom scopes, producers and consumers, you can inject an instance of narrower scope in an instance of broader scope, etc.
Spring also offers MVC which essentially competes JSF. It makes no sense to mix JSF with Spring MVC. Further Spring also offers Data which is essentially an extra abstraction layer over JPA, further minimizing DAO boilerplate (but which essentially doesn't represent the business service layer as whole).
See also:
What exactly is Java EE?
JSF Controller, Service and DAO
#Stateless beans versus #Stateful beans
There's no real easy answer here as Spring is many things.
On a really high level, Spring competes with Java EE, meaning you would use either one of them as a full stack framework.
On a finer grained level, the Spring IoC container and Spring Beans compete with the combination of CDI & EJB in Java EE.
As for the web layer, Spring MVC competes with JSF. Some Spring xyzTemplate competes with the JPA interfaces (both can use eg Hibernate as the implementation of those).
It's possible to mix and match; eg use CDI & EJB beans with Spring MVC, OR use Spring Beans with JSF.
You will normally not use 2 directly competing techs together. Spring beans + CDI + EJB in the same app, or Spring MVC + JSF is silly.

Transitioning to Spring Data

We are currently using Spring 3.2.3 + JPA (Hibernate). We use aspects for transaction support as opposed to annotations. We write out own entity services (read: repositories) to abstract the persistence away from our application.
I've read a lot about Spring Data and feel it would make our code considerably cleaner and more robust. I wonder though, are there any gotchas that I should consider before transitioning?
Thanks
If you're already on JPA the transition should be as easy as it can be: activate the repositories, point the infrastructure to your EntityManagerFactoryBean and off you go.
Transactions should just work fine as well. The annotation based usage within Spring Data is selectively activated for the repository beans only. They are configured to take part in existing transactions by default, so any custom larger scoped transaction setting should be in effect already.

Spring context refreshing makes Hibernate session throw this exception: No Session found for current thread

I am developing a web application that has multiple spring contexts. It has a main context that holds business logic, hibernate session and application's core needs, and other contexts are for spring mvc binding. Normally application works fine and everything, but when i refresh main context and try to reach hibernate session from other contexts, hibernate session throws this exception:
org.hibernate.HibernateException: No Session found for current thread at
org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97) at
org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:980)...
But funny thing is application can do startup initiation which includes selecting lots of data from db.
Is there a way that i can refresh spring context safe and sound?
P.S: I can get other spring context objects with no problem. And application works fine with multiple contexts until i refresh main context. And i tried refreshing the mvc context, from which i call hibernate session, after main context. Still the same exception in that mvc context.
The reason you are getting that error is that you are whacking the Hibernate sessions out from underneath the threads. The sessions, from what I remember, associated with the Thread that created them. This is why you can't pass a proxied Hibernate entity to frameworks like BlazeDS. As soon as the proxied entity leaves the thread, the session is no long associated with it and you loose the ability to go after the items that are being proxied.
One solution might be to not use Proxies, and eagerly-load all relationships. This would be undermining one of the main benefits of using an ORM, however. Or, if you could somehow re-start all the threads in questions, making new threads that are associated with the new Hibernate session(s), that might work too.

Spring transaction support in Netty handlers

I am using the following versions:
Spring 3.1.1.RELEASE
Netty 3.4.0.Final
Hibernate 3.5.6-Final
Now, I have a Netty server that works fairly well - the root of the server, the pipeline factories and the base "stub" of the server that owns everything are all set up with Spring. In this stub, spring #Transactional annotations work just fine.
However, in the handlers, which are stateful and created dynamically depending on what state the user is in - #Transactional doesn't work. I'm fairly sure I understand why. I even have a "solution" - but it's not very good.
After the decoders and encoders, I add an ExecutionHandler:
pipeline.addLast("execution", new ExecutionHandler(new OrderedMemoryAwareThreadPoolExecutor(16,1000000, 1000000)));
This appears to be where the Spring transaction support is breaking. Since Spring is unaware of these threads, it can't bind any transactions to them. The classes are proxied correctly, but in debug they have no associated transactions.
My solution is crappy, and it needs to be replaced by a real solution:
Session sess = SessionFactoryUtils.getSession(getSessionFactory(), true);
That's bad because it relies on me to release the session, and it may not even be transactional, I haven't checked. It sucks in a lot of ways.
Anyway - the root of the question. Given the above tech, what's my path to getting my #Transactional notations working on the Netty handlers?
Write an ExecutionHandler that's Spring aware?
NOTE: I can't upgrade to Hibernate 4, due to lack of compatibility with Spring-Flex, used in another project in the group. Probably the same story for the Spring version, can't remember.
I suggest you create these netty's handler inside spring container and inject the service or persistence layer into the handlers so you can have these layers independence from netty and of course these are old school spring beans.

Domain Driven Programming Using Spring

I have a question on DDD & Spring. I always design my application around anemic domain model and service taking care of business logic/persistence.
Assume you have a spring managed persistence/respository service for a Domain object e.g. Book. If I have to expose a save() method on book then i will need repository bean inside my domain or i will have to look up the context for the repository bean. Which is exactly opposite of Dependency Injection.
Now, If I have repository id injected into domain and domain object is cached ( clustered cache) and then on deserialization it will not have the injected repository service as spring containers will be different.
I might be wrong but if someone can explain me how this scenario will work, it would be of great help
I think that the "facade" of your application should use a Repository (or other infrastructure service) to save the "book". The book should not save it-self, this is responsibility of the Repository.
If you need to make any infrastructure operation (for example, search the database) from a Domain Entity, then you should gain access to this Repository by looking up the context (and getting coupled to Spring as a result) or injecting the Repository through Dependency Injection in the Entity.
The problem is that the "instantiation" of the Entity is not responsibility of Spring but of the Persistence Provider, so Spring cannot handle this injection. What to do?
Well, there are several ways (none of them very "beautyful") to do this:
Through AOP: you can instrument the code with Aspect Oriented Framework (like AspectJ) configuring the system to inject whatever dependency in the Entity in the instantiation moment.
Through a Hibernate interceptor: if your Persistence Provider is Hibernate, it offers you a hook to place interceptors in certain points of the life cycle of the Entities. You can configure an interceptor that looks-up the spring context to inject dependencies in the instantiation of every Entity.
Maybe the easiest way is to implement a little and static "serviceLocator" coupled with spring that looks-up services asked by the Entities when they need them. This service locator is just a layer to avoid your entities to get coupled to Spring.
I think that a "save" method (save in a DB, in example) doesn't belong to the domain object... Does the book "save" itself? Or is the repository saving it?...

Resources