Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database table access via JPA Vs. EJB in a Web-Application

I am designing a web-application that access many database tables. I am trying to figure out what is the preferred way to access those tables? Is it via JPA or EJB?

Thanks, Nathan

like image 937
Nathan Avatar asked Dec 16 '22 18:12

Nathan


1 Answers

The answer is 'both'.

EJB itself doesn't access any DB tables. Everything you do in Java that relates to the DB happens via the Java Persistence API (JPA), or if you want to do low level stuff via JDBC but let's not get into that here.

What EJB brings to the table is a very easy management of transactions. You always need those with JPA, and it's a bit of pain to manage these manually. EJB also gives you very easy access to main class that you will use in JPA to interact with the DB: the entity manager.

Using EJB in practice is for a lot of simple and lightweight situations nothing more than adding the @Stateless annotation to a bean:

@Stateless
public class FooService {

    @PersistenceContext
    private EntityManager entityManager;

    public Foo getByID(Long fooID) {
        return entityManager.find(Foo.class, ID);
    }
}

Without EJB, the code to do this simple find would be much more verbose. And without JPA, there simply wouldn't be any code. As said before, EJB has no functionality to access the DB.

like image 79
Arjan Tijms Avatar answered Feb 16 '23 01:02

Arjan Tijms