Hibernate - CDI - java

I have a few Hibernate Envers listeners which I use for audit purposes. I am just getting started on CDI and so far am pleasantly surprised by its simplicity and power. Since it seems everything is integrating CDI functionality, I thought I'd raise the question, is Hibernate supporting it or will it?
Not only would it be nice to have access to various components, but it would also be great to have access to other contextual information easily and not be limited by Hibernate's interfaces.

The question should be the other way around - will CDI support hibernate integration.
What CDI has to support, probably via an extension, is:
injecting an EntityManager where there is #PersistenceContext, and EntityManagerFactory where there is #PersistenceUnit
transaction and session lifecycle handling
Google for "Weld Persistence Context" and you'll get some examples of how to use Hibernate (JPA) with Weld, which is the reference implementation of CDI. Read this thread as well. And this example

Related

How to inject EntityManager in Java SE using #PersistenceContext (EclipseLink)

I have a client-server application that I made for a project at my university and I'm having problems with the database-JPA Cache synchronization. I'm using an application-managed EntityManager about which I found out from other posts that it's really hard to use because you always have to be careful to open and to close it.
The best solution which I found to this problem is to use a container-managed EntityManager, initialized using the #PersitenceContext annotation and this way I wouldn't have to worry about the EM opening and closing anymore.
So my real question is, how the injection of an EntityManager in Java SE using EclipseLink JPA is done, because I never passed the NullPointerException. I will attach some printscreens of an example of this operation and the way I think it should be done.
For my project I'm using jdk 1.8, basic jpa configuration(2.1) and EclipseLink 2.5.x as platform. On the DB side I'm using MySql-Server and no application server( this one has to be developed by me).
The persistence.xml file
The 2 classes which contain the example:
https://gyazo.com/a7b1a372875a259096dc220653cd5bcd
You cannot use the container managed persistence according to the used technologies listed by you because you do not have a container which could handle the injection. My understanding is that you are not in a JEE application server therefore you do not have an EJB container.
If you want to use JPA in a standalone application you can do 2 things:
Forget the injection and use the application managed persistence.
Use a spring container and you can still inject: How to inject JPA EntityManager using spring

Is JSF doesnt use Dependency Injection? [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.

Using Hibernate ORM without Spring

I'm writing a JavaFX Application which previously use Spring/QueryDSL for DI and persistence.
I'm hoping to move to using either Dagger or Guice (instead of spring) and Hibernate ORM.
I have noticed that Spring offers some nice functionality on top of hibernate, such as transaction management via #Transactional.
Are there other means of avoiding "boilerplate code" such as opening sessions, beginning transactions, committing transactions and closing sessions via some sort of hibernate configuration? Or are these features I'm really only going to get if I use Spring?
Guice has #Transactional support for JPA providers such as Hibernate using guice-persist, Dagger does not mention support for this.
If you are using Hibernate as your JPA provider, using Spring with #Transactional would probably be the most natural fit for building your backend. You would find a loss less documentation, examples, blog posts, books and online help in general using other alternatives than with Spring/Hibernate.

Using both JPA EntityManager and Hibernate session with shared transaction manager in Spring

We have a hard situation.
There is a large project which uses hibernate special features so cannot quit hibernate.
We are to add Activiti process engine to the project in embedded mode and make use of JPA extensions (which only works with EntityManager)
Some entities should not be present in JPA persistent unit because as activiti documentation says all entities must have #Id and cannot use #IdClass/#EmbeddedId so we have to exclude such entities from persistent unit
We wish to use one shared transaction manager for EntityManager and Session. Also the dataSources are identical (or even shared)
Everything is Spring!
All this effort is to enable Activiti to use EntityManager for its JPA extension while letting existing hibernate dependent codes to continue work.
First off, your 3rd point above may prove tricky to accommodate if you want to have one persistence unit and you're actually using #IdClass/#EmbeddedId in your Hibernate entities. Here are two possible solutions:
Pull JPA into your project and configure a persistence unit for your existing Hibernate entities, but continute to delegate the existing calls to Hibernate by accessing the Session directly. In this case, your configuration would be moved over to JPA, but your code would not. This approach also assumes that you have some reasonable abstraction dispensing Session objects in a pluggable fashion. See this question for the crux of the solution. If you have zero flexibility on point 3 above, this approach may not be an option for you.
Create both a session factory and persistence unit and coordinate transactions using JTA with two XA datasources. Even though your data may reside in the same database, you'll want to make sure you create distinct datasources in your configuration if you take this approach. This will prevent Spring's transactional proxy from getting confused when you participate in the distributed transaction. This is probably the cleanest approach, but does carry the stigma of XA transactions which, depending on your container, is more of a political problem these days than a technical one.

Where (which layer) to put Entity query methods, "persist" methods etc.?

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...

Categories

Resources