Assignment title: Information


SWE80005 Ent. Dev. Lab 03 Entity Class using JPA ãSwinburne University of Technology 2017 Page 1 of 7 Note: This document is developed based on the NetBeans IDE 6.7.1 and then modified to suit NetBeans IDE 6.9.1 and NetBeans IDE 7.1. If there are any discrepancies in the newer version of NetBeans IDE, please let the tutor know. Modification history Created:(long time ago J) Modified on: 2nd March 2011 Purpose: Update the instructions for NetBeans 6.9.1 Modified on: 9th Jan 2012 Purpose: Update the instructions for NetBeans 7.1 Modified on: 27th March 2013 Purpose: 1. Add actions to overcome "missing database tables" in LT2.31 2. Add actions to overcome deployment issues in LT6 Modified on: 11th April 2013 Purpose: Add reminder to the "Include All Entity Classes …" option in LT4.5 Modified on: 8th Feb 2017 Purpose: Update the instructions on NetBeans 8.2 Modified on: 7th Mar 2017 Purpose: Fix a mistake in LT5.5 Software To finish the lab, you may need the following software: 1. NetBeans IDE version 8.2 or later (or, NetBeans) 2. JDK version 1.8.0 update 60 or later (or, JDK) 3. GlassFish Server Open Source Edition version 4.1.1 or later (or, GlassFish) [JavaDB is the database server that comes with GlassFish.] Aim Write a program that makes use of Java Persistence API to add a new record to a database table. We do this as JPA application. My intention is for you to have some exposures on programming JPA without using Java EE. The techniques of programming JPA applies to other ORM technologies such as Hibernate. Figure 1 shows a rough design of "MyuserApp" and its related classes. It also shows related the roles of these classes in the project. The application "MyuserApp.java" will handle the input from users to perform the CRUD operations of MYUSER database table via the Myuser class using JPA (or, ORM). In order to manage to search relevant information from the MYUSER database (without executing any SQL statements) and return with proper Myuser objects, it is better to have a separate JPA controller class rather than doing everything in the Myuser class. We call this JPA controller class "MyuserDB", I name it as "…DB" because it emulates the required database functions. 1 The references to these Learning Tasks in Modification History may be invalid due to version updating and tasks changes.SWE80005 Ent. Dev. Lab 03 Entity Class using JPA ãSwinburne University of Technology 2017 Page 2 of 7 Figure 1 A rough design of MyuserApp ED#JPA'project MyuserApp MyuserDB Myuser (object) DB2server MYUSER2 (table) Thin2client2(UI) @ Get2input2from2users @ Display2output2to2users MyuserDB (Controller) @ Emulate2DB2function @ ORM2APIs2here Myuser (Entity2class) @ Map2to2MYUSER2table DB2server @ Actual2DB2functions MYUSER2(database2table) @ Store2informationSWE80005 Ent. Dev. Lab 03 Entity Class using JPA ãSwinburne University of Technology 2017 Page 3 of 7 PreLab Task Before this Lab, you need to first create the database table MYUSER in "sun-appserv-samples" on "Java DB" and load some data into the table, as documented in Lab_02_Database_Connectivity. If you have completed the program in Lab_02_Database_Connectivity, you are all set except you manually delete the table or alter the data in between. In that case, you can rerun the program (assuming you have not changed anything) to recreate the database table MYUSER and reload some data in the table. Overview of Lab Tasks In this Lab, you will learn to perform the following tasks in programming an entity class: LT1. Create a Java Class Library project LT2. Program an Entity Class using the Java Persistence API (JPA) LT3. Create a Java Application Project LT4. Add a project to another project LT5. Program a JPA controller class in the application project LT6. Create a DTO for the entity class created in LT2 above LT7. Program the thin client for the application project LT8. Program the remaining methods required LT9. Run the application and verify the results Lab Tasks This Lab should be run on MS Windows Platform LT1. In this Lab task, you will create a new Java Class Library project in NetBeans called "ED-Entity" LT1.1 Select "File" > "New Project" LT1.2 Choose "Java" > "Java Class Library", then click "Next" LT1.3 Enter "ED-Entity" in the Project Name field LT1.4 Click "Finish" Note: NetBeans creates the project. There is no Main class as suggested by the type of the project that we choose. LT2. In this Lab task, you will learn how to program the "Entity Class", Myuser. Make sure that you have completed the PreLab Task above. Note: We cannot reuse the "Myuser.java" class created in previous Lab because it is a normal Java class. You need to follow the instructions below to perform this task. LT2.1 Select "ED-Entity " project LT2.2 Right click the mouse and select "New" > "Entity Class from Database…" (See Note below if you cannot find this option) Note: If you cannot find "Entity Class from Database…", select "Other…". Then, in the "New File" window, choose "Persistence" in the "Categories:" selection box, then choose "Entity Classes from Database" in the "File Types:" selection box. Then, click "Next". LT2.3 In the "New Entity Classes from Database" window, select "jdbc:derby://localhost:1527/sun-appserv-samples [APP on APP]" (the one used in your PreLab Task) in the Database Connection field and put the "MYUSER" table in the "Selected Tables" text are (Make sure the "Include Related Tables" check box is checked) Note: If you cannot find the "MYUSER" table in the "Available Tables:" field, make sure your database connection string is right and you have set up the database properly with the proper username "APP" and password "APP". You may want to remove the database and recreate one with the right settings. LT2.4 Click "Next" Note: A new dialog box appears with "MYUSER" in the "Class Names" field and "ED-Entity" in the Project field LT2.5 Enter "entity" in the Package field LT2.6 Make sure that the following check boxes are checked a. "Generate Named Query Annotations for Persistent Fields"SWE80005 Ent. Dev. Lab 03 Entity Class using JPA ãSwinburne University of Technology 2017 Page 4 of 7 Note: By checking the box, NetBeans will create some standard named queries like "Myuser.findAll" to find all myusers in the database table "Myuser.findByUserid" to find a particular myuser using userid (userid is the primary key of the table) … (others omitted) … b. "Generate JAXB Annotations" Note: By checking the box, NetBeans will create some standard annotations that allow the entity class to be used via JAXB web services. We do not need this actually. c. "Create Persistence Unit" LT2.7 Click "Finish" Note: NetBeans will automatically generate the entity POJO "Myuser.java" for you, including some named queries. Note: If you do not have any methods to update the data, this entity class is now complete. Note: This entity class is a Data Access Object (DAO) that is responsible for holding the required information for the records in the MYUSER database table. Note: In the source folder, you can see a "package" called "META-INF". The file "persistence.xml" is the persistence unit of Myuser, in xml format and act as a config file. Note: In the Libraries folder, there are three additional EclipseLink libraries. They are the standard JPA libraries. Question to think further / deeper: Why "Myuser.java" needs to implement the "Serializable" interface? LT3. Create a new Java Application Project in NetBeans called "ED-JPA" LT3.1 Select "File" > "New Project" LT3.2 Choose "Java" > "Java Application", then click "Next" LT3.3 Enter "ED-JPA" in the Project Name field LT3.4 Check the "Create Main class" check box and enter "ej.jpa.MyuserApp" in the corresponding text field LT3.5 Click "Finish" Note: NetBeans now creates the project for you. You will also have a "public static void main()" method in MyuserApp.java. In the following, we are going to add the "ED-Entity" project to the "ED-JPA" project. The actual project jar file will be added. By doing so, we achieve reusability. LT4. Add a project to another project LT4.1 Right click on "Libraries" under the "ED-JPA" project, then select "Add Project…" LT4.2 In the "Add Project" windows, select "ED-Entity" LT4.3 Click "Add Project JAR Files" Note: NetBeans now adds the "ED-Entity.jar" file to the Libraries. LT5. Program a JPA controller class in the ED-JPA project LT5.1 In the ED-JPA project, right click on package "ed.jpa" under "Sources Packages" LT5.2 Select "New", then "Java Class…" LT5.3 In the "New Java Class" window, enter "MyuserDB" in the "Class Name" field LT5.4 Click "Finish" LT5.5 Copy and paste the following code segment into MyuserDB private EntityManager em = null; public MyuserDB() { // using default persistence unit defined in the persistence.xml file EntityManagerFactory emf = Persistence.createEntityManagerFactory("ED-EntityPU"); em = emf.createEntityManager(); } public EntityManager getEntityManger() { return em; }SWE80005 Ent. Dev. Lab 03 Entity Class using JPA ãSwinburne University of Technology 2017 Page 5 of 7 Note: This time, "Fix imports" does not work because the JPA libraries are not in the standard Java libraries. We will add them to the project in the next learning task. LT5.6 In this learning task, we need to add the JPA libraries (and Java DB libraries) to the "EDJPA" project a. Right click on the "Libraries…" in the "ED-JPA" project and select "Add Library…" b. In the "Add Library" window, select "EclipseLink (JPA 2.1)" and "Java DB Driver" together (holding the "Windows" key allows you to make multiple selections) c. Click "Add Library" Note: NetBeans will then add the relevant libraries into the project. d. Remember to fix imports… LT5.7 Copy and paste the following code segment after the getEntityManager() method public Myuser findMyuser(String userid) { return em.find(Myuser.class, userid); } public boolean createMyuser(Myuser myuser) throws Exception { try { if (findMyuser(myuser.getUserid()) != null) { // myuser exists already return false; } // myuser does not exist in database em.getTransaction().begin(); em.persist(myuser); // to add an object to database em.getTransaction().commit(); return true; } catch (Exception ex) { throw ex; } } Remember to fix imports and … LT6. Program the DTO (data transfer object) class for "Myuser.java", we call this "MyuserDTO.java" LT6.1 Create a new Java class called "MyuserDTO" in the package "ed.jpa" LT6.2 Make sure that "MyuserDTO" implements the "java.io.Serializable" interface Hint: Add "implements Serializable" in between "public class MyuserDTO" and "{". Remember to fix imports. LT6.3 Copy and paste the following code segments into "MyuserDTO" class private final String userid; private final String name; private final String password; private final String email; private final String phone; private final String address; private final String secQn; private final String secAns; public MyuserDTO(String userid, String name, String password, String email, String phone, String address, String secQn, String secAns) { this.userid = userid; this.name = name; this.password = password; this.email = email; this.phone = phone; this.address = address; this.secQn = secQn; this.secAns = secAns; } LT6.4 Generate the getters of these instance variables (Only getters are required. No setters.) Question to think further / deeper: What is the role of a DTO? How is it different from a DAO?SWE80005 Ent. Dev. Lab 03 Entity Class using JPA ãSwinburne University of Technology 2017 Page 6 of 7 LT7. Program the thin client, MyuserApp, to add data to database via JPA LT7.1 Copy and paste the following code segment to "MyuserApp.java" private MyuserDB mydb; public MyuserApp() { mydb = new MyuserDB(); } public static void main(String[] args) { MyuserApp client = new MyuserApp(); // assuming inputs from keyboard or any GUI MyuserDTO myuserDTO = new MyuserDTO("000001", "Edmonds Lau", "123456", "[email protected]", "9876543210", "Swinburne EN510a", "What is my name?", "Edmonds"); boolean result = client.createRecord(myuserDTO); client.showCreateResult(result, myuserDTO); // assuming inputs from keyboard or any GUI MyuserDTO myuserDTO2 = new MyuserDTO("000006", "Man Lau", "654321", "[email protected]", "9876543210", "Swinburne EN510a", "What is my name?", "Edmonds"); result = client.createRecord(myuserDTO2); client.showCreateResult(result, myuserDTO2); } public void showCreateResult(boolean result, MyuserDTO myuserDTO) { if (result) { System.out.println("Record with primary key " + myuserDTO.getUserid() + " has been created in the database table."); } else { System.out.println("Record with primary key " + myuserDTO.getUserid() + " could not be created in the database table!"); } } public boolean createRecord(MyuserDTO myuserDTO) { return mydb.createRecord(myuserDTO); } Note: In the next task, we will program the createRecord() method in the MyuserDB class. LT8. Program the remaining methods required in the MyuserDB class LT8.1 Copy and paste the following code segment in the MyuserDB class public boolean createRecord(MyuserDTO myuserDTO) { Myuser myuser = this.myDTO2DAO(myuserDTO); boolean result = false; try { result = this.createMyuser(myuser); } catch (Exception ex) { } return result; } private Myuser myDTO2DAO(MyuserDTO myDTO) { Myuser myuser = new Myuser(); myuser.setUserid(myDTO.getUserid()); myuser.setName(myDTO.getName()); myuser.setPassword(myDTO.getPassword()); myuser.setEmail(myDTO.getEmail()); myuser.setPhone(myDTO.getPhone()); myuser.setAddress(myDTO.getAddress()); myuser.setSecqn(myDTO.getSecQn()); myuser.setSecans(myDTO.getSecAns());SWE80005 Ent. Dev. Lab 03 Entity Class using JPA ãSwinburne University of Technology 2017 Page 7 of 7 return myuser; } LT8.2 Remember to save all the modifications made LT9. Run "MyuserApp" and verify the results Final Word Start from next week onwards, we will do "Java EE" stuff – the real deal. That will be more fun, more challenging and, I can guarantee you, "MORE FRUSTRATING" – You are warned.Faculty of Science, Engineering and Technology SWE80005 Enterprise Development [Java EE] Pass Task 3.1 Entity Persistence and ORM Time Frame: Weeks 3 – 4 Suggested to start and complete in Week 3 Submission Due: Week 3, Fri, 5:00pm Overview In this task, you are required to program a data access object that can access the content of a database table via Entity Persistence technologies, or Java Persistence API. You are also required to demonstrate your work is of good quality. Purpose To demonstrate your ability to develop quality application that involves the uses of entity persistence technologies to access the database content Tasks 1. Learn to develop an application that uses JPA API to manage an entity class 2. Extend the application so that it can handle all CRUD operations 3. Develop a client program that requests the actual CRUD operations provided by the entity class / object developed in 1 and 2 above as your test harness 4. Prepare your test cases and test your application thoroughly by using various database contents (e.g. different records) 5. Answer questions related to the design of the project Pre-req Task1 Pass Task 2.1 Follow-up Task2 Pass Task 4.1 Suggested Time 1 hour if you know the stuff well 4 - 5 hours if you need to read the concepts and learn how to use ORM to map to a database server Resources Lecture 03 Entity ORM Java EE – JPA Feedback Ask your tutor for feedback Next task Pass Task 4.1 Pass Task 3.1 Submission Details and Assessment Criteria You must create your own document (pdf) in portrait mode3, which you will upload to Doubtfire, with the following details: • Your name and student id • Your tutor's name • Your own responses to the tasks according to the corresponding instructions (see below) Tasks and Instructions Task 1. Complete Lab_03_Entity_Class_JPA Task 2. Programming [Assume you have completed Task 1 above] Add the following methods in the MyuserDB.java class (Lab_03_Entity_Class_JPA) that supports the remaining CRUD operations of MYUSER using JPA 1 You need to complete the pre-requisite task before doing this task. 2 You need to complete this task in order to do the follow-up task because the follow-up task depends on your answer in this one. 3 Landscape mode pdf does not work properly in Doubtfire.Faculty of Science, Engineering and Technology SWE80005 Ent. Dev. Pass Task 3.1 Page 2 of 2 1. "MyuserDTO getRecord(String userId)" – accepts a String object whose value is the userId of a record to be searched. If the record can be found, it returns a MyuserDTO object that stores the information of the actual database record. Otherwise, it returns a "null" object. 2. "boolean updateRecord(MyuserDTO myuserDTO)" – accepts a MyuserDTO object and checks whether the actual record exists in the database. If it does, it will update the information of the record with the current information stored in the MyuserDTO object and return true. Otherwise, it returns false without doing anything. Hint: Use the EntityManager's instance method called merge() 3. "boolean deleteRecord(String userId)" – accepts a String object whose value is the userId of a record to be deleted. If the record can be found, it removes the record in the database and return true. Otherwise, it returns false. Hint: Use the EntityManager's instance method called remove() Task 3. Modify the MyuserApp.java class so that it acts as a test harness of the CRUD operations developed in Task 2 above Note: The client program can be a desktop application (either console or with GUI). Console is the simplest. Or, it can be a web application (but this is too much work at the moment). Task 4. Write your test cases (including the database content and input values) and test your work thoroughly. Remember to collect the relevant screen dump (e.g. "Console" in NetBeans or your "JUnit" test results) Task 5. Answer the following questions: 5.1. Which class is responsible for doing all the ORM work? MyuserDB / Myuser? Justify your answer 5.2. Is the role of the Myuser entity class here different from that of the "Myuser" class in the application in Lab 02. Why? Justify your answer. 5.3. Why Myuser entity class in this application domain is different from that in the Lab 02 (in the JDBC domain)? 5.4. Why Myuser and MyuserDTO need to implement Serializable interface? Submission Task Once completed, you need to submit a pdf file that contains all your work (e.g. selected code segments – show me the key stuff and some screen dumps of your testing) Demonstration You may be asked to demonstrate your assignment in the lab. You should be able to do this and explain your code when asked in the lab session.