JPA For Beginners - Part 3


Your transaction can be managed either by Container or by Bean. I am using Container Management which does not need any JPA Manager Beans. Below given is a brief introduction about JPA Manager Beans


What are JPA Manager Beans ?
 
They are service beans that act as facades or controllers over a particular JPA entity. They encapsulate and abstract all of the data access code for creating, updating, deleting, and displaying information from your database using JPA entities.


JPA Manager Beans map one-to-one to a JPA entity. For example, if you have a Department entity, you can create a JPA Manager Bean named DepartmentManager, which contains all of the data access logic needed to work with the Department entity.


JPA Manager Beans are an ideal programming model for use in two-tier Web environments. They fill the role that would normally be filled by a session bean in an EJB environment. All of the business logic related to an entity is performed by the JPA Manager Bean.


The use of JPA Manager Beans is not limited to Web applications. They can be used anywhere that you want to take advantage of their data abstraction capabilities, such as an EJB project, a JPA Utility project, or even a plain Java project.


Note: If you want to use JPA inside of an EJB project, you may want to create an EJB Session Bean to contain all of your JPA logic.


JPA entities do not need to reside in the same project as the JPA Manager Beans. For example, your JPA entities can exist in a JPA Utility project or EJB project, and you can generate JPA Manager Beans for those entities inside of a Web project.


Country Entity Class

 
Step 10: Now let’s start with the EJB project for CountryJPA. If you want to use JPA inside of an EJB project, you may want to create an EJB Session Bean to contain all of your JPA logic. EJB version we are using is 3.0.  Create an EJB project named “CountryEJB3”. We can keep the same EAR project. So the EAR project will be shared among EJB and JPA projects. Click Finish.

Creating EJB 3 Project
Step 11: Once the project is created, create your Session Bean named “CountrySessionBean”. You can give mapped name as “CountryBean” and keep the transaction type as Container.


Creating Session Bean

Step 12: Now you can write your method for persisting data in Country table. You can see my method which inserts a row in the Country table. Remember, you need to declare your EntityManger and annotate with @PersistenceContext unitname with the name of your JPA project.

CountrySessionBean
Step 13: Now you need to create your UI project. Create a Dynamic Web project, add jsps and servlets for testing the application. I believe you are already an expert in Servlets and JSPs. Otherwise you can try with a JUnit test. Here is the demo of my project.

Country JSP Page

Country Table after insertion

Country Table after insertion

0 comments :

Post a Comment