Articles
Developer: Eclipse
Introduction to Oracle Enterprise Pack for Eclipse 11g JPA WorkbenchBy Andrei Cioroianu Learn how to use Oracle Enterprise Pack for Eclipse (OEPE) to build Java EE applications that map objects to relational databases, using Java Persistence API (JPA). Oracle Enterprise Pack for Eclipse (OEPE) is a set of certified plugins for developing Java EE applications that can be deployed very easily on Oracle WebLogic Server from the Eclipse IDE. In this article, you'll learn how to use the Java Persistence API (JPA) editors and wizards of OEPE, which let you create entities from existing tables or from Java classes. You'll also learn how to develop session beans and servlets for testing your entities. All these components will be packed in a Java EE application that runs on the WebLogic server. The article assumes that you have installed Eclipse 3.4 with OEPE 11g, Oracle WebLogic 10g Release 3, and Oracle Database XE. Application SetupIn this section, you'll find out how to configure WebLogic in Eclipse, which will allow you to use Java EE APIs in your code and deploy applications directly from the IDE as you'll see later in this article. You'll also learn how to setup a data source in Eclipse and WebLogic, and create a JPA project, using the wizards of OEPE 11g. Configuring Oracle WebLogic Server in Eclipse First of all, make sure you have a WebLogic domain properly configured. To create a new domain or view the existing ones, click Start > Programs > Oracle Fusion Middleware > WebLogic Server 10.3 > Tools > Configuration Wizard.
Figure-1 After verifying or creating the WebLogic domain, return to Eclipse, click File > New > Other..., select Server, and click Next.
Figure-2 Enter the server's host name, select Oracle WebLogic Server 10gR3 , and click Next.
Figure-3 Select the WebLogic Home and click Next.
Figure-4 Select the Server Type and the Domain Directory, and click Finish.
Figure-5 To start WebLogic from Eclipse, go to the Servers view, right-click Oracle WebLogic Server 10gR3, and click Start. Connecting to the Oracle Database from Eclipse and WebLogic If you've just installed the Oracle database, you must unlock the HR user so that you can access the sample schema of Oracle Database XE. Click Start > Programs > Oracle Database 10g Express Edition > Go To Database Home Page . Login as SYSTEM, using the password you provided during the installation of Oracle Database XE, click Administration > Database Users > HR, enter a password twice for the HR user, select Unlocked, and click Alter User.
Figure-6 Now you can configure the database connection in Eclipse. Click Window > Show View > Other..., select Data Management > Data Source Explorer, and click OK. Right click Database Connections, click New, select Oracle Database Connection, enter the hr name for the connection, and click Next.
Figure-7 Select Oracle Database 10g Driver Default , change the server name in the jdbc:oracle:thin:@localhost:1521:xe URL if necessary, enter the hr user name and its password, click Test Connection to verify that everything is correct, and click Finish.
Figure-8 Right-click the hr schema, click Connect if you aren't already connected, expand hr > orcl > Schemas, right-click HR, and click Show in Schema Viewer.
Figure-9 You must also configure the hr data source in WebLogic so that it can be used in your applications. Open http://localhost:7001/console/ in your Web browser, login and click JDBC > Data Sources. Click New, enter the hr name and the hr JNDI name, select the Oracle database type, select Oracle's Driver (Thin) Versions: 9.0.1, 9.2.0, 10, 11, and click Next. Leave the Transaction Options unchanged and click Next. Enter the xe database name, your database host name, the 1521 port number, the hr user name, the password, and click Next. Verify the URL, which should be something like jdbc:oracle:thin:@localhost:1521:xe and click Next. In the last screen, check AdminServer and click Finish. Important! Click Log Out in WebLogic Server Administration Console so that you can deploy applications from Eclipse. If you ever see the following error in Eclipse, you should go to the WebLogic console and log out.
Figure-10 Creating JPA Projects Click File > New > Project... In the New Project window, expand the JPA node and select JPA Project. Then, click Next.
Figure-11 Enter the HRModel name, keep the Oracle WebLogic Server v10.3 target runtime, use the Utility JPA project with Java 5.0 configuration, select the Add project to an EAR checkbox, enter HRApp in the text field labeled EAR Project Name, and click Next.
Figure-12 The default JPA platform is Generic, which means you'll be able to use only standard JPA 1.0 features. Select the EclipseLink platform if you want to use features that will become part of JPA 2.0 or if you want to configure properties that are specific to the EclipseLink JPA implementation, such as Persistence Unit Customization, Caching, Logging, Session Options, and Schema Generation. Select the hr connection, leave the remaining settings unchanged, and click Finish.
Figure-13 Click Yes when you are asked if you want to open the JPA perspective.
Figure-14 Creating and Modifying EntitiesIn this section, you'll learn how to generate JPA entities from existing tables or from Java classes, how to view their associations in the JPA Entity Editor, how to modify your entities in the JPA Structure and JPA Details views, and how to use the JPA configuration editor. All these wizards are provided by OEPE 11g. Creating Entities from Tables Next, you'll generate two entity classes from the DEPARTMENTS and EMPLOYEES tables of the HR schema. The CREATE statements of those tables are included below. You don't have to run them since the tables already exist. Take a look at the foreign keys because we'll discuss about them later in the article.
Right-click the newly created HRModel project, click JPA > Generate Custom JPA Entities..., make sure the hr connection is selected, and click the Connect icon if enabled. (If you're already connected the button is disabled.) Select the DEPARTMENTS and EMPLOYEES tables, and click Next.
Figure-15 In a real application, you'll normally generate entities for all the tables of the schema. For learning purposes, however, it is simpler to start with fewer tables. The JPA wizard will analyze the foreign keys to suggest three table associations for the two selected tables of this example.
Figure-16 In most cases, the schema doesn't contain enough information for the wizard to figure out exactly what you need. Therefore, you'll typically have to edit the associations. Click the first one, which is between the DEPARTMENTS and EMPLOYEES. Rename the employee property to manager, and uncheck Generate a reference to a collection of DEPARTMENTS in EMPLOYEES.
Figure-17 Click the second association, which allows each department to obtain its employees and each employee to get his/her department. There is no change to be made here.
Figure-18 Click the third association, which would allow each employee to reach his/her manager and each manager to get the subordinates. This information can also be obtained through the previous association. Therefore, the third association is redundant and can be removed. Uncheck Generate this association and click Next.
Figure-19 Use the default options in the following screen, provide the hr.model package name, and click Next.
Figure-20 The last screen lets you change the names of the entities as well as the names and types of their properties. None of these changes are necessary in this example. Click Finish to generate the Java classes.
Figure-21 Right-click the HRModel project and click JPA > Show in Entity Editor to view a diagram containing the entities you've just created and the relationships between them.
Figure-22 Here is the source code that the wizard generates for the Department entity:
The wizard also generates the Employee class:
In this example, the JPA wizard was able to suggest the associations because the database schema had information about the foreign keys. Sometimes, however, the foreign keys aren't explicitly defined by the schema and you don't have the permission to alter the tables in order to add the foreign keys. In such a situation, you can still use the wizard to define the table associations. Important! You don't need to follow the remaining steps of this sub-section if the schema contains the foreign keys. Let's suppose the HR sample schema didn't have the foreign keys. In this case, the Table Associations list of the Generate Custom Entities wizard would have been empty as shown in the following screen.
Figure-23 To add an association, you could have clicked the + (New Association) button to start the Create New Association sub-wizard. For example, if you want to define here the relationship between EMPLOYEES and DEPARTMENTS, using the DEPARTMENT_ID column, select the two tables as in the following screen and click Next.
Figure-24 Then, click Add, select the DEPARTMENT_ID column for both tables, and click Next.
Figure-25 In the Association Cardinality screen of the sub-wizard, select Many to one and click Finish.
Figure-26 After that, you can see the association in the main wizard.
Figure-27 In conclusion, the Generate Custom Entities wizard lets you modify the suggested associations and add new ones that aren't specified in the schema as foreign keys. This works during the creation of the entities. As you'll see later in this article, you can also define and modify associations after the entity creation, using the JPA Structure and JPA Details views. Creating Entities from Java Classes The sample application with this article started with an existing database, which was used to generate the entities. You can also create the Java classes first, and then, use JPA > Generate DDL... to create the tables. A third option is to map an existing class to an existing table. In this section, we'll build a new entity from a Java class that will be mapped to the JOBS table, whose CREATE statement is included below:
Create a new class named Job in the hr.model package and paste the following code:
Right-click the HRModel project and click JPA > Generate Entity from Java Class... Click the Browse icon, select the hr.model.Job class, and click Next.
Figure-28 Make sure the hr connection and HR schema are selected, select the JOBS table, leave jobId selected as Primary key property, and click Next.
Figure-29 Verify that the properties are mapped correctly to the columns of the JOBS table and click Finish.
Figure-30 The wizard will add the following annotations to the Job class.
Using JPA Structure and JPA Details Open the Employee entity and replace the String jobId field with Job job. You'll also have to remove the @Column(name="JOB_ID") annotation and replace the getJobId() and setJobId() methods with getJob() and setJob().
Eclipse will report an error: Column "job" cannot be resolved. Go to the JPA Structure view in the upper-right corner, right-click job, and click Map As > Many to One. The wizard will add the @ManyToOne annotation.
Figure-31 You should see the JPA Detail view in the lower right corner. Verify that the job property is still the current one, select Eager in the Fetch list, check Override Default in the Join Columns section, and click the Edit button.
Figure-32 Replace job_JOB_ID in the Name field with JOB_ID. After clicking OK, you should see the @JoinColumn(name="JOB_ID", referencedColumnName = "JOB_ID") annotation above the job property. This will fix the error signaled above. Save the Job.java file.
Figure-33 Right-click the HRModel project and click JPA > Show in Entity Editor to view the updated diagram containing all three entities.
Figure-34 Editing the XML Configuration Files Expand the JPA Content folder of the HRModel project, and double-click persistence.xml. The configuration editor lets you set the properties of this file. Select the Connection tab and enter the hr data source.
Figure-35 Then, press Ctrl+S to save the persistence.xml file whose content is included below.
Testing EntitiesIn this section, you'll use more OEPE 11g wizards to create a stateless session bean and a servlet that allow you to test the entities created earlier. You'll also see how to deploy the whole application on WebLogic and run the servlet from Eclipse. Creating Session Beans Click File > New > Project... In the New Project window, expand the EJB node, select EJB Project, and click Next.
Figure-36 Enter the HREJB name, keep the Oracle WebLogic Server v10.3 target runtime, use the 3.0 EJB version and Default Configuration for Oracle WebLogic Server v10.3, select the Add project to an EAR checkbox, select HRApp, and click Next.
Figure-37 Leave the default options unchanged in the following screens and click Finish.
Figure-38 Right-click the HREJB project, click New > Session Bean, enter the hr.ejb package name, type the HRBean class name, use the Stateless type, leave the hr.ejb.HRBeanLocal name of the interface unchanged, and click Next.
Figure-39 Don't modify the default settings in the following screen and click Finish.
Figure-40 Open the hr.ejb.HRBeanLocal interface of the HREJBClient project, and add the following method.
You'll get a compilation error: Employee cannot be resolved to a type. To fix it, move the mouse cursor over Employee, click Fix Project Setup...
Figure-41 Select Add project 'HRModel' to build path of HREJBClient, click OK, and save the file.
Figure-42 Return to the HRBean.java file move the mouse cursor over the class name, which should be underlined with red, and click Add unimplemented methods…
Figure-43 Move the mouse cursor over the Employee return type of the added findEmployee() method, click Fix Project Setup..., select Add project 'HRModel' to build path of HREJB, and click OK. Then, add the following lines at the beginning of the HRBean class:
Move the mouse cursor over @PersistenceContext and click Import 'PersistenceContext' (javax.persistence). Move the mouse cursor over EntityManager and click Import 'EntityManager' (javax.persistence). Next, replace return null; with the following code within the findEmployee() method and save the HRBean class.
After saving the file you should see no error in the Problems view. Here is the complete source code of the HRBean class.
Creating Test Servlets Click File > New > Project... In the New Project window, expand the Web node, select Dynamic Web Project, and click Next.
Figure-44 Enter the HRTest name for the Web project, select the Add project to an EAR checkbox, select HRApp, and click Next.
Figure-45 Leave the default options unchanged in the following screens and click Finish.
Figure-46 Right-click the HRTest project, click New > Servlet, enter the hr.test package name, type the HRServlet class name, and click Finish.
Figure-47 Add these two lines at the beginning of the HRServlet class.
Move the mouse cursor over @EJB and click Import 'EJB' (javax.ejb). Move the mouse cursor over HRBeanLocal, click Fix Project Setup..., select Add project 'HREJBClient' to build path of HRTest, click OK, and save the file. Then, add the following code within the doGet() method of HRServlet.
Move the mouse cursor over PrintWriter and click Import 'PrintWriter' (java.io). Move the mouse cursor over Employee, click Fix Project Setup..., select Add project 'HRModel' to build path of HRTest, click OK, and save the HRServlet.java file. Expand HRTest > Java Resources > src > hr.test, right-click HRServlet.java, click Run As > Run on Server, and click Next.
Figure-48 Review the application being deployed and click Finish.
Figure-49 You should see the following screen.
Figure-50 Add ?emp=101 at the end of the URL in Eclipse and press Enter. You'll see the screen included below.
Figure-51 SummaryIn this article, you learned how to build, deploy and test a Java EE application with Oracle Enterprise Pack for Eclipse (OEPE) and WebLogic. We focused on the JPA-related features and wizards that allow you to create entities from tables or from Java classes, and then modify them in easy-to-use editors and property sheets. Andrei Cioroianu is the founder of Devsphere, a provider of Java EE development and Web 2.0/Ajax consulting services. He's been using Java and Web technologies since 1997 and has over 10 years of professional experience in solving complex technical problems and managing the full life cycle of commercial products, custom applications, and open-source frameworks. You can reach Andrei through the contact form at www.devsphere.com. |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||