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

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

Related

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.

Use Java EE Transaction Annotation

Plan is to move away from Spring Transaction towards Java EE transactions
I need to replace annotation (#Transactional)
org.springframework.transaction.annotation.Transactional
WITH
Java EE transaction annotation.
The issue is where I read it tells use EJB but EJB is not needed. Please give me a small example that use Java EE Transaction with out Spring and EJB.
From Java 1.5 for managing the transactions we have a API which is introduce in extended java package (also called Java Transaction API(JTA)) which a user can implement their own transaction isolation levels.No need of specifiec EJB modules to be introduce here.You can make your own class as Transnational manager by implementing a simple Interface defined by API call User Transaction.
Please refer the below Link for details of the usage.
[http://docs.oracle.com/javaee/5/api/javax/transaction/UserTransaction.html][1]
Hope this helps! Have a good Code.
Regards,
Jagadish

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.

Best way to do database access in a Java desktop application

I've been working in Glassfish 3, JPA and Java EE 6. In a web container you can just inject the Entity Manager into an EJB and let that handle your transactions, rollbacks, etc. What do I do in a desktop application. Obviously that does not work. I know I would still use JPA for ORM. But would I create an EntityMangerFactory and then create an Entitymanager from that? Would I have to handle my transactions manually? It would great if I could see some sample applications. Thanks!
EntityManagerFactory entityManagerFactory =
Persistence.createEntityManagerFactory("DS");
em = entityManagerFactory.createEntityManager();
You have to handle transactions, by calling em.getTransaction.begin() and em.getTransaction.commit(), if you don't use the spring-framework or something else.
Well i suggest to try using Spring +JPA, there you do not need a container ,it is just the application context and you can configure transactions there.
You will not take care of the transactions ,just annotate your methods that you want to be #Transactional.
You could use Spring, this will bring you the plesent you know from JEE6 to desktop applications. (Of course it is not 100% the same!)
Another option could be to use so called Embeddable EJB Container. It could provide you same services as injection, CMT etc which you might be accustomed to.
I've built a 2-tier Java Swing client using Hibernate and Swing, and I will never do it again. If I had to rebuild it today, I would use raw JDBC queries, or maybe a very thin ORM mapping framework like iBatis.
The reason that Hibernate (and I assume other JPA implementations, although my experience is only with Hibernate) is so different in a desktop environment is 1) because objects tend to have a much longer lifespan on the desktop, and 2) it's very hard to know when an object will be accessed, so correct transaction handling for lazy loading is problematic.
The web request-response paradigm is fundamentally transactional, so it's very easy to demarcate your transactions there. On the desktop, every keypress, even just a MouseMovedEvent, could potentially trigger a database query or lazy load, so it's much harder to know when to initiate and commit transactions.
Error handling and object refreshing is a big problem, since objects tend to have a much longer life (often for the duration of the application launch). In Hibernate, exceptions are non-recoverable, which means that you're supposed to reload everything from the db. This is fine on the web, but definitely not fine when you have thousands of objects embedded in various models throughout your GUI.

Hibernate - CDI

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

Categories

Resources