简体   繁体   中英

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:

  1. Forget the injection and use the application managed persistence.
  2. Use a spring container and you can still inject: How to inject JPA EntityManager using spring

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM