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

泄露秘密 提交于 2019-11-29 05:09:10

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.

Unless your actually building an enterprise system and have a need for the added complexity of EJB, just use JPA. It sounds to me like your just building a web app and you need simple db access - go for JPA. We use OpenJPA, and have no issues with it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!