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

后端 未结 2 479
误落风尘
误落风尘 2020-12-17 05:04

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

2条回答
  •  伪装坚强ぢ
    2020-12-17 05:50

    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.

提交回复
热议问题