简体   繁体   中英

Integrate JSF with JPA

I did some research on JSF and JPA. Read some tutorials and followed some examples. Before this, I would create Managed Beans, Models and Services to handle my application.

What is the best practice to include JPA in this pattern? Should I include the JPQL queries and database calls in the same Service classes? In some example I saw JPA implemented in the same managed bean as the methods called in the Invoke application phase or I saw JPA implemented in other managed beans? What is the common practice to work with these two?

You should consolidate your JPA access into a DAO or service layer of one kind or another, if for no other reason you can then stub out that DAO layer for unit tests. All of your JSF managed beans would then route their JPA access through that class. That way, whenever you access JPA from your JSF managed beans, you can mock the single DAO method call rather than mocking EntityManager , Query , etc. individually.

Now, the harder question: should that DAO/service layer be another JSF managed bean, an EJB or something else altogether? That's in some sense less important than acknowledging that you want to separate JPA access.

Personally, I started out making DAOs as just another flavor of JSF managed beans using @ManagedProperty for injection. Then I discovered CDI in Java EE 6 and made them POJOs with @Named / @Inject instead.

If you are doing writes and not just reads, though, you should consider having a separate service layer on which you can declare transactions - probably @Stateless EJBs make the most sense if you're using JSF.

Hope this helps!

I am a self-learner, so please forgive my wording that may be not appropriate.

If you look at this answer , there is a link to NetBeans' wizard for creating RESTful web services. This is surely beyond the scope of your question, but the generated DAO classes are really helpful and can be used for JSF projects. If you want you can remove the JAX-RS RESTful annotation, but keep the rest.

Then I inject into my Beans the Facade classes auto-generated (making use of EJB annotations). In these Facade and Entity classes the base JPA queries are already written.

If you need to create more complicated queries, you can also use type-safe Criteria API instead of JPQL. The initial effort is bigger, but the Criteria API lets you write complex queries in a OO way that can be also helpful in concrete situations like the use of multiple conditions in the "WHERE" statement (whose number is dynamically generated like in an Advanced Search ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM