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

后端 未结 2 472
误落风尘
误落风尘 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.

    0 讨论(0)
  • 2020-12-17 05:56

    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.

    0 讨论(0)
提交回复
热议问题