Can someone outline the steps required to get hibernate working with spring mvc.
I've seen EntityDao's that basically inherit from a GenericDAo.
The generic Dao has basic operations like GetAll, GetByID, Save, Delete, etc.
And inside their methods they use:
getHibernateTemplate
So basically the Session has to be wired up in a bean, and mysql settings have to be set.
I find the spring documentation to be a little confusing: http://static.springsource.org/spring/docs/3.0.0.RELEASE/spring-framework-reference/html/orm.html#orm-hibernate
The basic components are:
Something to configure and create the Hibernate SessionFactory. This is typically done by the LocalSessionFactoryBean, as used in the example in the link you posted. This exposes a Spring-managed bean that implements the Hibernate SessionFactory interface.
Typically, you then have one or more DAO beans which are injected with the SessionFactory. In many cases, the simplest thing to do here is to extend the convenient HibernateDaoSupport class, which has a sessionFactory property. HibernateDaoSupport proves a getHibernateTemplate() method, which gets a Hibernate Session from the SessionFactory and wraps it in a HibernateTemplate object, which provides various convenience methods for doing common Hibernate operations, and is generally more useful than the raw Session interface.
Using this pattern, there is very little direct interaction between application code and the Hibernate API itself, its mostly done though s Spring intermediate layer. Some would call this a good thing, others would rather Spring stayed out of the way. This is a perfectly good alternative - there's nothing to stop you injecting your bean with SessionFactory and using the Hibernate API directly. The HibernateDaoSupport and HibernateTemplate classes are there purely as a convenience.
There is another way. If you don't want to use HibernateDaoSupport then you could directly inject SessionFactory into your DAO classes. This avoids tying you down to Spring classes.
Refer this for example - Spring Doc
This shows how to use Hibernate APIs directly.
Hope that helps.
Related
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.
I've read that the new way of creating Hibernate DAO is using Hibernate contextual sessions. The main reason being to avoid the Spring based HibernateTemplate/HiberateDaoSupport and thus Spring-Free DAO.
When I searched what to do with Exception translation? It's written everywhere that I should use #Repository! #Repository does need import and creates dependencies in my code. Am I right?
Aren't annotations considered dependency? If they are, is there anyway I can have that using XML? Or should I use the old HibernateDaoSupport way, since I'm going to have my code coupled with Spring anyway?
Update
Found a similar question: "integrate hibernate with spring without spring dependency in dao" but:
The first paragraph of the answer that #pap has given does not specify any clear XML alternative for #Repository.
The insight offered in the rest of that answer is plausible, yet my question remains unanswered that if decoupling is not much of a concern, why did Spring try proposing the new approach to Hibernate DAO?
P.S. This is not a criticism. It's rather an attempt to learn the proper way of thinking about this topic (i.e. the dependency).
The point of Spring exception translation in the first place is to break a dependency on Hibernate by creating a dependency on Spring. Regardless of the annotation, Spring exception translation catches a Hibernate exception and turns it into a Spring exception. By putting catch statements in your code tied to the Spring exception you are coupling your code to Spring far more directly than by adding any #Repository annotations. If you don't want to depend on Spring then simply use the Hibernate exceptions directly. Basically, there are two approaches:
Use Hibernate for exceptions and contextual sessions (no coupling to Spring). In this case, simply don't use Spring exception translation at all.
Use Spring for exceptions and session handling (looser coupling to Hibernate, additional coupling to Spring).
I am trying to use the org.springframework.orm.jdo.TransactionAwarePersistenceManagerFactoryProxy in my Spring project, but I am not sure how to use it or whether it's exactly what I am looking for. I realize it can help make my DAOs work with a plain JDO PersistenceManagerFactory. Another question is: what happens if the proxy doesn't get made properly? Can I still use it to access my factory to create a transaction aware persistence manager? If the object managed by the factory is a singleton, does this change things? Why not just access the PersistenceManagerFactory directly? Perhaps PersistenceManagerFactoryUtils.getPersistenceManager would be more suited to my needs? Can getObject return null?
Answers are directly available on documentation
I realize it can help make my DAOs work with a plain JDO PersistenceManagerFactory.
Yes.
TransactionAwarePersistenceManagerFactoryProxy proxy allows DAOs to work with a plain JDO PersistenceManagerFactory reference, while still participating in Spring's (or a J2EE server's) resource and transaction management.
You can surely use it in your app. But without knowing your exact needs, we can't confirm any further.
Can I still use it to access my factory to create a transaction aware persistence manager
DAOs could seamlessly switch between a JNDI PersistenceManagerFactory and this proxy for a local PersistenceManagerFactory.
If the object managed by the factory is a singleton, does this change things? Why not just access the PersistenceManagerFactory directly?
It is usually preferable to write your JDO-based DAOs with Spring's JdoTemplate, offering benefits such as consistent data access exceptions instead of JDOExceptions at the DAO layer. However, Spring's resource and transaction management (and Dependency Injection) will work for DAOs written against the plain JDO API as well.
I'm working on a web application that uses Spring MVC 2.5 and Hibernate.
One of the requirements of the application is that it must be able to export some objects to an external database. I figure I might as well use my existing data layer and just save the objects to the external source.
I'm new to Spring and Hibernate, and I guess I'm just wondering how I should approach this. Right now everything is automatically wired up through annotations. I'm guessing I'll have to create a new dataSource bean, and a new sessionFactory, and a transactionManager...maybe...but...
I only want the connection to the external data source to be available when the user is specifically "exporting".
Is autowiring going to get in my way? How can I tell Spring to inject the appropriate sessionFactory when I instantiate a DAO for my export process? (I'm autowiring through constructors) Should I programatically create my session factory (etc) and then manually instantiate my DAO? If so, will this "override" the autowire annotation?
I guess I don't need answers to the above questions specifically if someone can just step me through the basic process of getting something like this to work. Thanks!
Spring fortunately already has a solution for this: AbstractRoutingDataSource. It basically acts as a Facade for multiple DataSources and allows you to subclass it and implement whatever logic you need to decide which DataSource should be used. Some details are here:
http://blog.springsource.com/2007/01/23/dynamic-datasource-routing/
This allows your DataSource lookup logic to be handled in exactly one place. Your DAO layer and SessionFactory do not need to be adjusted, except that you need to inject your subclass of AbstractRoutingDataSource into the Hibernate SessionFactory.
Configuring multiple data sources and session factories in your spring context will not itself be a problem, but it does make autowiring less attractive.
You could use the #Qualifier annotation to tell the autowiring which one to choose, but I'd suggest not using autowiring, and instead explicitly injecting the correct data source and session factory using <property> or <constructor-arg>.
The transaction manager could potentially be shared between both data sources, if both data sources are managed by your app server, but it sounds like having transactional integrity across both data sources is not a requirement for you, and that having separate transactions for each data source would be enough.
I have a SEAM app with some JPA/Hibernate entities. And I now wonder where to put my query, persistence methods.
The default choice seems to put them in a session bean layer with injected
#PersistenceContext(...) #Inject EntityManager entityManager;
But I think I would rather have the methods on the entities themselves. What are the pro's/con's?
Testablity?
Niceness?
Performance?
And does anyone have links to best practices for interacting with the EntityManager etc. from methods on the Entities rather than session beans?
Best,
Anders
I have no experience with SEAM, but from my experience with Java projects, I found it easiest to keep beans clear of persist methods. What we usually do:
Have beans for business objects (like "User" and "Setting" for example)
Have a DAO layer which can persist and retrieve these beans (simple CRUD)
Have a Service Layer which nows how to handle the beans, and maybe even how to build an aggregate of beans
This way, everything is pretty separated, and is easy to unittest. Performance is usually not an issue with this setup.
Yes, that is also what I have done before.
In general, I think, EJB is insanely verbose and boilerplate'y, but SEAM actually helps a bit, so that is why, in my current project, the extra layer of session beans just to query and persist annoys me. I have the feeling that I could make a reasonably concise app if I could kill this layer...