What is the easiest way to have CDI and JPA in Java SE?

I would like to have in Java SE

@Stateless public class CarDAO { @Inject private EntityManager em; public Car findById(Long id) { return em.find(Car.class, id); } } @Singleton public class Application { @Inject private CarDAO carDAO; public void run() { Car car = carDAO.findById(44); System.out.println(car); } } public class EntryPoint { public static void main(String[] args) { Application application = // missing code application.run(); } } 

What should I do to achieve this? I am using postgres and maven database in my project.

I already read something about Weld (but it only looks like CDI). I don’t know how to add the ability to embed Entity Manager into Weld. I know that I can get Entity Manager with

 EntityManagerFactory emf = Persistence.createEntityManagerFactory("mgr"); EntityManager em = emf.createEntityManager(); 

but it’s not as convenient as an injection.

It would be great if taught about it. Anyway, thanks for any help!

+8
java jpa cdi entitymanager
source share
2 answers

First of all, EJBs are part of Java EE, so you cannot use them in Java SE. However, CDI can be used in the Java SE environment, my example will show you how to use it with Weld, but there are other implementations - note that CDI is just a specification, and Weld is one of the implementations of this specification.

To use Weld, you need to either put weld-se-xxx-Final.jar in the classpath, or specify its dependency in Maven as

 <dependency> <groupId>org.jboss.weld.se</groupId> <artifactId>weld-se</artifactId> <version><!-- See https://mvnrepository.com/artifact/org.jboss.weld.se/weld-se for current version --></version> </dependency> 

Then you need to run the container in the main method, so do something like this

 public static void main(String[] args) throws IOException { Weld weld = new Weld(); WeldContainer container = weld.initialize(); Application application = container.instance().select(Application.class).get(); application.run(); weld.shutdown(); } 

This should get you started, then you can use CDI Producers to inject your EntityManager

 @Produces @RequestScoped public EntityManager createEntityManager() { return Persistence.createEntityManagerFactory("mgr").createEntityManager(); } public void closeEM(@Disposes EntityManager manager) { manager.close(); } 

See Also Provides documentation on using CDI in Java SE .

+14
source share

Peter's answer seems to work, but Maven's dependencies are deprecated (see this error )

 <dependency> <groupId>org.jboss.weld.se</groupId> <artifactId>weld-se-core</artifactId> <version>2.3.1.Final</version> </dependency> <dependency> <groupId>org.jboss.weld</groupId> <artifactId>weld-core</artifactId> <version>2.3.1.Final</version> </dependency> <dependency> <groupId>org.jboss</groupId> <artifactId>jandex</artifactId> <version>1.2.2.Final</version> </dependency> 
+1
source share

All Articles