Dariusz Mydlarz Dariusz Mydlarz - 1 year ago 76
Java Question

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

I would like to have in Java SE

public class CarDAO {
private EntityManager em;

public Car findById(Long id) {
return em.find(Car.class, id);

public class Application {
private CarDAO carDAO;

public void run() {
Car car = carDAO.findById(44);

public class EntryPoint {
public static void main(String[] args) {
Application application = // missing code

What I have to do to achieve that? I'm using postgres database, and maven in my project.

I was already reading something about Weld (but it looks only like CDI). I don't know how to add to Weld
possibilty to inject Entity Manager. I know that I can obtain Entity Manager with

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

but it's not so convenient as injecting.

It would be great if there is any tutorial about that. Anyway, thanks for any help!

Answer Source

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

In order to use Weld, you need to either put weld-se-x.x.x-Final.jar on the classpath or specify its dependency in Maven like

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

Then you need to startup the container in your 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();

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

public EntityManager createEntityManager() {
   return Persistence.createEntityManagerFactory("mgr").createEntityManager();

public void closeEM(@Disposes EntityManager manager) {

See also Weld documentation on using CDI in Java SE.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download