diff --git a/9781430219569.jpg b/9781430219569.jpg new file mode 100644 index 0000000..3376fb2 Binary files /dev/null and b/9781430219569.jpg differ diff --git a/GettingStarted.txt b/GettingStarted.txt new file mode 100644 index 0000000..f7a3b2e --- /dev/null +++ b/GettingStarted.txt @@ -0,0 +1,50 @@ + +These examples assume that you have installed Java SE 6 and Apache ant. + +Java SE 6 is available for download at http://java.sun.com/javase/downloads/index.jsp. +Apache ant is available for download at http://ant.apache.org. + +1. Assume the examples have been downloaded and unzipped to . + +2. Edit /config/setenv.bat to point to your JDK 1.6 ant 1.7.1 installation + directories if JAVA_HOME and ANT_HOME have not been set in your environment. + +3. Download and install Glassfish V3 from http://glassfish.dev.java.net. + We recommend installing the Glassfish V3 Web Profile (only a couple of demos, 3-3 and 3-7 will not run). + +4. Edit /config/common.properties and set: + + EXAMPLES_HOME - the folder in which the examples were unzipped + SERVER_HOME - the folder in which Glassfish was installed + + NOTE: Make sure you use a forward slash separator ('/') not a backward slash ('\') + +5. Start Glassfish and the Derby database by invoking the startservers.bat script + in /bin. + +6. Open /examples/examplesHome.html to get started. + + For each server-based example: + + 1. Run deploy.bat before running the example + 2. Run undeploy.bat when finished with the example + + The client-based examples have a run.bat script. They assume the database is + already runnning, as in sep 5. + +Notes: + +A. The first time you start the Glassfish server it will appear to hang at the + Felix intro. It should be faster every time after that. + +B. Derby seems to take a long time dropping non-existent tables, so the first time + deploying each of the tests it will take a little longer to execute the run_sql target. + You will also see the DROP TABLE commands fail. It's expected. + +C. Example 12 in Ch 4 will not run on Derby because Derby does not support sequences. + +D. A few of the tests in Ch 5 do not run correctly due to obscure Map support bugs in EclipseLink. + Installing a later version of EclipseLink into Glassfish might be necessary to get past these. + +E. If you plan on taking the demos and changing them for fun, and you get an exception that + an entity class is an "unknown entity type", you may need to bounce (stop and restart) the server. diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..ebd15e1 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,27 @@ +Freeware License, some rights reserved + +Copyright (c) 2010 Mike Keith, Merrick Schincariol, and Jeremy Keith + +Permission is hereby granted, free of charge, to anyone obtaining a copy +of this software and associated documentation files (the "Software"), +to work with the Software within the limits of freeware distribution and fair use. +This includes the rights to use, copy, and modify the Software for personal use. +Users are also allowed and encouraged to submit corrections and modifications +to the Software for the benefit of other users. + +It is not allowed to reuse, modify, or redistribute the Software for +commercial use in any way, or for a user’s educational materials such as books +or blog articles without prior permission from the copyright holder. + +The above copyright notice and this permission notice need to be included +in all copies or substantial portions of the software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS OR APRESS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + diff --git a/README.md b/README.md new file mode 100644 index 0000000..6950e37 --- /dev/null +++ b/README.md @@ -0,0 +1,15 @@ +#Apress Source Code + +This repository accompanies [*Pro JPA 2*](http://www.apress.com/9781430219569) by Mike Keith, Merrick Schincariol, and Jeremy Keith (Apress, 2010). + +![Cover image](9781430219569.jpg) + +Download the files as a zip using the green button, or clone the repository to your machine using Git. + +##Releases + +Release v1.0 corresponds to the code in the published book, without corrections or updates. + +##Contributions + +See the file Contributing.md for more information on how you can contribute to this repository. diff --git a/bin/bounceAppServer.bat b/bin/bounceAppServer.bat new file mode 100644 index 0000000..3fabd22 --- /dev/null +++ b/bin/bounceAppServer.bat @@ -0,0 +1,6 @@ +call ../config/setenv + +call %ANT_HOME%/bin/ant -f ../config/common.xml stop_server +call %ANT_HOME%/bin/ant -f ../config/common.xml start_server + +pause diff --git a/bin/startservers.bat b/bin/startservers.bat new file mode 100644 index 0000000..55a5e48 --- /dev/null +++ b/bin/startservers.bat @@ -0,0 +1,7 @@ +call ../config/setenv + +call %ANT_HOME%/bin/ant -f ../config/common.xml start_db +call %ANT_HOME%/bin/ant -f ../config/common.xml start_server + + +pause diff --git a/bin/stopservers.bat b/bin/stopservers.bat new file mode 100644 index 0000000..41c719c --- /dev/null +++ b/bin/stopservers.bat @@ -0,0 +1,6 @@ +call ../config/setenv + +call %ANT_HOME%/bin/ant -f ../config/common.xml stop_server +call %ANT_HOME%/bin/ant -f ../config/common.xml stop_db + +pause diff --git a/config/ant.bat b/config/ant.bat new file mode 100644 index 0000000..1ed703a --- /dev/null +++ b/config/ant.bat @@ -0,0 +1,7 @@ +@echo off +rem === Called from each example 3 levels down === + +call ../../../config/setenv.bat + +call %ANT_HOME%/bin/ant %1 + diff --git a/config/common.properties b/config/common.properties new file mode 100644 index 0000000..29be50a --- /dev/null +++ b/config/common.properties @@ -0,0 +1,43 @@ + +################################################## +# Installation properties +################################################## + +EXAMPLES_HOME=EXAMPLES_HOME_property_not_set_yet +SERVER_HOME=SERVER_HOME_property_not_set_yet + +################################################## +# Glassfish properties +################################################## + +ADMIN_USER=admin + +PASSWORD_PREFIX= +PASSWORD_FILE= + +# Uncomment out the following 2 lines if GlassFish was installed with an +# admin password, and enter the password in the password.txt file. +#PASSWORD_PREFIX=--passwordfile +#PASSWORD_FILE="${EXAMPLES_HOME}/config/password.txt" + +################################################## +# Derby Database properties +################################################## + +DERBY_INSTALL=${SERVER_HOME}/javadb +DERBY_PORT=1527 +DERBY_HOST=localhost +DERBY_USER=APP +DERBY_PWD=APP +DERBY_SYSTEM_HOME=${EXAMPLES_HOME}/database +DERBY_CLASSPATH=${DERBY_INSTALL}/lib/derby.jar;${DERBY_INSTALL}/lib/derbynet.jar;${DERBY_INSTALL}/lib/derbyclient.jar;${DERBY_INSTALL}/lib/derbytools.jar + +################################################## +# Additional library properties +################################################## + +ECLIPSELINK_CLASSPATH=${SERVER_HOME}/glassfish/modules/javax.persistence.jar;${SERVER_HOME}/glassfish/modules/org.eclipse.persistence.oracle.jar;${SERVER_HOME}/glassfish/modules/org.eclipse.persistence.core.jar;${SERVER_HOME}/glassfish/modules/org.eclipse.persistence.jpa.jar;${SERVER_HOME}/glassfish/modules/org.eclipse.persistence.asm.jar;${SERVER_HOME}/glassfish/modules/org.eclipse.persistence.antlr.jar;${SERVER_HOME}/glassfish/modules/org.eclipse.persistence.jpa.modelgen.jar; +SPRING_CLASSPATH=${EXAMPLES_HOME}/lib/spring.jar;${EXAMPLES_HOME}/lib/commons-logging.jar +J2EE_CLASSPATH=${SERVER_HOME}/glassfish/lib/javaee.jar +JPA_CLASSPATH=${SERVER_HOME}/glassfish/modules/javax.persistence.jar +CLIENT_CLASSPATH=${ECLIPSELINK_CLASSPATH};${J2EE_CLASSPATH};${DERBY_CLASSPATH} diff --git a/config/common.xml b/config/common.xml new file mode 100644 index 0000000..b9bf71b --- /dev/null +++ b/config/common.xml @@ -0,0 +1,197 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/config/password.txt b/config/password.txt new file mode 100644 index 0000000..f0ebfdb --- /dev/null +++ b/config/password.txt @@ -0,0 +1 @@ +AS_ADMIN_PASSWORD=adminadmin \ No newline at end of file diff --git a/config/setenv.bat b/config/setenv.bat new file mode 100644 index 0000000..8c1a494 --- /dev/null +++ b/config/setenv.bat @@ -0,0 +1,13 @@ +@echo off +rem === If these are not already set in your environment then uncomment and set these +rem === two to the directory appropriate to your environment. +rem +rem JAVA_HOME= +rem ANT_HOME= +rem +set ANT_HOME=c:\ant\apache-ant-1.7.1 + +if "%JAVA_HOME%"=="" echo "Need to set JAVA_HOME environment variable in \config\setEnv.bat" +if "%ANT_HOME%"=="" echo "Need to set ANT_HOME environment variable in \config\setEnv.bat" + + diff --git a/contributing.md b/contributing.md new file mode 100644 index 0000000..f6005ad --- /dev/null +++ b/contributing.md @@ -0,0 +1,14 @@ +# Contributing to Apress Source Code + +Copyright for Apress source code belongs to the author(s). However, under fair use you are encouraged to fork and contribute minor corrections and updates for the benefit of the author(s) and other readers. + +## How to Contribute + +1. Make sure you have a GitHub account. +2. Fork the repository for the relevant book. +3. Create a new branch on which to make your change, e.g. +`git checkout -b my_code_contribution` +4. Commit your change. Include a commit message describing the correction. Please note that if your commit message is not clear, the correction will not be accepted. +5. Submit a pull request. + +Thank you for your contribution! \ No newline at end of file diff --git a/database/Readme.txt b/database/Readme.txt new file mode 100644 index 0000000..0622e45 --- /dev/null +++ b/database/Readme.txt @@ -0,0 +1,2 @@ +This directory contains the Derby databases used for the examples. +They will be created when the examples are run. \ No newline at end of file diff --git a/examples/Chapter2/employeeService/build.xml b/examples/Chapter2/employeeService/build.xml new file mode 100644 index 0000000..90da33d --- /dev/null +++ b/examples/Chapter2/employeeService/build.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Chapter2/employeeService/etc/persistence/META-INF/persistence.xml b/examples/Chapter2/employeeService/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..441ce8e --- /dev/null +++ b/examples/Chapter2/employeeService/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,14 @@ + + + examples.model.Employee + NONE + + + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter2/employeeService/etc/sql/db.sql b/examples/Chapter2/employeeService/etc/sql/db.sql new file mode 100644 index 0000000..a6a8dd1 --- /dev/null +++ b/examples/Chapter2/employeeService/etc/sql/db.sql @@ -0,0 +1,4 @@ +DROP TABLE EMPLOYEE; + +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, NUMBER INTEGER, PRIMARY KEY (ID)); + diff --git a/examples/Chapter2/employeeService/lib/eclipselink.jar b/examples/Chapter2/employeeService/lib/eclipselink.jar new file mode 100644 index 0000000..f419dce Binary files /dev/null and b/examples/Chapter2/employeeService/lib/eclipselink.jar differ diff --git a/examples/Chapter2/employeeService/run.bat b/examples/Chapter2/employeeService/run.bat new file mode 100644 index 0000000..15bf23b --- /dev/null +++ b/examples/Chapter2/employeeService/run.bat @@ -0,0 +1,2 @@ +call ../../../config/ant +pause \ No newline at end of file diff --git a/examples/Chapter2/employeeService/runInteractive.bat b/examples/Chapter2/employeeService/runInteractive.bat new file mode 100644 index 0000000..d09b67b --- /dev/null +++ b/examples/Chapter2/employeeService/runInteractive.bat @@ -0,0 +1,2 @@ +call ../../../config/ant interactive_client +pause diff --git a/examples/Chapter2/employeeService/src/client/examples/client/EmployeeTest.java b/examples/Chapter2/employeeService/src/client/examples/client/EmployeeTest.java new file mode 100644 index 0000000..29956bb --- /dev/null +++ b/examples/Chapter2/employeeService/src/client/examples/client/EmployeeTest.java @@ -0,0 +1,51 @@ +package examples.client; + +import java.util.Collection; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import examples.model.Employee; +import examples.model.EmployeeService; + +public class EmployeeTest { + + public static void main(String[] args) { + EntityManagerFactory emf = + Persistence.createEntityManagerFactory("EmployeeService"); + EntityManager em = emf.createEntityManager(); + EmployeeService service = new EmployeeService(em); + + // create and persist an employee + em.getTransaction().begin(); + Employee emp = service.createEmployee(158, "John Doe", 45000); + em.getTransaction().commit(); + System.out.println("Persisted " + emp); + + // find a specific employee + emp = service.findEmployee(158); + System.out.println("Found " + emp); + + // find all employees + Collection emps = service.findAllEmployees(); + for (Employee e : emps) + System.out.println("Found Employee: " + e); + + // update the employee + em.getTransaction().begin(); + emp = service.raiseEmployeeSalary(158, 1000); + em.getTransaction().commit(); + System.out.println("Updated " + emp); + + // remove an employee + em.getTransaction().begin(); + service.removeEmployee(158); + em.getTransaction().commit(); + System.out.println("Removed Employee 158"); + + // close the EM and EMF when done + em.close(); + emf.close(); + } +} diff --git a/examples/Chapter2/employeeService/src/client/examples/client/EmployeeTestInteractive.java b/examples/Chapter2/employeeService/src/client/examples/client/EmployeeTestInteractive.java new file mode 100644 index 0000000..2411969 --- /dev/null +++ b/examples/Chapter2/employeeService/src/client/examples/client/EmployeeTestInteractive.java @@ -0,0 +1,91 @@ +package examples.client; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Collection; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import examples.model.Employee; +import examples.model.EmployeeService; + +public class EmployeeTestInteractive { + + public static void main(String[] args) throws IOException { + // init the EntityManager + EntityManagerFactory emf = + Persistence.createEntityManagerFactory("EmployeeService"); + EntityManager em = emf.createEntityManager(); + EmployeeService service = new EmployeeService(em); + + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + String action; + int id; + try { + while (true) { + System.out.println("\n\n\n[L]ist| [A]dd | [R]emove | [Q]uit: \n\t\t\t"); + action = in.readLine(); + if ((action.length() == 0) || action.toUpperCase().charAt(0) == 'Q') { + break; + } + + switch (action.toUpperCase().charAt(0)) { + case 'A': + System.out.println("Enter int value for employee id: \n\t\t\t"); + try { + id = new Integer(in.readLine()); + } catch (NumberFormatException e) { + break; + } + + System.out.println("Enter value for employee name: \n\t\t\t"); + String name = in.readLine(); + + System.out.println("Enter long value for employee salary: \n\t\t\t"); + long salary = 0; + try { + salary = new Long(in.readLine()); + } catch (NumberFormatException e) { + break; + } + + em.getTransaction().begin(); + Employee emp = service.createEmployee(id, name, salary); + em.getTransaction().commit(); + + System.out.println("\n\nCreated " + emp); + break; + + case 'L': + Collection emps = service.findAllEmployees(); + System.out.println("\n\nFound employees: " + emps); + break; + + case 'R': + System.out.println("Enter int value for employee id: \n\t\t\t"); + try { + id = new Integer(in.readLine()); + } catch (NumberFormatException e) { + break; + } + + em.getTransaction().begin(); + service.removeEmployee(id); + em.getTransaction().commit(); + + System.out.println("\n\nRemoved Employee " + id); + break; + default: + continue; + } + } + } finally { + // close the EntityManager when done + em.close(); + emf.close(); + } + } +} diff --git a/examples/Chapter2/employeeService/src/model/examples/model/Employee.java b/examples/Chapter2/employeeService/src/model/examples/model/Employee.java new file mode 100644 index 0000000..40615dd --- /dev/null +++ b/examples/Chapter2/employeeService/src/model/examples/model/Employee.java @@ -0,0 +1,45 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + + public Employee() {} + public Employee(int id) { + this.id = id; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + " salary: " + getSalary(); + } +} diff --git a/examples/Chapter2/employeeService/src/model/examples/model/EmployeeService.java b/examples/Chapter2/employeeService/src/model/examples/model/EmployeeService.java new file mode 100644 index 0000000..9274f42 --- /dev/null +++ b/examples/Chapter2/employeeService/src/model/examples/model/EmployeeService.java @@ -0,0 +1,47 @@ +package examples.model; + +import java.util.Collection; + +import javax.persistence.EntityManager; +import javax.persistence.Query; + + +public class EmployeeService { + protected EntityManager em; + + public EmployeeService(EntityManager em) { + this.em = em; + } + + public Employee createEmployee(int id, String name, long salary) { + Employee emp = new Employee(id); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + return emp; + } + + public void removeEmployee(int id) { + Employee emp = findEmployee(id); + if (emp != null) { + em.remove(emp); + } + } + + public Employee raiseEmployeeSalary(int id, long raise) { + Employee emp = em.find(Employee.class, id); + if (emp != null) { + emp.setSalary(emp.getSalary() + raise); + } + return emp; + } + + public Employee findEmployee(int id) { + return em.find(Employee.class, id); + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter3/01-slsbExample/build.xml b/examples/Chapter3/01-slsbExample/build.xml new file mode 100644 index 0000000..2c0229f --- /dev/null +++ b/examples/Chapter3/01-slsbExample/build.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/examples/Chapter3/01-slsbExample/deploy.bat b/examples/Chapter3/01-slsbExample/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter3/01-slsbExample/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter3/01-slsbExample/etc/web/WEB-INF/web.xml b/examples/Chapter3/01-slsbExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..05e35aa --- /dev/null +++ b/examples/Chapter3/01-slsbExample/etc/web/WEB-INF/web.xml @@ -0,0 +1,5 @@ + + \ No newline at end of file diff --git a/examples/Chapter3/01-slsbExample/src/model/examples/stateless/HelloService.java b/examples/Chapter3/01-slsbExample/src/model/examples/stateless/HelloService.java new file mode 100644 index 0000000..efc4eba --- /dev/null +++ b/examples/Chapter3/01-slsbExample/src/model/examples/stateless/HelloService.java @@ -0,0 +1,6 @@ +package examples.stateless; + +public interface HelloService { + public String sayHello(String name); +} + diff --git a/examples/Chapter3/01-slsbExample/src/model/examples/stateless/HelloServiceBean.java b/examples/Chapter3/01-slsbExample/src/model/examples/stateless/HelloServiceBean.java new file mode 100644 index 0000000..42edaf1 --- /dev/null +++ b/examples/Chapter3/01-slsbExample/src/model/examples/stateless/HelloServiceBean.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import javax.ejb.Stateless; + +@Stateless +public class HelloServiceBean implements HelloService { + public String sayHello(String name) { + return "Hello, " + name; + } +} + diff --git a/examples/Chapter3/01-slsbExample/src/servlet/examples/servlet/HelloServiceServlet.java b/examples/Chapter3/01-slsbExample/src/servlet/examples/servlet/HelloServiceServlet.java new file mode 100644 index 0000000..009882c --- /dev/null +++ b/examples/Chapter3/01-slsbExample/src/servlet/examples/servlet/HelloServiceServlet.java @@ -0,0 +1,72 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.naming.InitialContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.annotation.WebServlet; +import javax.ejb.EJB; + +import examples.stateless.HelloService; + +@WebServlet(name="HelloServiceServlet", + urlPatterns="/HelloServiceServlet") +public class HelloServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 3: Stateless Session Bean Example"; + + private final String DESCRIPTION = + "This example demonstrates the basics of defining and accessing " + + "a Stateless Session Bean.
" + + "Enter a name and click 'Go'. This will trigger a servlet client that talks " + + "to a Stateless Session Bean to create a 'hello' String that is then " + + "displayed in the browser."; + + @EJB + HelloService service; + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // if there was a name submitted, print the hello string + String name = request.getParameter("name"); + if (name != null) { + // use the service to print the 'hello' string to the html stream + out.println(service.sayHello(name)); + } + printHtmlFooter(out); + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println(""); + out.println("
"); + out.println(""); + out.println(""); + out.println("
Name:
"); + out.println(""); + out.println("
"); + out.println("
"); + } + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter3/01-slsbExample/undeploy.bat b/examples/Chapter3/01-slsbExample/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter3/01-slsbExample/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter3/02-slsbLifecycleExample/build.xml b/examples/Chapter3/02-slsbLifecycleExample/build.xml new file mode 100644 index 0000000..a72c47f --- /dev/null +++ b/examples/Chapter3/02-slsbLifecycleExample/build.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/examples/Chapter3/02-slsbLifecycleExample/deploy.bat b/examples/Chapter3/02-slsbLifecycleExample/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter3/02-slsbLifecycleExample/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter3/02-slsbLifecycleExample/etc/web/WEB-INF/web.xml b/examples/Chapter3/02-slsbLifecycleExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..a19269e --- /dev/null +++ b/examples/Chapter3/02-slsbLifecycleExample/etc/web/WEB-INF/web.xml @@ -0,0 +1,21 @@ + + + + LoggerServlet + examples.servlet.LoggerServlet + + + + LoggerServlet + /LoggerServlet + + + + ejb/Logger + Session + examples.stateless.Logger + + \ No newline at end of file diff --git a/examples/Chapter3/02-slsbLifecycleExample/src/model/examples/stateless/Logger.java b/examples/Chapter3/02-slsbLifecycleExample/src/model/examples/stateless/Logger.java new file mode 100644 index 0000000..77b311d --- /dev/null +++ b/examples/Chapter3/02-slsbLifecycleExample/src/model/examples/stateless/Logger.java @@ -0,0 +1,5 @@ +package examples.stateless; + +public interface Logger { + public void logMessage(String message); +} diff --git a/examples/Chapter3/02-slsbLifecycleExample/src/model/examples/stateless/LoggerBean.java b/examples/Chapter3/02-slsbLifecycleExample/src/model/examples/stateless/LoggerBean.java new file mode 100644 index 0000000..0bfa7b9 --- /dev/null +++ b/examples/Chapter3/02-slsbLifecycleExample/src/model/examples/stateless/LoggerBean.java @@ -0,0 +1,19 @@ +package examples.stateless; + +import javax.annotation.PostConstruct; +import javax.ejb.Stateless; + +@Stateless +public class LoggerBean implements Logger { + private java.util.logging.Logger logger; + + @PostConstruct + public void init() { + logger = java.util.logging.Logger.getLogger("notification"); + } + + public void logMessage(String message) { + logger.info(message); + } +} + diff --git a/examples/Chapter3/02-slsbLifecycleExample/src/servlet/examples/servlet/LoggerServlet.java b/examples/Chapter3/02-slsbLifecycleExample/src/servlet/examples/servlet/LoggerServlet.java new file mode 100644 index 0000000..e4ba4b3 --- /dev/null +++ b/examples/Chapter3/02-slsbLifecycleExample/src/servlet/examples/servlet/LoggerServlet.java @@ -0,0 +1,76 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.naming.InitialContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateless.Logger; + +public class LoggerServlet extends HttpServlet { + + private final String TITLE = + "Chapter 3: Stateless Session Bean Lifecycle Example"; + + private final String DESCRIPTION = + "This example demonstrates the basic use of lifecycle callbacks to initialize a Stateless Session Bean.
" + + "Enter a and click 'Go'. This will trigger a servlet client that talks " + + "to a Stateless Session Bean to log a message."; + + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + + // if there was a message submitted, log it + String message = request.getParameter("message"); + if (message != null) { + // lookup the Logger + Logger service = null; + try { + service = (Logger) + new InitialContext().lookup("java:comp/env/ejb/Logger"); + } catch (Exception e) { + throw new ServletException(e); + } + + // use the logger bean to log a message + service.logMessage(message); + out.println("Message '" + message + "' sent to logger. " + + "See the console or the log file at <EXAMPLES_HOME>/glassfish/domains/domain1/logs/server.log."); + } + + + printHtmlFooter(out); + } + + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println(""); + out.println("
"); + out.println(""); + out.println(""); + out.println("
Message:
"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter3/02-slsbLifecycleExample/undeploy.bat b/examples/Chapter3/02-slsbLifecycleExample/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter3/02-slsbLifecycleExample/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter3/03-slsbRemoteExample/build.xml b/examples/Chapter3/03-slsbRemoteExample/build.xml new file mode 100644 index 0000000..2ccaa93 --- /dev/null +++ b/examples/Chapter3/03-slsbRemoteExample/build.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Chapter3/03-slsbRemoteExample/deploy.bat b/examples/Chapter3/03-slsbRemoteExample/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter3/03-slsbRemoteExample/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter3/03-slsbRemoteExample/etc/client/Manifest.mf b/examples/Chapter3/03-slsbRemoteExample/etc/client/Manifest.mf new file mode 100644 index 0000000..ad7b638 --- /dev/null +++ b/examples/Chapter3/03-slsbRemoteExample/etc/client/Manifest.mf @@ -0,0 +1,2 @@ +Main-Class: examples.client.Client + diff --git a/examples/Chapter3/03-slsbRemoteExample/etc/web/WEB-INF/web.xml b/examples/Chapter3/03-slsbRemoteExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..9d190a8 --- /dev/null +++ b/examples/Chapter3/03-slsbRemoteExample/etc/web/WEB-INF/web.xml @@ -0,0 +1,21 @@ + + + + HelloServiceServlet + examples.servlet.HelloServiceServlet + + + + HelloServiceServlet + /HelloServiceServlet + + + + ejb/HelloService + Session + examples.stateless.HelloServiceRemote + + \ No newline at end of file diff --git a/examples/Chapter3/03-slsbRemoteExample/runClient.bat b/examples/Chapter3/03-slsbRemoteExample/runClient.bat new file mode 100644 index 0000000..8882b73 --- /dev/null +++ b/examples/Chapter3/03-slsbRemoteExample/runClient.bat @@ -0,0 +1,2 @@ +call ../../../config/ant run +pause \ No newline at end of file diff --git a/examples/Chapter3/03-slsbRemoteExample/src/client/examples/client/Client.java b/examples/Chapter3/03-slsbRemoteExample/src/client/examples/client/Client.java new file mode 100644 index 0000000..fa940b4 --- /dev/null +++ b/examples/Chapter3/03-slsbRemoteExample/src/client/examples/client/Client.java @@ -0,0 +1,18 @@ +package examples.client; + +import javax.ejb.EJB; + +import examples.stateless.HelloServiceRemote; + +public class Client { + @EJB + private static HelloServiceRemote helloService; + + public static void main(String[] args) { + // a session bean with a Remote interface can be accessed + // by a fat client + System.out.println("######################"); + System.out.println("# " + helloService.sayHello("John")); + System.out.println("######################"); + } +} diff --git a/examples/Chapter3/03-slsbRemoteExample/src/model/examples/stateless/HelloServiceBean.java b/examples/Chapter3/03-slsbRemoteExample/src/model/examples/stateless/HelloServiceBean.java new file mode 100644 index 0000000..af30bc3 --- /dev/null +++ b/examples/Chapter3/03-slsbRemoteExample/src/model/examples/stateless/HelloServiceBean.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import javax.ejb.Stateless; + +@Stateless +public class HelloServiceBean implements HelloServiceRemote { + public String sayHello(String name) { + return "Hello, " + name; + } +} diff --git a/examples/Chapter3/03-slsbRemoteExample/src/model/examples/stateless/HelloServiceRemote.java b/examples/Chapter3/03-slsbRemoteExample/src/model/examples/stateless/HelloServiceRemote.java new file mode 100644 index 0000000..4e568f8 --- /dev/null +++ b/examples/Chapter3/03-slsbRemoteExample/src/model/examples/stateless/HelloServiceRemote.java @@ -0,0 +1,8 @@ +package examples.stateless; + +import javax.ejb.Remote; + +@Remote +public interface HelloServiceRemote { + public String sayHello(String name); +} diff --git a/examples/Chapter3/03-slsbRemoteExample/src/servlet/examples/servlet/HelloServiceServlet.java b/examples/Chapter3/03-slsbRemoteExample/src/servlet/examples/servlet/HelloServiceServlet.java new file mode 100644 index 0000000..ebb5bca --- /dev/null +++ b/examples/Chapter3/03-slsbRemoteExample/src/servlet/examples/servlet/HelloServiceServlet.java @@ -0,0 +1,76 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.naming.InitialContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateless.HelloServiceRemote; + +public class HelloServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 3: Remote Stateless Session Bean Example"; + + private final String DESCRIPTION = + "This example demonstrates access to a Stateless Session Bean by using " + + "its remote interface.
" + + "Enter a name and click 'Go'. This will trigger a servlet client that talks " + + "to a Stateless Session Bean to create a 'hello' String that is then " + + "displayed in the browser."; + + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + + // if there was a name submitted, print the hello string + String name = request.getParameter("name"); + if (name != null) { + // lookup the HelloService + HelloServiceRemote service = null; + try { + service = (HelloServiceRemote) + new InitialContext().lookup("java:comp/env/ejb/HelloService"); + } catch (Exception e) { + throw new ServletException(e); + } + + // use the service to print the 'hello' string to the html stream + out.println(service.sayHello(name)); + } + + + printHtmlFooter(out); + } + + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println(""); + out.println("
"); + out.println(""); + out.println(""); + out.println("
Name:
"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter3/03-slsbRemoteExample/undeploy.bat b/examples/Chapter3/03-slsbRemoteExample/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter3/03-slsbRemoteExample/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter3/04-sfsbExample/build.xml b/examples/Chapter3/04-sfsbExample/build.xml new file mode 100644 index 0000000..6a7936e --- /dev/null +++ b/examples/Chapter3/04-sfsbExample/build.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/examples/Chapter3/04-sfsbExample/deploy.bat b/examples/Chapter3/04-sfsbExample/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter3/04-sfsbExample/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter3/04-sfsbExample/etc/web/WEB-INF/web.xml b/examples/Chapter3/04-sfsbExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..9346399 --- /dev/null +++ b/examples/Chapter3/04-sfsbExample/etc/web/WEB-INF/web.xml @@ -0,0 +1,21 @@ + + + + ShoppingCartServlet + examples.servlet.ShoppingCartServlet + + + + ShoppingCartServlet + /ShoppingCartServlet + + + + ejb/ShoppingCart + Session + examples.stateful.ShoppingCart + + \ No newline at end of file diff --git a/examples/Chapter3/04-sfsbExample/src/model/examples/model/Employee.java b/examples/Chapter3/04-sfsbExample/src/model/examples/model/Employee.java new file mode 100644 index 0000000..8b574c8 --- /dev/null +++ b/examples/Chapter3/04-sfsbExample/src/model/examples/model/Employee.java @@ -0,0 +1,40 @@ +package examples.model; + +public class Employee { + private int id; + private String name; + private long salary; + + public Employee() {} + public Employee(int id) { + this.id = id; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + " salary: " + getSalary(); + } +} diff --git a/examples/Chapter3/04-sfsbExample/src/model/examples/stateful/ShoppingCart.java b/examples/Chapter3/04-sfsbExample/src/model/examples/stateful/ShoppingCart.java new file mode 100644 index 0000000..932bce4 --- /dev/null +++ b/examples/Chapter3/04-sfsbExample/src/model/examples/stateful/ShoppingCart.java @@ -0,0 +1,13 @@ +package examples.stateful; + +import java.util.Map; + +public interface ShoppingCart { + public void addItem(String id, int quantity); + public void removeItem(String id, int quantity); + public Map getItems(); + public void checkout(int paymentId); + public void cancel(); +} + + diff --git a/examples/Chapter3/04-sfsbExample/src/model/examples/stateful/ShoppingCartBean.java b/examples/Chapter3/04-sfsbExample/src/model/examples/stateful/ShoppingCartBean.java new file mode 100644 index 0000000..6264c06 --- /dev/null +++ b/examples/Chapter3/04-sfsbExample/src/model/examples/stateful/ShoppingCartBean.java @@ -0,0 +1,49 @@ +package examples.stateful; + +import java.util.HashMap; +import java.util.Map; + +import javax.ejb.Remove; +import javax.ejb.Stateful; + +@Stateful +public class ShoppingCartBean implements ShoppingCart { + private HashMap items = new HashMap(); + + public void addItem(String item, int quantity) { + Integer orderQuantity = items.get(item); + if (orderQuantity == null) { + orderQuantity = 0; + } + orderQuantity += quantity; + items.put(item, orderQuantity); + } + + public void removeItem(String item, int quantity) { + Integer orderQuantity = items.get(item); + if (orderQuantity == null) { + return; + } + orderQuantity -= quantity; + if (orderQuantity > 0) { + items.put(item, orderQuantity); + } else { + items.remove(item); + } + } + + public Map getItems() { + return items; + } + + @Remove + public void checkout(int paymentId) { + // store items to database + // ... + } + + @Remove + public void cancel() { + } +} + diff --git a/examples/Chapter3/04-sfsbExample/src/servlet/examples/servlet/ShoppingCartServlet.java b/examples/Chapter3/04-sfsbExample/src/servlet/examples/servlet/ShoppingCartServlet.java new file mode 100644 index 0000000..6127a5e --- /dev/null +++ b/examples/Chapter3/04-sfsbExample/src/servlet/examples/servlet/ShoppingCartServlet.java @@ -0,0 +1,122 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.naming.InitialContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateful.ShoppingCart; + +public class ShoppingCartServlet extends HttpServlet { + + private final String TITLE = + "Chapter 3: Stateful Session Bean Example"; + + private final String DESCRIPTION = + "This example demonstrates the basics of defining and accessing a Stateful Session Bean.
" + + "The simple example allows you to add/remove items to/from a shopping cart and then checkout " + + "or cancel your order."; + + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + + // create shopping cart if needed + ShoppingCart cart = (ShoppingCart) request.getSession().getAttribute("cart"); + if (cart == null) { + // lookup the ShoppingCart + try { + cart = (ShoppingCart) + new InitialContext().lookup("java:comp/env/ejb/ShoppingCart"); + request.getSession().setAttribute("cart", cart); + } catch (Exception e) { + throw new ServletException(e); + } + } + + // process request + if (request.getParameter("add") != null) { + cart.addItem(request.getParameter("item"), + parseInt(request.getParameter("quantity"))); + printCurrentOrder(cart, out); + } else if (request.getParameter("remove") != null) { + cart.removeItem(request.getParameter("item"), + parseInt(request.getParameter("quantity"))); + printCurrentOrder(cart, out); + } else if (request.getParameter("checkout") != null) { + out.println("Order completed with payment Id: " + request.getParameter("payment")); + printCurrentOrder(cart, out); + cart.checkout(parseInt(request.getParameter("payment"))); + request.getSession().removeAttribute("cart"); + } else if (request.getParameter("cancel") != null) { + out.println("Order cancelled!"); + cart.cancel(); + request.getSession().removeAttribute("cart"); + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printCurrentOrder(ShoppingCart cart, PrintWriter out) { + out.println("

Current Order:

"); + out.println(""); + for (String item : cart.getItems().keySet()) { + out.println(""); + out.println( ""); + } + out.println("
Item:" + item + "Quantity:" + cart.getItems().get(item) + "
"); + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + out.println("Add/Remove Items to/from Cart"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Item:(String)
Quantity:(int)
"); + out.println(""); + out.println(""); + out.println("
"); + out.println("Complete order
"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(" "); + out.println("
Payment Id:(int)
"); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter3/04-sfsbExample/undeploy.bat b/examples/Chapter3/04-sfsbExample/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter3/04-sfsbExample/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter3/05-sfsbLifecycleExample/build.xml b/examples/Chapter3/05-sfsbLifecycleExample/build.xml new file mode 100644 index 0000000..ec2525a --- /dev/null +++ b/examples/Chapter3/05-sfsbLifecycleExample/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter3/05-sfsbLifecycleExample/deploy.bat b/examples/Chapter3/05-sfsbLifecycleExample/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter3/05-sfsbLifecycleExample/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter3/05-sfsbLifecycleExample/etc/web/WEB-INF/web.xml b/examples/Chapter3/05-sfsbLifecycleExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..25abfaf --- /dev/null +++ b/examples/Chapter3/05-sfsbLifecycleExample/etc/web/WEB-INF/web.xml @@ -0,0 +1,21 @@ + + + + OrderBrowserServlet + examples.servlet.OrderBrowserServlet + + + + OrderBrowserServlet + /OrderBrowserServlet + + + + ejb/OrderBrowser + Session + examples.stateful.OrderBrowser + + \ No newline at end of file diff --git a/examples/Chapter3/05-sfsbLifecycleExample/src/model/examples/model/Order.java b/examples/Chapter3/05-sfsbLifecycleExample/src/model/examples/model/Order.java new file mode 100644 index 0000000..32b1885 --- /dev/null +++ b/examples/Chapter3/05-sfsbLifecycleExample/src/model/examples/model/Order.java @@ -0,0 +1,35 @@ +package examples.model; + +public class Order { + private int id; + private String name; + private int paymentId; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getPaymentId() { + return paymentId; + } + + public void setPaymentId(int paymentId) { + this.paymentId = paymentId; + } + + public String toString() { + return "Order id: " + getId() + " name: " + getName() + " paymentId: " + getPaymentId(); + } +} diff --git a/examples/Chapter3/05-sfsbLifecycleExample/src/model/examples/stateful/OrderBrowser.java b/examples/Chapter3/05-sfsbLifecycleExample/src/model/examples/stateful/OrderBrowser.java new file mode 100644 index 0000000..bb75481 --- /dev/null +++ b/examples/Chapter3/05-sfsbLifecycleExample/src/model/examples/stateful/OrderBrowser.java @@ -0,0 +1,10 @@ +package examples.stateful; + +import java.util.Collection; + +import examples.model.Order; + +public interface OrderBrowser { + public Collection listOrders(); +} + diff --git a/examples/Chapter3/05-sfsbLifecycleExample/src/model/examples/stateful/OrderBrowserBean.java b/examples/Chapter3/05-sfsbLifecycleExample/src/model/examples/stateful/OrderBrowserBean.java new file mode 100644 index 0000000..36ef6f0 --- /dev/null +++ b/examples/Chapter3/05-sfsbLifecycleExample/src/model/examples/stateful/OrderBrowserBean.java @@ -0,0 +1,77 @@ +package examples.stateful; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collection; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import javax.annotation.Resource; +import javax.ejb.EJBException; +import javax.ejb.PostActivate; +import javax.ejb.PrePassivate; +import javax.ejb.Stateful; +import javax.naming.InitialContext; +import javax.sql.DataSource; + +import examples.model.Order; + +@Stateful +// Resource declaration is covered later in the chapter. +// use of mappedName is vendor specific. In this case, it is used +// to specify the JNDI location of the datasource to use. +@Resource(name="jdbc/ds", type=DataSource.class, mappedName="jdbc/sfsbLifecycleExample") +public class OrderBrowserBean implements OrderBrowser { + DataSource ds; + Connection conn; + + @PostConstruct + public void init() { + // acquire the data source + try { + ds = (DataSource) + new InitialContext().lookup("java:comp/env/jdbc/ds"); + } catch (Exception e) { + throw new EJBException(e); + } + acquireConnection(); + } + + @PrePassivate + public void passivate() { + releaseConnection(); + } + + @PostActivate + public void activate() { + acquireConnection(); + } + + @PreDestroy + public void shutdown() { + releaseConnection(); + } + + private void acquireConnection() { + try { + conn = ds.getConnection(); + } catch (SQLException e) { + throw new EJBException(e); + } + } + + private void releaseConnection() { + try { + conn.close(); + } catch (SQLException e) { + } + conn = null; + } + + public Collection listOrders() { + // ... + return new ArrayList(); + } +} + diff --git a/examples/Chapter3/05-sfsbLifecycleExample/src/servlet/examples/servlet/OrderBrowserServlet.java b/examples/Chapter3/05-sfsbLifecycleExample/src/servlet/examples/servlet/OrderBrowserServlet.java new file mode 100644 index 0000000..123478c --- /dev/null +++ b/examples/Chapter3/05-sfsbLifecycleExample/src/servlet/examples/servlet/OrderBrowserServlet.java @@ -0,0 +1,71 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.naming.InitialContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateful.OrderBrowser; + +public class OrderBrowserServlet extends HttpServlet { + + private final String TITLE = + "Chapter 3: Stateful Session Bean Lifecycle Example"; + + private final String DESCRIPTION = + "This example demonstrates the basic use of lifecycle callbacks to " + + "initialize/cleanup a Stateful Session Bean.
" + + "NOTE: The example doesn't show the details of issuing/parsing the jdbc to create " + + "orders, hence no orders are displayed. See the code to see how to use the lifecycle callbacks."; + + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + + // create order browser if needed + OrderBrowser browser = (OrderBrowser) request.getSession().getAttribute("browser"); + if (browser == null) { + // lookup the OrderBrowser + try { + browser = (OrderBrowser) + new InitialContext().lookup("java:comp/env/ejb/OrderBrowser"); + request.getSession().setAttribute("browser", browser); + } catch (Exception e) { + throw new ServletException(e); + } + } + + // process request + if (request.getParameter("list") != null) { + out.println("Orders: " + browser.listOrders()); + } + + printHtmlFooter(out); + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + out.println(""); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter3/05-sfsbLifecycleExample/undeploy.bat b/examples/Chapter3/05-sfsbLifecycleExample/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter3/05-sfsbLifecycleExample/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter3/06-singletonBean/build.xml b/examples/Chapter3/06-singletonBean/build.xml new file mode 100644 index 0000000..b1b03ab --- /dev/null +++ b/examples/Chapter3/06-singletonBean/build.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/examples/Chapter3/06-singletonBean/deploy.bat b/examples/Chapter3/06-singletonBean/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter3/06-singletonBean/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter3/06-singletonBean/etc/web/WEB-INF/web.xml b/examples/Chapter3/06-singletonBean/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5daabff --- /dev/null +++ b/examples/Chapter3/06-singletonBean/etc/web/WEB-INF/web.xml @@ -0,0 +1,6 @@ + + + \ No newline at end of file diff --git a/examples/Chapter3/06-singletonBean/src/model/examples/singleton/HitCounter.java b/examples/Chapter3/06-singletonBean/src/model/examples/singleton/HitCounter.java new file mode 100644 index 0000000..b9b23ec --- /dev/null +++ b/examples/Chapter3/06-singletonBean/src/model/examples/singleton/HitCounter.java @@ -0,0 +1,17 @@ +package model.examples.singleton; + +import javax.ejb.Lock; +import javax.ejb.LockType; +import javax.ejb.Singleton; + +@Singleton +public class HitCounter { + int count; + + public void increment() { ++count; } + + @Lock(LockType.READ) + public int getCount() { return count; } + + public void reset() { count = 0; } +} \ No newline at end of file diff --git a/examples/Chapter3/06-singletonBean/src/servlet/examples/servlet/HitCountServlet.java b/examples/Chapter3/06-singletonBean/src/servlet/examples/servlet/HitCountServlet.java new file mode 100644 index 0000000..27203ae --- /dev/null +++ b/examples/Chapter3/06-singletonBean/src/servlet/examples/servlet/HitCountServlet.java @@ -0,0 +1,72 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.naming.InitialContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.annotation.WebServlet; + +import javax.ejb.EJB; + +import model.examples.singleton.HitCounter; + +@WebServlet(name="HitCountServlet", + urlPatterns="/HitCountServlet") +public class HitCountServlet extends HttpServlet { + + private final String TITLE = + "Chapter 3: Singleton Session Bean Example"; + + private final String DESCRIPTION = + "This example demonstrates the basic use of a " + + "Singleton Session Bean.
" + + "The simple example allows you to call and update the count stored in the singleton bean."; + + @EJB + HitCounter counter; + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + if (request.getParameter("list") != null) { + out.println("Count: " + counter.getCount()); + } + else if (request.getParameter("increment") != null) { + counter.increment(); + out.println("Count incremented."); + } + else if (request.getParameter("reset") != null) { + counter.reset(); + out.println("Count reset."); + } + + printHtmlFooter(out); + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + out.println(""); + out.println(""); + out.println(""); + out.println("
"); + } + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter3/06-singletonBean/undeploy.bat b/examples/Chapter3/06-singletonBean/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter3/06-singletonBean/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter3/07-mdbExample/build.xml b/examples/Chapter3/07-mdbExample/build.xml new file mode 100644 index 0000000..199a8a6 --- /dev/null +++ b/examples/Chapter3/07-mdbExample/build.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Chapter3/07-mdbExample/deploy.bat b/examples/Chapter3/07-mdbExample/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter3/07-mdbExample/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter3/07-mdbExample/etc/web/WEB-INF/web.xml b/examples/Chapter3/07-mdbExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..1485222 --- /dev/null +++ b/examples/Chapter3/07-mdbExample/etc/web/WEB-INF/web.xml @@ -0,0 +1,27 @@ + + + + ReportProcessorServlet + examples.servlet.ReportProcessorServlet + + + + ReportProcessorServlet + /ReportProcessorServlet + + + + jms/MyQueue + javax.jms.Queue + destinationQueue + + + + jms/MyQueueConnectionFactory + javax.jms.QueueConnectionFactory + factory + + \ No newline at end of file diff --git a/examples/Chapter3/07-mdbExample/src/model/examples/mdb/ReportProcessorBean.java b/examples/Chapter3/07-mdbExample/src/model/examples/mdb/ReportProcessorBean.java new file mode 100644 index 0000000..2cae9f1 --- /dev/null +++ b/examples/Chapter3/07-mdbExample/src/model/examples/mdb/ReportProcessorBean.java @@ -0,0 +1,20 @@ +package examples.mdb; + +import javax.ejb.ActivationConfigProperty; +import javax.ejb.MessageDriven; + +// use of mappedName is vendor specific. In this case, it is used +// to specify the JNDI location of the JMS Queue to use. +@MessageDriven( + mappedName="destinationQueue", + activationConfig = { + @ActivationConfigProperty(propertyName="destinationType", + propertyValue="javax.jms.Queue"), + @ActivationConfigProperty(propertyName="messageSelector", + propertyValue="RECIPIENT='ReportProcessor'") +}) +public class ReportProcessorBean implements javax.jms.MessageListener { + public void onMessage(javax.jms.Message message) { + System.out.println("Processing message: " + message.toString()); + } +} diff --git a/examples/Chapter3/07-mdbExample/src/servlet/examples/servlet/ReportProcessorServlet.java b/examples/Chapter3/07-mdbExample/src/servlet/examples/servlet/ReportProcessorServlet.java new file mode 100644 index 0000000..824a0b8 --- /dev/null +++ b/examples/Chapter3/07-mdbExample/src/servlet/examples/servlet/ReportProcessorServlet.java @@ -0,0 +1,91 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.jms.Message; +import javax.jms.Queue; +import javax.jms.QueueConnection; +import javax.jms.QueueConnectionFactory; +import javax.jms.QueueSender; +import javax.jms.QueueSession; +import javax.jms.Session; +import javax.naming.InitialContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public class ReportProcessorServlet extends HttpServlet { + + private final String TITLE = + "Chapter 3: Message Driven Bean Example"; + + private final String DESCRIPTION = + "This example demonstrates the basics for defining and accessing a Message Driven Bean.
" + + "Enter the message text and click 'Send'. This will trigger a servlet " + + "client that sends a JMS message that will be processed by an MDB."; + + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + + // if there was info submitted, send the message + String messageText = request.getParameter("message"); + if (messageText != null) { + try { + QueueConnectionFactory factory = (QueueConnectionFactory) + new InitialContext().lookup("java:comp/env/jms/MyQueueConnectionFactory"); + Queue destinationQueue = (Queue) + new InitialContext().lookup("java:comp/env/jms/MyQueue"); + QueueConnection connection = factory.createQueueConnection(); + QueueSession session = connection.createQueueSession(false, + Session.AUTO_ACKNOWLEDGE); + + QueueSender sender = session.createSender(null); + Message message = session.createTextMessage(messageText); + message.setStringProperty("RECIPIENT", "ReportProcessor"); + sender.send(destinationQueue, message); + connection.close(); + + // print a response to the html stream + out.println("Message \"" + messageText + "\" sent! See the console " + + "or the log file at <EXAMPLES_HOME>/glassfish/domains/domain1/logs/server.log."); + } catch (Exception e) { + throw new ServletException(e); + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println(""); + out.println("
"); + out.println(""); + out.println("" + + ""); + out.println("
Message Text:
"); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter3/07-mdbExample/undeploy.bat b/examples/Chapter3/07-mdbExample/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter3/07-mdbExample/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter3/08-servletExample/build.xml b/examples/Chapter3/08-servletExample/build.xml new file mode 100644 index 0000000..601ff81 --- /dev/null +++ b/examples/Chapter3/08-servletExample/build.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/examples/Chapter3/08-servletExample/deploy.bat b/examples/Chapter3/08-servletExample/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter3/08-servletExample/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter3/08-servletExample/etc/web/WEB-INF/web.xml b/examples/Chapter3/08-servletExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..2922bb2 --- /dev/null +++ b/examples/Chapter3/08-servletExample/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + LoginServlet + examples.servlet.LoginServlet + + + + LoginServlet + /LoginServlet + + \ No newline at end of file diff --git a/examples/Chapter3/08-servletExample/src/servlet/examples/servlet/LoginServlet.java b/examples/Chapter3/08-servletExample/src/servlet/examples/servlet/LoginServlet.java new file mode 100644 index 0000000..cc521d4 --- /dev/null +++ b/examples/Chapter3/08-servletExample/src/servlet/examples/servlet/LoginServlet.java @@ -0,0 +1,64 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +public class LoginServlet extends HttpServlet { + + private final String TITLE = + "Chapter 3: Servlet Example"; + + private final String DESCRIPTION = + "This example demonstrates the basics of defining and accessing a servlet and how it can maintain state.
" + + "Enter a user id and click 'Go'. This will trigger a servlet that stores " + + "the user id in the http session and prints it out. Note there is no " + + "persistence yet"; + + + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + String userId = request.getParameter("user"); + HttpSession session = request.getSession(); + session.setAttribute("user", userId); + + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + + printHtmlHeader(out); + out.println("User id: " + session.getAttribute("user")); + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println(""); + out.println("
"); + out.println(""); + out.println(""); + out.println("
User Id:
"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter3/08-servletExample/undeploy.bat b/examples/Chapter3/08-servletExample/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter3/08-servletExample/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter3/09-dependencyLookup/build.xml b/examples/Chapter3/09-dependencyLookup/build.xml new file mode 100644 index 0000000..d8ea31c --- /dev/null +++ b/examples/Chapter3/09-dependencyLookup/build.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/examples/Chapter3/09-dependencyLookup/deploy.bat b/examples/Chapter3/09-dependencyLookup/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter3/09-dependencyLookup/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter3/09-dependencyLookup/etc/web/WEB-INF/web.xml b/examples/Chapter3/09-dependencyLookup/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..857eae6 --- /dev/null +++ b/examples/Chapter3/09-dependencyLookup/etc/web/WEB-INF/web.xml @@ -0,0 +1,21 @@ + + + + DepartmentServiceServlet + examples.servlet.DepartmentServiceServlet + + + + DepartmentServiceServlet + /DepartmentServiceServlet + + + + ejb/DepartmentService + Session + examples.stateless.DepartmentService + + \ No newline at end of file diff --git a/examples/Chapter3/09-dependencyLookup/src/model/examples/stateless/AuditService.java b/examples/Chapter3/09-dependencyLookup/src/model/examples/stateless/AuditService.java new file mode 100644 index 0000000..8ae36bc --- /dev/null +++ b/examples/Chapter3/09-dependencyLookup/src/model/examples/stateless/AuditService.java @@ -0,0 +1,6 @@ +package examples.stateless; + +public interface AuditService { + public void audit(); +} + diff --git a/examples/Chapter3/09-dependencyLookup/src/model/examples/stateless/AuditServiceBean.java b/examples/Chapter3/09-dependencyLookup/src/model/examples/stateless/AuditServiceBean.java new file mode 100644 index 0000000..1091120 --- /dev/null +++ b/examples/Chapter3/09-dependencyLookup/src/model/examples/stateless/AuditServiceBean.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import javax.ejb.Stateless; + +@Stateless +public class AuditServiceBean implements AuditService { + public void audit() { + System.out.println("Audit performed."); + } +} + diff --git a/examples/Chapter3/09-dependencyLookup/src/model/examples/stateless/DepartmentService.java b/examples/Chapter3/09-dependencyLookup/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..3225979 --- /dev/null +++ b/examples/Chapter3/09-dependencyLookup/src/model/examples/stateless/DepartmentService.java @@ -0,0 +1,6 @@ +package examples.stateless; + +public interface DepartmentService { + public void performAudit(); +} + diff --git a/examples/Chapter3/09-dependencyLookup/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter3/09-dependencyLookup/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..02bc39a --- /dev/null +++ b/examples/Chapter3/09-dependencyLookup/src/model/examples/stateless/DepartmentServiceBean.java @@ -0,0 +1,32 @@ +package examples.stateless; + +import javax.annotation.PostConstruct; +import javax.ejb.EJB; +import javax.ejb.EJBException; +import javax.ejb.Stateless; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +@Stateless +@EJB(name="audit", beanInterface=AuditService.class) +public class DepartmentServiceBean implements DepartmentService { + private AuditService audit; + + @PostConstruct + public void init() { + try { + Context ctx = new InitialContext(); + audit = (AuditService) ctx.lookup("java:comp/env/audit"); + } catch (NamingException e) { + throw new EJBException(e); + } + } + + public void performAudit() { + audit.audit(); + } + + // ... +} + diff --git a/examples/Chapter3/09-dependencyLookup/src/servlet/examples/servlet/DepartmentServiceServlet.java b/examples/Chapter3/09-dependencyLookup/src/servlet/examples/servlet/DepartmentServiceServlet.java new file mode 100644 index 0000000..919a818 --- /dev/null +++ b/examples/Chapter3/09-dependencyLookup/src/servlet/examples/servlet/DepartmentServiceServlet.java @@ -0,0 +1,71 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.naming.InitialContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateless.DepartmentService; + +public class DepartmentServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 3: Dependency Lookup Example"; + + private final String DESCRIPTION = + "This example demonstrates InitialContext lookup of a dependency.
" + + "Click the 'Audit' button. This will trigger a servlet client that looks " + + "up a SLSB dependency that was defined in the web.xml file. That SLSB in turn " + + "looks up another SLSB using the dependency is defined using the @EJB annotation."; + + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + + if (request.getParameter("action") != null) { + DepartmentService service = null; + try { + service = (DepartmentService) + new InitialContext().lookup("java:comp/env/ejb/DepartmentService"); + } catch (Exception e) { + throw new ServletException(e); + } + service.performAudit(); + out.println("Audit Performed"); + } + + printHtmlFooter(out); + } + + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println(""); + out.println("
"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter3/09-dependencyLookup/undeploy.bat b/examples/Chapter3/09-dependencyLookup/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter3/09-dependencyLookup/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter3/10-ejbContextLookup/build.xml b/examples/Chapter3/10-ejbContextLookup/build.xml new file mode 100644 index 0000000..91eeb6b --- /dev/null +++ b/examples/Chapter3/10-ejbContextLookup/build.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/examples/Chapter3/10-ejbContextLookup/deploy.bat b/examples/Chapter3/10-ejbContextLookup/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter3/10-ejbContextLookup/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter3/10-ejbContextLookup/etc/web/WEB-INF/web.xml b/examples/Chapter3/10-ejbContextLookup/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..857eae6 --- /dev/null +++ b/examples/Chapter3/10-ejbContextLookup/etc/web/WEB-INF/web.xml @@ -0,0 +1,21 @@ + + + + DepartmentServiceServlet + examples.servlet.DepartmentServiceServlet + + + + DepartmentServiceServlet + /DepartmentServiceServlet + + + + ejb/DepartmentService + Session + examples.stateless.DepartmentService + + \ No newline at end of file diff --git a/examples/Chapter3/10-ejbContextLookup/src/model/examples/stateless/AuditService.java b/examples/Chapter3/10-ejbContextLookup/src/model/examples/stateless/AuditService.java new file mode 100644 index 0000000..8ae36bc --- /dev/null +++ b/examples/Chapter3/10-ejbContextLookup/src/model/examples/stateless/AuditService.java @@ -0,0 +1,6 @@ +package examples.stateless; + +public interface AuditService { + public void audit(); +} + diff --git a/examples/Chapter3/10-ejbContextLookup/src/model/examples/stateless/AuditServiceBean.java b/examples/Chapter3/10-ejbContextLookup/src/model/examples/stateless/AuditServiceBean.java new file mode 100644 index 0000000..1091120 --- /dev/null +++ b/examples/Chapter3/10-ejbContextLookup/src/model/examples/stateless/AuditServiceBean.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import javax.ejb.Stateless; + +@Stateless +public class AuditServiceBean implements AuditService { + public void audit() { + System.out.println("Audit performed."); + } +} + diff --git a/examples/Chapter3/10-ejbContextLookup/src/model/examples/stateless/DepartmentService.java b/examples/Chapter3/10-ejbContextLookup/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..3225979 --- /dev/null +++ b/examples/Chapter3/10-ejbContextLookup/src/model/examples/stateless/DepartmentService.java @@ -0,0 +1,6 @@ +package examples.stateless; + +public interface DepartmentService { + public void performAudit(); +} + diff --git a/examples/Chapter3/10-ejbContextLookup/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter3/10-ejbContextLookup/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..8a785b9 --- /dev/null +++ b/examples/Chapter3/10-ejbContextLookup/src/model/examples/stateless/DepartmentServiceBean.java @@ -0,0 +1,31 @@ +package examples.stateless; + +import javax.annotation.PostConstruct; +import javax.annotation.Resource; +import javax.ejb.EJB; +import javax.ejb.SessionContext; +import javax.ejb.Stateless; + +@Stateless +@EJB(name="audit", beanInterface=AuditService.class) +public class DepartmentServiceBean implements DepartmentService { + // use of resource dependency injection is covered later in the chapter + @Resource SessionContext context; + AuditService audit; + + public void setSessionContext(SessionContext context) { + this.context = context; + } + + @PostConstruct + public void init() { + audit = (AuditService) context.lookup("audit"); + } + + public void performAudit() { + audit.audit(); + } + + // ... +} + diff --git a/examples/Chapter3/10-ejbContextLookup/src/servlet/examples/servlet/DepartmentServiceServlet.java b/examples/Chapter3/10-ejbContextLookup/src/servlet/examples/servlet/DepartmentServiceServlet.java new file mode 100644 index 0000000..5dbbd52 --- /dev/null +++ b/examples/Chapter3/10-ejbContextLookup/src/servlet/examples/servlet/DepartmentServiceServlet.java @@ -0,0 +1,73 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.naming.InitialContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateless.DepartmentService; + +public class DepartmentServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 3: EJBContext Lookup Example"; + + private final String DESCRIPTION = + "This example demonstrates EJBContext lookup of a dependency.
" + + "Click the 'Audit' button. This will trigger a servlet client that looks " + + "up a SLSB dependency that was defined in the web.xml file. That SLSB in turn " + + "looks up another SLSB using the dependency is defined using the @EJB " + + "annotation. The example is identical to the previous one, except that the SLSB " + + "uses an EJBContext instead of an InitialContext for the lookup."; + + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + + if (request.getParameter("action") != null) { + DepartmentService service = null; + try { + service = (DepartmentService) + new InitialContext().lookup("java:comp/env/ejb/DepartmentService"); + } catch (Exception e) { + throw new ServletException(e); + } + service.performAudit(); + out.println("Audit Performed"); + } + + printHtmlFooter(out); + } + + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println(""); + out.println("
"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter3/10-ejbContextLookup/undeploy.bat b/examples/Chapter3/10-ejbContextLookup/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter3/10-ejbContextLookup/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter3/11-fieldInjection/build.xml b/examples/Chapter3/11-fieldInjection/build.xml new file mode 100644 index 0000000..e15adff --- /dev/null +++ b/examples/Chapter3/11-fieldInjection/build.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/examples/Chapter3/11-fieldInjection/deploy.bat b/examples/Chapter3/11-fieldInjection/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter3/11-fieldInjection/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter3/11-fieldInjection/etc/web/WEB-INF/web.xml b/examples/Chapter3/11-fieldInjection/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..a64ff0e --- /dev/null +++ b/examples/Chapter3/11-fieldInjection/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + DepartmentServiceServlet + examples.servlet.DepartmentServiceServlet + + + + DepartmentServiceServlet + /DepartmentServiceServlet + + \ No newline at end of file diff --git a/examples/Chapter3/11-fieldInjection/src/model/examples/stateless/AuditService.java b/examples/Chapter3/11-fieldInjection/src/model/examples/stateless/AuditService.java new file mode 100644 index 0000000..8ae36bc --- /dev/null +++ b/examples/Chapter3/11-fieldInjection/src/model/examples/stateless/AuditService.java @@ -0,0 +1,6 @@ +package examples.stateless; + +public interface AuditService { + public void audit(); +} + diff --git a/examples/Chapter3/11-fieldInjection/src/model/examples/stateless/AuditServiceBean.java b/examples/Chapter3/11-fieldInjection/src/model/examples/stateless/AuditServiceBean.java new file mode 100644 index 0000000..1091120 --- /dev/null +++ b/examples/Chapter3/11-fieldInjection/src/model/examples/stateless/AuditServiceBean.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import javax.ejb.Stateless; + +@Stateless +public class AuditServiceBean implements AuditService { + public void audit() { + System.out.println("Audit performed."); + } +} + diff --git a/examples/Chapter3/11-fieldInjection/src/model/examples/stateless/DepartmentService.java b/examples/Chapter3/11-fieldInjection/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..3225979 --- /dev/null +++ b/examples/Chapter3/11-fieldInjection/src/model/examples/stateless/DepartmentService.java @@ -0,0 +1,6 @@ +package examples.stateless; + +public interface DepartmentService { + public void performAudit(); +} + diff --git a/examples/Chapter3/11-fieldInjection/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter3/11-fieldInjection/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..410f407 --- /dev/null +++ b/examples/Chapter3/11-fieldInjection/src/model/examples/stateless/DepartmentServiceBean.java @@ -0,0 +1,16 @@ +package examples.stateless; + +import javax.ejb.EJB; +import javax.ejb.Stateless; + +@Stateless +public class DepartmentServiceBean implements DepartmentService { + @EJB AuditService audit; + + public void performAudit() { + audit.audit(); + } + + // ... +} + diff --git a/examples/Chapter3/11-fieldInjection/src/servlet/examples/servlet/DepartmentServiceServlet.java b/examples/Chapter3/11-fieldInjection/src/servlet/examples/servlet/DepartmentServiceServlet.java new file mode 100644 index 0000000..3be4068 --- /dev/null +++ b/examples/Chapter3/11-fieldInjection/src/servlet/examples/servlet/DepartmentServiceServlet.java @@ -0,0 +1,67 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateless.DepartmentService; + +public class DepartmentServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 3: Field Injection Example"; + + private final String DESCRIPTION = + "This example demonstrates field injection of a dependency.
" + + "Click the 'Audit' button. This will trigger a servlet client that looks " + + "up a SLSB dependency that was defined in the web.xml file. That SLSB in turn " + + "accesses another SLSB that was automatically injected into the field by " + + "the container using the @EJB annotation. The example is identical to the " + + "previous two, except that the SLSB uses field injection to aquire its dependency."; + + @EJB + DepartmentService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + if (request.getParameter("action") != null) { + service.performAudit(); + out.println("Audit Performed"); + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println(""); + out.println("
"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter3/11-fieldInjection/undeploy.bat b/examples/Chapter3/11-fieldInjection/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter3/11-fieldInjection/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter3/12-setterInjection/build.xml b/examples/Chapter3/12-setterInjection/build.xml new file mode 100644 index 0000000..a389764 --- /dev/null +++ b/examples/Chapter3/12-setterInjection/build.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/examples/Chapter3/12-setterInjection/deploy.bat b/examples/Chapter3/12-setterInjection/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter3/12-setterInjection/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter3/12-setterInjection/etc/web/WEB-INF/web.xml b/examples/Chapter3/12-setterInjection/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..a64ff0e --- /dev/null +++ b/examples/Chapter3/12-setterInjection/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + DepartmentServiceServlet + examples.servlet.DepartmentServiceServlet + + + + DepartmentServiceServlet + /DepartmentServiceServlet + + \ No newline at end of file diff --git a/examples/Chapter3/12-setterInjection/src/model/examples/stateless/AuditService.java b/examples/Chapter3/12-setterInjection/src/model/examples/stateless/AuditService.java new file mode 100644 index 0000000..8ae36bc --- /dev/null +++ b/examples/Chapter3/12-setterInjection/src/model/examples/stateless/AuditService.java @@ -0,0 +1,6 @@ +package examples.stateless; + +public interface AuditService { + public void audit(); +} + diff --git a/examples/Chapter3/12-setterInjection/src/model/examples/stateless/AuditServiceBean.java b/examples/Chapter3/12-setterInjection/src/model/examples/stateless/AuditServiceBean.java new file mode 100644 index 0000000..1091120 --- /dev/null +++ b/examples/Chapter3/12-setterInjection/src/model/examples/stateless/AuditServiceBean.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import javax.ejb.Stateless; + +@Stateless +public class AuditServiceBean implements AuditService { + public void audit() { + System.out.println("Audit performed."); + } +} + diff --git a/examples/Chapter3/12-setterInjection/src/model/examples/stateless/DepartmentService.java b/examples/Chapter3/12-setterInjection/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..3225979 --- /dev/null +++ b/examples/Chapter3/12-setterInjection/src/model/examples/stateless/DepartmentService.java @@ -0,0 +1,6 @@ +package examples.stateless; + +public interface DepartmentService { + public void performAudit(); +} + diff --git a/examples/Chapter3/12-setterInjection/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter3/12-setterInjection/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..00cb6e3 --- /dev/null +++ b/examples/Chapter3/12-setterInjection/src/model/examples/stateless/DepartmentServiceBean.java @@ -0,0 +1,21 @@ +package examples.stateless; + +import javax.ejb.EJB; +import javax.ejb.Stateless; + +@Stateless +public class DepartmentServiceBean implements DepartmentService { + private AuditService audit; + + @EJB + public void setAuditService(AuditService audit) { + this.audit = audit; + } + + public void performAudit() { + audit.audit(); + } + + // ... +} + diff --git a/examples/Chapter3/12-setterInjection/src/servlet/examples/servlet/DepartmentServiceServlet.java b/examples/Chapter3/12-setterInjection/src/servlet/examples/servlet/DepartmentServiceServlet.java new file mode 100644 index 0000000..b4c3c58 --- /dev/null +++ b/examples/Chapter3/12-setterInjection/src/servlet/examples/servlet/DepartmentServiceServlet.java @@ -0,0 +1,71 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateless.DepartmentService; + +public class DepartmentServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 3: Setter Injection Example"; + + private final String DESCRIPTION = + "This example demonstrates setter injection of a dependency.
" + + "Click the 'Audit' button. This will trigger a servlet client that looks " + + "up a SLSB dependency that was defined in the web.xml file. That SLSB in turn " + + "accesses another SLSB that was automatically injected into the setter by " + + "the container using the @EJB annotation. The example is identical to the " + + "previous one, except that the SLSB uses setter injection to aquire its dependency."; + + DepartmentService service; + + @EJB + public void setDepartmentService(DepartmentService service) { + this.service = service; + } + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + if (request.getParameter("action") != null) { + service.performAudit(); + out.println("Audit Performed"); + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println(""); + out.println("
"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter3/12-setterInjection/undeploy.bat b/examples/Chapter3/12-setterInjection/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter3/12-setterInjection/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter3/13-bmtExample/build.xml b/examples/Chapter3/13-bmtExample/build.xml new file mode 100644 index 0000000..0771d1b --- /dev/null +++ b/examples/Chapter3/13-bmtExample/build.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/examples/Chapter3/13-bmtExample/deploy.bat b/examples/Chapter3/13-bmtExample/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter3/13-bmtExample/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter3/13-bmtExample/etc/web/WEB-INF/web.xml b/examples/Chapter3/13-bmtExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..36c8478 --- /dev/null +++ b/examples/Chapter3/13-bmtExample/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + ProcessingServiceServlet + examples.servlet.ProcessingServiceServlet + + + + ProcessingServiceServlet + /ProcessingServiceServlet + + \ No newline at end of file diff --git a/examples/Chapter3/13-bmtExample/src/model/examples/stateless/ProcessingService.java b/examples/Chapter3/13-bmtExample/src/model/examples/stateless/ProcessingService.java new file mode 100644 index 0000000..efba451 --- /dev/null +++ b/examples/Chapter3/13-bmtExample/src/model/examples/stateless/ProcessingService.java @@ -0,0 +1,6 @@ +package examples.stateless; + +public interface ProcessingService { + public void process(); +} + diff --git a/examples/Chapter3/13-bmtExample/src/model/examples/stateless/ProcessingServiceBean.java b/examples/Chapter3/13-bmtExample/src/model/examples/stateless/ProcessingServiceBean.java new file mode 100644 index 0000000..0111fcd --- /dev/null +++ b/examples/Chapter3/13-bmtExample/src/model/examples/stateless/ProcessingServiceBean.java @@ -0,0 +1,31 @@ +package examples.stateless; + +import javax.annotation.Resource; +import javax.ejb.EJBException; +import javax.ejb.Stateless; +import javax.ejb.TransactionManagement; +import javax.ejb.TransactionManagementType; +import javax.transaction.UserTransaction; + +@Stateless +@TransactionManagement(TransactionManagementType.BEAN) +public class ProcessingServiceBean implements ProcessingService { + @Resource UserTransaction tx; + + public void process() { + try { + try { + tx.begin(); + // do the work... + System.out.println("Processing..."); + } finally { + tx.commit(); + } + } catch (Exception e) { + // handle all the tx.begin()/commit() exceptions + throw new EJBException(e); + } + } + + // ... +} diff --git a/examples/Chapter3/13-bmtExample/src/servlet/examples/servlet/ProcessingServiceServlet.java b/examples/Chapter3/13-bmtExample/src/servlet/examples/servlet/ProcessingServiceServlet.java new file mode 100644 index 0000000..cc9a2d3 --- /dev/null +++ b/examples/Chapter3/13-bmtExample/src/servlet/examples/servlet/ProcessingServiceServlet.java @@ -0,0 +1,65 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateless.ProcessingService; + +public class ProcessingServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 3: Bean Managed Transaction (BMT) Example"; + + private final String DESCRIPTION = + "This example demonstrates the basic use of bean managed transactions in an EJB.
" + + "Click the 'Process' button. This will trigger a servlet client that invokes " + + "a SLSB that uses bean managed transactions. The SLSB first injects an instance of " + + "UserTransaction and then uses its API to demarcate the transaction."; + + @EJB + ProcessingService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + if (request.getParameter("action") != null) { + service.process(); + out.println("Processing done"); + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println(""); + out.println("
"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter3/13-bmtExample/undeploy.bat b/examples/Chapter3/13-bmtExample/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter3/13-bmtExample/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter3/14-cmtExample/build.xml b/examples/Chapter3/14-cmtExample/build.xml new file mode 100644 index 0000000..6da4ebe --- /dev/null +++ b/examples/Chapter3/14-cmtExample/build.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/examples/Chapter3/14-cmtExample/deploy.bat b/examples/Chapter3/14-cmtExample/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter3/14-cmtExample/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter3/14-cmtExample/etc/web/WEB-INF/web.xml b/examples/Chapter3/14-cmtExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..e5b5a7e --- /dev/null +++ b/examples/Chapter3/14-cmtExample/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + ShoppingCartServlet + examples.servlet.ShoppingCartServlet + + + + ShoppingCartServlet + /ShoppingCartServlet + + \ No newline at end of file diff --git a/examples/Chapter3/14-cmtExample/src/model/examples/stateful/ShoppingCart.java b/examples/Chapter3/14-cmtExample/src/model/examples/stateful/ShoppingCart.java new file mode 100644 index 0000000..7e8ba32 --- /dev/null +++ b/examples/Chapter3/14-cmtExample/src/model/examples/stateful/ShoppingCart.java @@ -0,0 +1,10 @@ +package examples.stateful; + +import java.util.Map; + +public interface ShoppingCart { + public void addItem(String id, Integer quantity); + public Map getItems(); + public void cancel(); +} + diff --git a/examples/Chapter3/14-cmtExample/src/model/examples/stateful/ShoppingCartBean.java b/examples/Chapter3/14-cmtExample/src/model/examples/stateful/ShoppingCartBean.java new file mode 100644 index 0000000..337140e --- /dev/null +++ b/examples/Chapter3/14-cmtExample/src/model/examples/stateful/ShoppingCartBean.java @@ -0,0 +1,33 @@ +package examples.stateful; + +import static javax.ejb.TransactionAttributeType.SUPPORTS; + +import java.util.HashMap; +import java.util.Map; + +import javax.ejb.Remove; +import javax.ejb.Stateful; +import javax.ejb.TransactionAttribute; + +@Stateful +public class ShoppingCartBean implements ShoppingCart { + private HashMap items = new HashMap(); + + @TransactionAttribute(SUPPORTS) + public void addItem(String item, Integer quantity) { + Integer orderQuantity = items.get(item); + if (orderQuantity == null) { + orderQuantity = 0; + } + orderQuantity += quantity; + items.put(item, orderQuantity); + } + + public Map getItems() { + return items; + } + + @Remove + public void cancel() {} +} + diff --git a/examples/Chapter3/14-cmtExample/src/servlet/examples/servlet/ShoppingCartServlet.java b/examples/Chapter3/14-cmtExample/src/servlet/examples/servlet/ShoppingCartServlet.java new file mode 100644 index 0000000..7106efa --- /dev/null +++ b/examples/Chapter3/14-cmtExample/src/servlet/examples/servlet/ShoppingCartServlet.java @@ -0,0 +1,111 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.annotation.Resource; +import javax.ejb.EJB; +import javax.naming.InitialContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.transaction.UserTransaction; + +import examples.stateful.ShoppingCart; + +// declare a dependency on the ShoppingCart sfsb +@EJB(name="cart", beanInterface=ShoppingCart.class) +public class ShoppingCartServlet extends HttpServlet { + // inject a reference to UserTransaction + @Resource UserTransaction tx; + + private final String TITLE = + "Chapter 3: Container Managed Transaction (CMT) Example"; + + private final String DESCRIPTION = + "This example demonstrates the basic use of container managed transactions in an EJB.
" + + "Click the 'Process' button. This will trigger a servlet client that invokes " + + "a SFSB that uses container managed transactions. The SFSB methods use different " + + "TransactionAttributes on its methods to achieve different transaction semantics."; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // create shopping cart if needed + ShoppingCart cart = (ShoppingCart) request.getSession().getAttribute("cart"); + if (cart == null) { + // lookup the ShoppingCart + try { + cart = (ShoppingCart) + new InitialContext().lookup("java:comp/env/cart"); + request.getSession().setAttribute("cart", cart); + } catch (Exception e) { + throw new ServletException(e); + } + } + + // process request + if (request.getParameter("add") != null) { + cart.addItem(request.getParameter("item"), + parseInt(request.getParameter("quantity"))); + printCurrentOrder(cart, out); + } else if (request.getParameter("cancel") != null) { + out.println("Order cancelled!"); + cart.cancel(); + request.getSession().removeAttribute("cart"); + } + + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printCurrentOrder(ShoppingCart cart, PrintWriter out) { + out.println("

Current Order:

"); + out.println(""); + for (String item : cart.getItems().keySet()) { + out.println(""); + out.println( ""); + } + out.println("
Item:" + item + "Quantity:" + cart.getItems().get(item) + "
"); + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Item:(String)
Quantity:(int)
"); + out.println(""); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter3/14-cmtExample/undeploy.bat b/examples/Chapter3/14-cmtExample/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter3/14-cmtExample/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter3/15-userTxExample/build.xml b/examples/Chapter3/15-userTxExample/build.xml new file mode 100644 index 0000000..6e76f81 --- /dev/null +++ b/examples/Chapter3/15-userTxExample/build.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/examples/Chapter3/15-userTxExample/deploy.bat b/examples/Chapter3/15-userTxExample/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter3/15-userTxExample/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter3/15-userTxExample/etc/web/WEB-INF/web.xml b/examples/Chapter3/15-userTxExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..e7a135a --- /dev/null +++ b/examples/Chapter3/15-userTxExample/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + ProjectServlet + examples.servlet.ProjectServlet + + + + ProjectServlet + /ProjectServlet + + \ No newline at end of file diff --git a/examples/Chapter3/15-userTxExample/src/model/examples/stateless/ProjectService.java b/examples/Chapter3/15-userTxExample/src/model/examples/stateless/ProjectService.java new file mode 100644 index 0000000..7b77ecf --- /dev/null +++ b/examples/Chapter3/15-userTxExample/src/model/examples/stateless/ProjectService.java @@ -0,0 +1,7 @@ +package examples.stateless; + +public interface ProjectService { + public void assignEmployeeToProject(int projectId, int empId); + public void updateProjectStatistics(); +} + diff --git a/examples/Chapter3/15-userTxExample/src/model/examples/stateless/ProjectServiceBean.java b/examples/Chapter3/15-userTxExample/src/model/examples/stateless/ProjectServiceBean.java new file mode 100644 index 0000000..4027b72 --- /dev/null +++ b/examples/Chapter3/15-userTxExample/src/model/examples/stateless/ProjectServiceBean.java @@ -0,0 +1,18 @@ +package examples.stateless; + +import javax.ejb.Stateless; + +@Stateless +public class ProjectServiceBean implements ProjectService { + public void assignEmployeeToProject(int projectId, int empId) { + // ... + System.out.println("Adding Employee to Project..."); + } + + public void updateProjectStatistics() { + // ... + System.out.println("Updating Project Stats..."); + } + + // ... +} diff --git a/examples/Chapter3/15-userTxExample/src/servlet/examples/servlet/ProjectServlet.java b/examples/Chapter3/15-userTxExample/src/servlet/examples/servlet/ProjectServlet.java new file mode 100644 index 0000000..19d7584 --- /dev/null +++ b/examples/Chapter3/15-userTxExample/src/servlet/examples/servlet/ProjectServlet.java @@ -0,0 +1,82 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.annotation.Resource; +import javax.ejb.EJB; +import javax.ejb.EJBException; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.transaction.UserTransaction; + +import examples.stateless.ProjectService; + +public class ProjectServlet extends HttpServlet { + + private final String TITLE = + "Chapter 3: UserTransaction Example"; + + private final String DESCRIPTION = + "This example demonstrates the basic use of a UserTransaction in a Servlet.
" + + "Click the 'Go' button. This will trigger a servlet client that uses " + + "a UserTransaction to demarcate the transaction semantics for the EJBs upon " + + "which it invokes."; + + @EJB + ProjectService bean; + @Resource UserTransaction tx; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + if (request.getParameter("action") != null) { + int projectId = 1; //request.getParameter("projectId"); + int empId = 1; //request.getParameter("empId"); + try { + try { + tx.begin(); + bean.assignEmployeeToProject(projectId, empId); + bean.updateProjectStatistics(); + } finally { + tx.commit(); + } + } catch (Exception e) { + // handle all the tx.begin()/commit() exceptions + throw new EJBException(e); + } + out.println("Update done"); + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println(""); + out.println("
"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter3/15-userTxExample/undeploy.bat b/examples/Chapter3/15-userTxExample/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter3/15-userTxExample/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter3/16-employeeService/build.xml b/examples/Chapter3/16-employeeService/build.xml new file mode 100644 index 0000000..95e8cc6 --- /dev/null +++ b/examples/Chapter3/16-employeeService/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter3/16-employeeService/deploy.bat b/examples/Chapter3/16-employeeService/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter3/16-employeeService/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter3/16-employeeService/etc/persistence/META-INF/persistence.xml b/examples/Chapter3/16-employeeService/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..0fec500 --- /dev/null +++ b/examples/Chapter3/16-employeeService/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,11 @@ + + + jdbc/EmpServDB_ch3 + + + + + + + \ No newline at end of file diff --git a/examples/Chapter3/16-employeeService/etc/sql/db.sql b/examples/Chapter3/16-employeeService/etc/sql/db.sql new file mode 100644 index 0000000..e35905b --- /dev/null +++ b/examples/Chapter3/16-employeeService/etc/sql/db.sql @@ -0,0 +1,4 @@ +DROP TABLE EMPLOYEE; + +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, PRIMARY KEY (ID)); + diff --git a/examples/Chapter3/16-employeeService/etc/web/WEB-INF/web.xml b/examples/Chapter3/16-employeeService/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..9eebc68 --- /dev/null +++ b/examples/Chapter3/16-employeeService/etc/web/WEB-INF/web.xml @@ -0,0 +1,16 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + + \ No newline at end of file diff --git a/examples/Chapter3/16-employeeService/src/model/examples/model/Employee.java b/examples/Chapter3/16-employeeService/src/model/examples/model/Employee.java new file mode 100644 index 0000000..40615dd --- /dev/null +++ b/examples/Chapter3/16-employeeService/src/model/examples/model/Employee.java @@ -0,0 +1,45 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + + public Employee() {} + public Employee(int id) { + this.id = id; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + " salary: " + getSalary(); + } +} diff --git a/examples/Chapter3/16-employeeService/src/model/examples/stateless/EmployeeService.java b/examples/Chapter3/16-employeeService/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..a42c261 --- /dev/null +++ b/examples/Chapter3/16-employeeService/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,13 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(int id, String name, long salary); + public Employee removeEmployee(int id); + public Employee changeEmployeeSalary(int id, long newSalary); + public Employee findEmployee(int id); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter3/16-employeeService/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter3/16-employeeService/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..bc6f558 --- /dev/null +++ b/examples/Chapter3/16-employeeService/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,60 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.annotation.Resource; +import javax.ejb.Stateless; +// import javax.jms.Queue; +// import javax.jms.QueueConnectionFactory; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + //@Resource(mappedName="destinationQueue") Queue destinationQueue; + //@Resource(mappedName="factory") QueueConnectionFactory factory; + + public EntityManager getEntityManager() { + return em; + } + + public Employee createEmployee(int id, String name, long salary) { + Employee emp = new Employee(id); + emp.setName(name); + emp.setSalary(salary); + getEntityManager().persist(emp); + return emp; + } + + public Employee removeEmployee(int id) { + Employee emp = findEmployee(id); + if (emp != null) { + getEntityManager().remove(emp); + return emp; + } else return null; + + } + + public Employee changeEmployeeSalary(int id, long newSalary) { + Employee emp = findEmployee(id); + if (emp != null) { + emp.setSalary(newSalary); + } + return emp; + } + + public Employee findEmployee(int id) { + return getEntityManager().find(Employee.class, id); + } + + public Collection findAllEmployees() { + Query query = getEntityManager().createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter3/16-employeeService/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter3/16-employeeService/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..6c41dcc --- /dev/null +++ b/examples/Chapter3/16-employeeService/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,146 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 3: Employee Service Example"; + + private final String DESCRIPTION = + "This example pulls together much of what was learned in this chapter " + + "and relates it to our earlier EmployeeService example.
" + + "The example allows you to create/remove/find/update employees. All " + + "operations are persisted to the database."; + + + // inject a reference to the EmployeeService slsb + @EJB EmployeeService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("Create")) { + Employee emp = service.createEmployee( + parseInt(request.getParameter("createId")), + request.getParameter("name"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("Remove")) { + String id = request.getParameter("removeId"); + Employee emp = service.removeEmployee(parseInt(id)); + out.println("Removed " + emp); + } else if (action.equals("Update")) { + String id = request.getParameter("raiseId"); + Employee emp = service.changeEmployeeSalary( + parseInt(id), + parseLong(request.getParameter("raise"))); + out.println("Updated " + emp); + } else if (action.equals("Find")) { + Employee emp = service.findEmployee( + parseInt(request.getParameter("findId"))); + out.println("Found " + emp); + } else if (action.equals("FindAll")) { + Collection emps = service.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.print(emp + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println("" + + ""); + out.println("
Id:(int)
Name:(String)
Salary:(long)
"); + out.println("
"); + // form to remove + out.println("

Remove an Employee

"); + out.println(""); + out.println("" + + ""); + out.println("
Id:(int)
"); + out.println("
"); + // form to update + out.println("

Update an Employee

"); + out.println(""); + out.println(""); + out.println("" + + ""); + out.println("
Id:(int)
Raise:(long)
"); + out.println("
"); + // form to find + out.println("

Find an Employee

"); + out.println(""); + out.println("" + + ""); + out.println("
Id:(int)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees

"); + out.println(""); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter3/16-employeeService/undeploy.bat b/examples/Chapter3/16-employeeService/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter3/16-employeeService/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter4/01-fieldAccess/build.xml b/examples/Chapter4/01-fieldAccess/build.xml new file mode 100644 index 0000000..14781d4 --- /dev/null +++ b/examples/Chapter4/01-fieldAccess/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/01-fieldAccess/deploy.bat b/examples/Chapter4/01-fieldAccess/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter4/01-fieldAccess/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter4/01-fieldAccess/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/01-fieldAccess/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..ca6bde0 --- /dev/null +++ b/examples/Chapter4/01-fieldAccess/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/fieldAccess + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/01-fieldAccess/etc/sql/db.sql b/examples/Chapter4/01-fieldAccess/etc/sql/db.sql new file mode 100644 index 0000000..e35905b --- /dev/null +++ b/examples/Chapter4/01-fieldAccess/etc/sql/db.sql @@ -0,0 +1,4 @@ +DROP TABLE EMPLOYEE; + +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, PRIMARY KEY (ID)); + diff --git a/examples/Chapter4/01-fieldAccess/etc/web/WEB-INF/web.xml b/examples/Chapter4/01-fieldAccess/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/01-fieldAccess/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter4/01-fieldAccess/src/model/examples/model/Employee.java b/examples/Chapter4/01-fieldAccess/src/model/examples/model/Employee.java new file mode 100644 index 0000000..049ce3f --- /dev/null +++ b/examples/Chapter4/01-fieldAccess/src/model/examples/model/Employee.java @@ -0,0 +1,40 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + " salary: " + getSalary(); + } +} diff --git a/examples/Chapter4/01-fieldAccess/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/01-fieldAccess/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..1707ef2 --- /dev/null +++ b/examples/Chapter4/01-fieldAccess/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(int id, String name, long salary); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter4/01-fieldAccess/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/01-fieldAccess/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..0815bdf --- /dev/null +++ b/examples/Chapter4/01-fieldAccess/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,31 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(int id, String name, long salary) { + Employee emp = new Employee(); + emp.setId(id); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/01-fieldAccess/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/01-fieldAccess/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..8e2b9a7 --- /dev/null +++ b/examples/Chapter4/01-fieldAccess/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,110 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 4: Field Access Example"; + + private final String DESCRIPTION = + "This example demonstrates how to specify field access for entities.
" + + "It allows you to create/find employees. All operations " + + "are persisted to the database."; + + + // inject a reference to the EmployeeService slsb + @EJB EmployeeService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("Create")) { + Employee emp = service.createEmployee( + parseInt(request.getParameter("id")), + request.getParameter("name"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("FindAll")) { + Collection emps = service.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println(""); + // form to create and Employee and Address + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
Employee Name:(String)
Employee Salary:(long)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees

"); + out.println(""); + out.println(""); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter4/01-fieldAccess/undeploy.bat b/examples/Chapter4/01-fieldAccess/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter4/01-fieldAccess/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter4/02-propertyAccess/build.xml b/examples/Chapter4/02-propertyAccess/build.xml new file mode 100644 index 0000000..1b59d23 --- /dev/null +++ b/examples/Chapter4/02-propertyAccess/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/02-propertyAccess/deploy.bat b/examples/Chapter4/02-propertyAccess/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter4/02-propertyAccess/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter4/02-propertyAccess/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/02-propertyAccess/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..a4d3e7c --- /dev/null +++ b/examples/Chapter4/02-propertyAccess/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/propertyAccess + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/02-propertyAccess/etc/sql/db.sql b/examples/Chapter4/02-propertyAccess/etc/sql/db.sql new file mode 100644 index 0000000..e35905b --- /dev/null +++ b/examples/Chapter4/02-propertyAccess/etc/sql/db.sql @@ -0,0 +1,4 @@ +DROP TABLE EMPLOYEE; + +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, PRIMARY KEY (ID)); + diff --git a/examples/Chapter4/02-propertyAccess/etc/web/WEB-INF/web.xml b/examples/Chapter4/02-propertyAccess/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/02-propertyAccess/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter4/02-propertyAccess/src/model/examples/model/Employee.java b/examples/Chapter4/02-propertyAccess/src/model/examples/model/Employee.java new file mode 100644 index 0000000..f29c9fe --- /dev/null +++ b/examples/Chapter4/02-propertyAccess/src/model/examples/model/Employee.java @@ -0,0 +1,40 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Employee { + private int id; + private String name; + private long wage; + + @Id + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return wage; + } + + public void setSalary(long salary) { + this.wage = salary; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + " salary: " + getSalary(); + } +} diff --git a/examples/Chapter4/02-propertyAccess/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/02-propertyAccess/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..1707ef2 --- /dev/null +++ b/examples/Chapter4/02-propertyAccess/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(int id, String name, long salary); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter4/02-propertyAccess/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/02-propertyAccess/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..0815bdf --- /dev/null +++ b/examples/Chapter4/02-propertyAccess/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,31 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(int id, String name, long salary) { + Employee emp = new Employee(); + emp.setId(id); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/02-propertyAccess/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/02-propertyAccess/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..3325bc6 --- /dev/null +++ b/examples/Chapter4/02-propertyAccess/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,110 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 4: Property Access Example"; + + private final String DESCRIPTION = + "This example demonstrates how to specify property access for entities.
" + + "It allows you to create/find employees. All operations " + + "are persisted to the database."; + + + // inject a reference to the EmployeeService slsb + @EJB EmployeeService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("Create")) { + Employee emp = service.createEmployee( + parseInt(request.getParameter("id")), + request.getParameter("name"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("FindAll")) { + Collection emps = service.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Address + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
Employee Name:(String)
Employee Salary:(long)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter4/02-propertyAccess/undeploy.bat b/examples/Chapter4/02-propertyAccess/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter4/02-propertyAccess/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter4/03-mixedAccess/build.xml b/examples/Chapter4/03-mixedAccess/build.xml new file mode 100644 index 0000000..676a282 --- /dev/null +++ b/examples/Chapter4/03-mixedAccess/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/03-mixedAccess/deploy.bat b/examples/Chapter4/03-mixedAccess/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter4/03-mixedAccess/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter4/03-mixedAccess/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/03-mixedAccess/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..8fb5acf --- /dev/null +++ b/examples/Chapter4/03-mixedAccess/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/mixedAccess + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/03-mixedAccess/etc/sql/db.sql b/examples/Chapter4/03-mixedAccess/etc/sql/db.sql new file mode 100644 index 0000000..a00daba --- /dev/null +++ b/examples/Chapter4/03-mixedAccess/etc/sql/db.sql @@ -0,0 +1,4 @@ +DROP TABLE EMPLOYEE; + +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, PHONE VARCHAR(255), NAME VARCHAR(255), WAGE BIGINT, PRIMARY KEY (ID)); + diff --git a/examples/Chapter4/03-mixedAccess/etc/web/WEB-INF/web.xml b/examples/Chapter4/03-mixedAccess/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/03-mixedAccess/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter4/03-mixedAccess/src/model/examples/model/Employee.java b/examples/Chapter4/03-mixedAccess/src/model/examples/model/Employee.java new file mode 100644 index 0000000..86770d1 --- /dev/null +++ b/examples/Chapter4/03-mixedAccess/src/model/examples/model/Employee.java @@ -0,0 +1,65 @@ +package examples.model; + +import javax.persistence.Access; +import javax.persistence.AccessType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Transient; + +@Access(AccessType.FIELD) +@Entity +public class Employee { +public static final String LOCAL_AREA_CODE = "613"; + @Id private int id; + @Transient private String phoneNum; + + private String name; + private long wage; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return wage; + } + + public void setSalary(long salary) { + this.wage = salary; + } + + public String getPhoneNumber() { return phoneNum; } + public void setPhoneNumber(String num) { this.phoneNum = num; } + + @Access(AccessType.PROPERTY) @Column(name="PHONE") + protected String getPhoneNumberForDb() { + if (null != phoneNum && phoneNum.length() == 10) + return phoneNum; + else + return LOCAL_AREA_CODE + phoneNum; + } + + protected void setPhoneNumberForDb(String num) { + if (num.startsWith(LOCAL_AREA_CODE)) + phoneNum = num.substring(3); + else + phoneNum = num; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + " salary: " + getSalary(); + } +} diff --git a/examples/Chapter4/03-mixedAccess/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/03-mixedAccess/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..1707ef2 --- /dev/null +++ b/examples/Chapter4/03-mixedAccess/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(int id, String name, long salary); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter4/03-mixedAccess/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/03-mixedAccess/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..0815bdf --- /dev/null +++ b/examples/Chapter4/03-mixedAccess/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,31 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(int id, String name, long salary) { + Employee emp = new Employee(); + emp.setId(id); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/03-mixedAccess/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/03-mixedAccess/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..49c8248 --- /dev/null +++ b/examples/Chapter4/03-mixedAccess/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,110 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 4:Mixed @Access Example"; + + private final String DESCRIPTION = + "This example demonstrates how to specify mixed property access for entities.
" + + "It allows you to create/find employees. All operations " + + "are persisted to the database."; + + + // inject a reference to the EmployeeService slsb + @EJB EmployeeService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("Create")) { + Employee emp = service.createEmployee( + parseInt(request.getParameter("id")), + request.getParameter("name"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("FindAll")) { + Collection emps = service.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Address + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
Employee Name:(String)
Employee Salary:(long)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter4/03-mixedAccess/undeploy.bat b/examples/Chapter4/03-mixedAccess/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter4/03-mixedAccess/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter4/04-customTableSchema/build.xml b/examples/Chapter4/04-customTableSchema/build.xml new file mode 100644 index 0000000..bb2f47f --- /dev/null +++ b/examples/Chapter4/04-customTableSchema/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/04-customTableSchema/deploy.bat b/examples/Chapter4/04-customTableSchema/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter4/04-customTableSchema/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter4/04-customTableSchema/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/04-customTableSchema/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..398488e --- /dev/null +++ b/examples/Chapter4/04-customTableSchema/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/customTableSchema + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/04-customTableSchema/etc/sql/db.sql b/examples/Chapter4/04-customTableSchema/etc/sql/db.sql new file mode 100644 index 0000000..552b016 --- /dev/null +++ b/examples/Chapter4/04-customTableSchema/etc/sql/db.sql @@ -0,0 +1,4 @@ +DROP TABLE HR.EMP; + +CREATE TABLE HR.EMP (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, PRIMARY KEY (ID)); + diff --git a/examples/Chapter4/04-customTableSchema/etc/web/WEB-INF/web.xml b/examples/Chapter4/04-customTableSchema/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/04-customTableSchema/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter4/04-customTableSchema/src/model/examples/model/Employee.java b/examples/Chapter4/04-customTableSchema/src/model/examples/model/Employee.java new file mode 100644 index 0000000..2b514c5 --- /dev/null +++ b/examples/Chapter4/04-customTableSchema/src/model/examples/model/Employee.java @@ -0,0 +1,42 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name="EMP", schema="HR") +public class Employee { + @Id + private int id; + private String name; + private long salary; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + " salary: " + getSalary(); + } +} diff --git a/examples/Chapter4/04-customTableSchema/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/04-customTableSchema/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..1707ef2 --- /dev/null +++ b/examples/Chapter4/04-customTableSchema/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(int id, String name, long salary); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter4/04-customTableSchema/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/04-customTableSchema/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..0815bdf --- /dev/null +++ b/examples/Chapter4/04-customTableSchema/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,31 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(int id, String name, long salary) { + Employee emp = new Employee(); + emp.setId(id); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/04-customTableSchema/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/04-customTableSchema/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..42a8694 --- /dev/null +++ b/examples/Chapter4/04-customTableSchema/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,110 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 4: Custom Table/Schema Example"; + + private final String DESCRIPTION = + "This example demonstrates how to specify custom table/schema for entities.
" + + "It allows you to create/find employees. All operations " + + "are persisted to the database."; + + + // inject a reference to the EmployeeService slsb + @EJB EmployeeService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("Create")) { + Employee emp = service.createEmployee( + parseInt(request.getParameter("id")), + request.getParameter("name"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("FindAll")) { + Collection emps = service.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Address + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
Employee Name:(String)
Employee Salary:(long)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter4/04-customTableSchema/undeploy.bat b/examples/Chapter4/04-customTableSchema/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter4/04-customTableSchema/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter4/05-customColumnMapping/build.xml b/examples/Chapter4/05-customColumnMapping/build.xml new file mode 100644 index 0000000..db9d682 --- /dev/null +++ b/examples/Chapter4/05-customColumnMapping/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/05-customColumnMapping/deploy.bat b/examples/Chapter4/05-customColumnMapping/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter4/05-customColumnMapping/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter4/05-customColumnMapping/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/05-customColumnMapping/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..9e98658 --- /dev/null +++ b/examples/Chapter4/05-customColumnMapping/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/customColumnMapping + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/05-customColumnMapping/etc/sql/db.sql b/examples/Chapter4/05-customColumnMapping/etc/sql/db.sql new file mode 100644 index 0000000..bfe6b57 --- /dev/null +++ b/examples/Chapter4/05-customColumnMapping/etc/sql/db.sql @@ -0,0 +1,4 @@ +DROP TABLE EMPLOYEE; + +CREATE TABLE EMPLOYEE (EMP_ID INTEGER NOT NULL, NAME VARCHAR(255), SAL BIGINT, COMM VARCHAR(255), PRIMARY KEY (EMP_ID)); + diff --git a/examples/Chapter4/05-customColumnMapping/etc/web/WEB-INF/web.xml b/examples/Chapter4/05-customColumnMapping/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/05-customColumnMapping/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter4/05-customColumnMapping/src/model/examples/model/Employee.java b/examples/Chapter4/05-customColumnMapping/src/model/examples/model/Employee.java new file mode 100644 index 0000000..bb2331f --- /dev/null +++ b/examples/Chapter4/05-customColumnMapping/src/model/examples/model/Employee.java @@ -0,0 +1,54 @@ +package examples.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Employee { + @Id + @Column(name = "EMP_ID") + private int id; + private String name; + @Column(name = "SAL") + private long salary; + @Column(name = "COMM") + private String comments; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public String getComments() { + return comments; + } + + public void setComments(String comments) { + this.comments = comments; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " salary: " + getSalary() + " comments: " + getComments(); + } +} diff --git a/examples/Chapter4/05-customColumnMapping/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/05-customColumnMapping/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..85900ed --- /dev/null +++ b/examples/Chapter4/05-customColumnMapping/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(int id, String name, long salary, String comments); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter4/05-customColumnMapping/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/05-customColumnMapping/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..fe2483d --- /dev/null +++ b/examples/Chapter4/05-customColumnMapping/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,32 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(int id, String name, long salary, String comments) { + Employee emp = new Employee(); + emp.setId(id); + emp.setName(name); + emp.setSalary(salary); + emp.setComments(comments); + em.persist(emp); + + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/05-customColumnMapping/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/05-customColumnMapping/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..e6efacf --- /dev/null +++ b/examples/Chapter4/05-customColumnMapping/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,112 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 4: Custom Column Mapping Example"; + + private final String DESCRIPTION = + "This example demonstrates how to specify custom column names for entities attributes.
" + + "It allows you to create/find employees. All operations " + + "are persisted to the database."; + + + // inject a reference to the EmployeeService slsb + @EJB EmployeeService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("Create")) { + Employee emp = service.createEmployee( + parseInt(request.getParameter("id")), + request.getParameter("name"), + parseLong(request.getParameter("salary")), + request.getParameter("comments")); + out.println("Created " + emp); + } else if (action.equals("FindAll")) { + Collection emps = service.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Address + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
Employee Name:(String)
Employee Salary:(long)
Employee Comments:(String)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter4/05-customColumnMapping/undeploy.bat b/examples/Chapter4/05-customColumnMapping/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter4/05-customColumnMapping/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter4/06-lobMapping/build.xml b/examples/Chapter4/06-lobMapping/build.xml new file mode 100644 index 0000000..e905b54 --- /dev/null +++ b/examples/Chapter4/06-lobMapping/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/06-lobMapping/deploy.bat b/examples/Chapter4/06-lobMapping/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter4/06-lobMapping/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter4/06-lobMapping/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/06-lobMapping/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..48c37d4 --- /dev/null +++ b/examples/Chapter4/06-lobMapping/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/lobMapping + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/06-lobMapping/etc/sql/db.sql b/examples/Chapter4/06-lobMapping/etc/sql/db.sql new file mode 100644 index 0000000..53b0112 --- /dev/null +++ b/examples/Chapter4/06-lobMapping/etc/sql/db.sql @@ -0,0 +1,4 @@ +DROP TABLE EMPLOYEE; + +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, PIC BLOB, PRIMARY KEY (ID)); + diff --git a/examples/Chapter4/06-lobMapping/etc/web/WEB-INF/web.xml b/examples/Chapter4/06-lobMapping/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/06-lobMapping/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter4/06-lobMapping/src/model/examples/model/Employee.java b/examples/Chapter4/06-lobMapping/src/model/examples/model/Employee.java new file mode 100644 index 0000000..1e37e0d --- /dev/null +++ b/examples/Chapter4/06-lobMapping/src/model/examples/model/Employee.java @@ -0,0 +1,59 @@ +package examples.model; + +import static javax.persistence.FetchType.LAZY; + +import javax.persistence.Basic; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Lob; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + + @Basic(fetch=LAZY) + @Lob @Column(name="PIC") + private byte[] picture; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public byte[] getPicture() { + return picture; + } + + public void setPicture(byte[] picture) { + this.picture = picture; + } + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " salary: " + getSalary() + " pic: " + new String(getPicture()); + } + +} diff --git a/examples/Chapter4/06-lobMapping/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/06-lobMapping/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..381f445 --- /dev/null +++ b/examples/Chapter4/06-lobMapping/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(int id, String name, long salary, byte[] pic); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter4/06-lobMapping/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/06-lobMapping/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..57477df --- /dev/null +++ b/examples/Chapter4/06-lobMapping/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,32 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(int id, String name, long salary, byte[] pic) { + Employee emp = new Employee(); + emp.setId(id); + emp.setName(name); + emp.setSalary(salary); + emp.setPicture(pic); + em.persist(emp); + + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/06-lobMapping/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/06-lobMapping/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..45e483e --- /dev/null +++ b/examples/Chapter4/06-lobMapping/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,113 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 4: LOB Mapping Example"; + + private final String DESCRIPTION = + "This example demonstrates how to map a byte[] to a LOB column.
" + + "It allows you to create/find employees. All operations " + + "are persisted to the database. The example also demonstrates the use of" + + "fetch=LAZY for simple fields."; + + + // inject a reference to the EmployeeService slsb + @EJB EmployeeService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("Create")) { + Employee emp = service.createEmployee( + parseInt(request.getParameter("id")), + request.getParameter("name"), + parseLong(request.getParameter("salary")), + request.getParameter("pic").getBytes()); + out.println("Created " + emp); + } else if (action.equals("FindAll")) { + Collection emps = service.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Address + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
Employee Name:(String)
Employee Salary:(long)
Employee Picture:(String -> converted to byte[])
"); + out.println("
"); + // form to find all + out.println("

Find all Employees

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter4/06-lobMapping/undeploy.bat b/examples/Chapter4/06-lobMapping/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter4/06-lobMapping/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter4/07-enumMapping/build.xml b/examples/Chapter4/07-enumMapping/build.xml new file mode 100644 index 0000000..57965cb --- /dev/null +++ b/examples/Chapter4/07-enumMapping/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/07-enumMapping/deploy.bat b/examples/Chapter4/07-enumMapping/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter4/07-enumMapping/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter4/07-enumMapping/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/07-enumMapping/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..56a78ec --- /dev/null +++ b/examples/Chapter4/07-enumMapping/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/enumMapping + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/07-enumMapping/etc/sql/db.sql b/examples/Chapter4/07-enumMapping/etc/sql/db.sql new file mode 100644 index 0000000..3f0c1a9 --- /dev/null +++ b/examples/Chapter4/07-enumMapping/etc/sql/db.sql @@ -0,0 +1,4 @@ +DROP TABLE EMPLOYEE; + +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, TYPE INTEGER, PREVIOUSTYPE VARCHAR(64), PRIMARY KEY (ID)); + diff --git a/examples/Chapter4/07-enumMapping/etc/web/WEB-INF/web.xml b/examples/Chapter4/07-enumMapping/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/07-enumMapping/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter4/07-enumMapping/src/model/examples/model/Employee.java b/examples/Chapter4/07-enumMapping/src/model/examples/model/Employee.java new file mode 100644 index 0000000..4362ae3 --- /dev/null +++ b/examples/Chapter4/07-enumMapping/src/model/examples/model/Employee.java @@ -0,0 +1,63 @@ +package examples.model; + +import static javax.persistence.EnumType.STRING; + +import javax.persistence.Entity; +import javax.persistence.Enumerated; +import javax.persistence.Id; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + private EmployeeType type; + @Enumerated(STRING) + private EmployeeType previousType; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public EmployeeType getType() { + return type; + } + + public void setType(EmployeeType type) { + this.previousType = this.type; + if (this.previousType == null) { + this.previousType = type; + } + this.type = type; + } + + public EmployeeType getPreviousType() { + return previousType; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " salary: " + getSalary() + " type: " + getType(); + } +} diff --git a/examples/Chapter4/07-enumMapping/src/model/examples/model/EmployeeType.java b/examples/Chapter4/07-enumMapping/src/model/examples/model/EmployeeType.java new file mode 100644 index 0000000..6fab5b2 --- /dev/null +++ b/examples/Chapter4/07-enumMapping/src/model/examples/model/EmployeeType.java @@ -0,0 +1,7 @@ +package examples.model; + +public enum EmployeeType { + FULL_TIME_EMPLOYEE, + PART_TIME_EMPLOYEE, + CONTRACT_EMPLOYEE +} diff --git a/examples/Chapter4/07-enumMapping/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/07-enumMapping/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..d5ed61c --- /dev/null +++ b/examples/Chapter4/07-enumMapping/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; +import examples.model.EmployeeType; + +public interface EmployeeService { + public Employee createEmployee(int id, String name, long salary, EmployeeType type); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter4/07-enumMapping/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/07-enumMapping/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..195f5c1 --- /dev/null +++ b/examples/Chapter4/07-enumMapping/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,33 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Employee; +import examples.model.EmployeeType; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(int id, String name, long salary, EmployeeType type) { + Employee emp = new Employee(); + emp.setId(id); + emp.setName(name); + emp.setSalary(salary); + emp.setType(type); + em.persist(emp); + + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/07-enumMapping/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/07-enumMapping/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..98919fe --- /dev/null +++ b/examples/Chapter4/07-enumMapping/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,128 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.model.EmployeeType; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 4: Enum Mapping Example"; + + private final String DESCRIPTION = + "This example demonstrates how to map an Enum entity attribute.
" + + "It allows you to create/find employees. All operations " + + "are persisted to the database. It shows how to map enumerations using " + + "both ordinals and strings."; + + + // inject a reference to the EmployeeService slsb + @EJB EmployeeService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("Create")) { + Employee emp = service.createEmployee( + parseInt(request.getParameter("id")), + request.getParameter("name"), + parseLong(request.getParameter("salary")), + getEmployeeType(request.getParameter("type"))); + out.println("Created " + emp); + } else if (action.equals("FindAll")) { + Collection emps = service.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + } + + printHtmlFooter(out); + } + + private EmployeeType getEmployeeType(String type) { + if (type.equals("Full")) { + return EmployeeType.FULL_TIME_EMPLOYEE; + } else if (type.equals("Part")) { + return EmployeeType.PART_TIME_EMPLOYEE; + } else { + return EmployeeType.CONTRACT_EMPLOYEE; + } + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Address + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
Employee Name:(String)
Employee Salary:(long)
Empoyee Type:"); + out.println(" Full Time
"); + out.println(" Part Time
"); + out.println(" Contract"); + out.println("
"); + out.println("
"); + // form to find all + out.println("

Find all Employees

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter4/07-enumMapping/undeploy.bat b/examples/Chapter4/07-enumMapping/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter4/07-enumMapping/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter4/08-temporalMapping/build.xml b/examples/Chapter4/08-temporalMapping/build.xml new file mode 100644 index 0000000..599552f --- /dev/null +++ b/examples/Chapter4/08-temporalMapping/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/08-temporalMapping/deploy.bat b/examples/Chapter4/08-temporalMapping/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter4/08-temporalMapping/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter4/08-temporalMapping/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/08-temporalMapping/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..e42ff2a --- /dev/null +++ b/examples/Chapter4/08-temporalMapping/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/temporalMapping + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/08-temporalMapping/etc/sql/db.sql b/examples/Chapter4/08-temporalMapping/etc/sql/db.sql new file mode 100644 index 0000000..c4d8b70 --- /dev/null +++ b/examples/Chapter4/08-temporalMapping/etc/sql/db.sql @@ -0,0 +1,4 @@ +DROP TABLE EMPLOYEE; + +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, DOB DATE, S_DATE DATE, PRIMARY KEY (ID)); + diff --git a/examples/Chapter4/08-temporalMapping/etc/web/WEB-INF/web.xml b/examples/Chapter4/08-temporalMapping/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/08-temporalMapping/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter4/08-temporalMapping/src/model/examples/model/Employee.java b/examples/Chapter4/08-temporalMapping/src/model/examples/model/Employee.java new file mode 100644 index 0000000..d52e503 --- /dev/null +++ b/examples/Chapter4/08-temporalMapping/src/model/examples/model/Employee.java @@ -0,0 +1,73 @@ +package examples.model; + +import java.text.DateFormat; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + + @Temporal(TemporalType.DATE) + private java.util.Calendar dob; + @Temporal(TemporalType.DATE) + @Column(name="S_DATE") + private java.util.Date startDate; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + + public java.util.Calendar getDob() { + return dob; + } + + public void setDob(java.util.Calendar dob) { + this.dob = dob; + } + + public java.util.Date getStartDate() { + return startDate; + } + + public void setStartDate(java.util.Date startDate) { + this.startDate = startDate; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " salary: " + getSalary() + + " dob: " + DateFormat.getDateInstance().format(getDob().getTime()) + + " startDate: " + DateFormat.getDateInstance().format(getStartDate()); + } + +} diff --git a/examples/Chapter4/08-temporalMapping/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/08-temporalMapping/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..f36fdf0 --- /dev/null +++ b/examples/Chapter4/08-temporalMapping/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Calendar; +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(int id, String name, long salary, Calendar dob); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter4/08-temporalMapping/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/08-temporalMapping/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..0c2c796 --- /dev/null +++ b/examples/Chapter4/08-temporalMapping/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,35 @@ +package examples.stateless; + +import java.util.Calendar; +import java.util.Collection; +import java.util.Date; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(int id, String name, long salary, Calendar dob) { + Employee emp = new Employee(); + emp.setId(id); + emp.setName(name); + emp.setSalary(salary); + emp.setDob(dob); + emp.setStartDate(new Date()); + em.persist(emp); + + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/08-temporalMapping/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/08-temporalMapping/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..2c22490 --- /dev/null +++ b/examples/Chapter4/08-temporalMapping/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,121 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Calendar; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 4: Temporal Type Mapping Example"; + + private final String DESCRIPTION = + "This example demonstates how to map temporal type entity attributes.
" + + "It allows you to create/find employees. All operations " + + "are persisted to the database."; + + + // inject a reference to the EmployeeService slsb + @EJB EmployeeService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("Create")) { + Calendar dob = Calendar.getInstance(); + dob.set(parseInt(request.getParameter("year")), + parseInt(request.getParameter("month"))-1, // month is zero-based + parseInt(request.getParameter("date"))); + Employee emp = service.createEmployee( + parseInt(request.getParameter("id")), + request.getParameter("name"), + parseLong(request.getParameter("salary")), + dob); + out.println("Created " + emp); + } else if (action.equals("FindAll")) { + Collection emps = service.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Address + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
Employee Name:(String)
Employee Salary:(long)
Empoyee DOB:"); + out.println("-"); + out.println("-"); + out.println(" day-month-year (xx-xx-xxxx)"); + out.println("
"); + out.println("
"); + // form to find all + out.println("

Find all Employees

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter4/08-temporalMapping/undeploy.bat b/examples/Chapter4/08-temporalMapping/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter4/08-temporalMapping/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter4/09-transientMapping/build.xml b/examples/Chapter4/09-transientMapping/build.xml new file mode 100644 index 0000000..f8c5b39 --- /dev/null +++ b/examples/Chapter4/09-transientMapping/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/09-transientMapping/deploy.bat b/examples/Chapter4/09-transientMapping/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter4/09-transientMapping/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter4/09-transientMapping/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/09-transientMapping/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..4fb3ce5 --- /dev/null +++ b/examples/Chapter4/09-transientMapping/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/transientMapping + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/09-transientMapping/etc/sql/db.sql b/examples/Chapter4/09-transientMapping/etc/sql/db.sql new file mode 100644 index 0000000..e35905b --- /dev/null +++ b/examples/Chapter4/09-transientMapping/etc/sql/db.sql @@ -0,0 +1,4 @@ +DROP TABLE EMPLOYEE; + +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, PRIMARY KEY (ID)); + diff --git a/examples/Chapter4/09-transientMapping/etc/web/WEB-INF/web.xml b/examples/Chapter4/09-transientMapping/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/09-transientMapping/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter4/09-transientMapping/src/model/examples/model/Employee.java b/examples/Chapter4/09-transientMapping/src/model/examples/model/Employee.java new file mode 100644 index 0000000..a916b26 --- /dev/null +++ b/examples/Chapter4/09-transientMapping/src/model/examples/model/Employee.java @@ -0,0 +1,55 @@ +package examples.model; + +import java.util.Locale; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Transient; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + @Transient + private String convertedName; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + convertedName = convertName(name); + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public String getConvertedName() { + return convertedName; + } + + public String toString() { + return "Employee " + " id: " + getId() + " name: " + getName() + " converted name: " + getConvertedName() + " salary: " + getSalary(); + } + + protected String convertName(String name) { + // Convert to upper case Canadian... + return name.toUpperCase(Locale.CANADA); + } +} diff --git a/examples/Chapter4/09-transientMapping/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/09-transientMapping/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..1707ef2 --- /dev/null +++ b/examples/Chapter4/09-transientMapping/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(int id, String name, long salary); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter4/09-transientMapping/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/09-transientMapping/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..0815bdf --- /dev/null +++ b/examples/Chapter4/09-transientMapping/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,31 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(int id, String name, long salary) { + Employee emp = new Employee(); + emp.setId(id); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/09-transientMapping/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/09-transientMapping/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..2f57ab5 --- /dev/null +++ b/examples/Chapter4/09-transientMapping/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,110 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 4: Transient Mapping Example"; + + private final String DESCRIPTION = + "This example demonstates how to specify a transient mapping for entities.
" + + "It allows you to create/find employees. All operations " + + "are persisted to the database."; + + + // inject a reference to the EmployeeService slsb + @EJB EmployeeService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("Create")) { + Employee emp = service.createEmployee( + parseInt(request.getParameter("id")), + request.getParameter("name"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("FindAll")) { + Collection emps = service.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Address + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
Employee Name:(String)
Employee Salary:(long)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter4/09-transientMapping/undeploy.bat b/examples/Chapter4/09-transientMapping/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter4/09-transientMapping/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter4/10-autoIdGeneration/build.xml b/examples/Chapter4/10-autoIdGeneration/build.xml new file mode 100644 index 0000000..4b8350b --- /dev/null +++ b/examples/Chapter4/10-autoIdGeneration/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/10-autoIdGeneration/deploy.bat b/examples/Chapter4/10-autoIdGeneration/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter4/10-autoIdGeneration/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter4/10-autoIdGeneration/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/10-autoIdGeneration/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..2ec83b7 --- /dev/null +++ b/examples/Chapter4/10-autoIdGeneration/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/autoIdGeneration + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/10-autoIdGeneration/etc/sql/db.sql b/examples/Chapter4/10-autoIdGeneration/etc/sql/db.sql new file mode 100644 index 0000000..4d41c4b --- /dev/null +++ b/examples/Chapter4/10-autoIdGeneration/etc/sql/db.sql @@ -0,0 +1,7 @@ +DROP TABLE EMPLOYEE; +DROP TABLE SEQUENCE; + +CREATE TABLE SEQUENCE (SEQ_NAME VARCHAR(64), SEQ_COUNT INTEGER); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, PRIMARY KEY (ID)); + +INSERT INTO SEQUENCE (SEQ_NAME, SEQ_COUNT ) VALUES('SEQ_GEN',1); diff --git a/examples/Chapter4/10-autoIdGeneration/etc/web/WEB-INF/web.xml b/examples/Chapter4/10-autoIdGeneration/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/10-autoIdGeneration/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter4/10-autoIdGeneration/src/model/examples/model/Employee.java b/examples/Chapter4/10-autoIdGeneration/src/model/examples/model/Employee.java new file mode 100644 index 0000000..8d50e3c --- /dev/null +++ b/examples/Chapter4/10-autoIdGeneration/src/model/examples/model/Employee.java @@ -0,0 +1,42 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Employee { + @Id @GeneratedValue(strategy=GenerationType.AUTO) + private int id; + private String name; + private long salary; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + " salary: " + getSalary(); + } +} diff --git a/examples/Chapter4/10-autoIdGeneration/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/10-autoIdGeneration/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..824af91 --- /dev/null +++ b/examples/Chapter4/10-autoIdGeneration/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(String name, long salary); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter4/10-autoIdGeneration/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/10-autoIdGeneration/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..e98e2fe --- /dev/null +++ b/examples/Chapter4/10-autoIdGeneration/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,30 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String name, long salary) { + Employee emp = new Employee(); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/10-autoIdGeneration/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/10-autoIdGeneration/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..fec98aa --- /dev/null +++ b/examples/Chapter4/10-autoIdGeneration/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,100 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 4: Auto Id Generation Example"; + + private final String DESCRIPTION = + "This example demonstates how to use auto id generation.
" + + "It allows you to create/find employees. In the case of TopLink " + + "Essentials, a sequence table is required."; + + + // inject a reference to the EmployeeService slsb + @EJB EmployeeService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("Create")) { + Employee emp = service.createEmployee( + request.getParameter("name"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("FindAll")) { + Collection emps = service.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Address + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
Employee Salary:(long)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter4/10-autoIdGeneration/undeploy.bat b/examples/Chapter4/10-autoIdGeneration/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter4/10-autoIdGeneration/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter4/11-tableIdGeneration/build.xml b/examples/Chapter4/11-tableIdGeneration/build.xml new file mode 100644 index 0000000..a3f28ae --- /dev/null +++ b/examples/Chapter4/11-tableIdGeneration/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/11-tableIdGeneration/deploy.bat b/examples/Chapter4/11-tableIdGeneration/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter4/11-tableIdGeneration/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter4/11-tableIdGeneration/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/11-tableIdGeneration/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..d187405 --- /dev/null +++ b/examples/Chapter4/11-tableIdGeneration/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/tableIdGeneration + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/11-tableIdGeneration/etc/sql/db.sql b/examples/Chapter4/11-tableIdGeneration/etc/sql/db.sql new file mode 100644 index 0000000..ba52474 --- /dev/null +++ b/examples/Chapter4/11-tableIdGeneration/etc/sql/db.sql @@ -0,0 +1,12 @@ +DROP TABLE EMPLOYEE; +DROP TABLE ADDRESS; +DROP TABLE ID_GEN; + +CREATE TABLE ADDRESS (ID INTEGER NOT NULL, CITY VARCHAR(255), STATE VARCHAR(255), STREET VARCHAR(255), ZIP VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, ADDRESS_ID INTEGER, + CONSTRAINT ADDRESS_FK FOREIGN KEY (ADDRESS_ID) REFERENCES ADDRESS (ID), PRIMARY KEY (ID)); +CREATE TABLE ID_GEN (GEN_NAME VARCHAR(80), GEN_VAL INTEGER, PRIMARY KEY (GEN_NAME)); + +INSERT INTO ID_GEN (GEN_NAME, GEN_VAL) VALUES ('Emp_Gen', 0); +INSERT INTO ID_GEN (GEN_NAME, GEN_VAL) VALUES ('Addr_Gen', 10000); + diff --git a/examples/Chapter4/11-tableIdGeneration/etc/web/WEB-INF/web.xml b/examples/Chapter4/11-tableIdGeneration/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/11-tableIdGeneration/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter4/11-tableIdGeneration/src/model/examples/model/Address.java b/examples/Chapter4/11-tableIdGeneration/src/model/examples/model/Address.java new file mode 100644 index 0000000..a7651d7 --- /dev/null +++ b/examples/Chapter4/11-tableIdGeneration/src/model/examples/model/Address.java @@ -0,0 +1,73 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.TableGenerator; + +@Entity +public class Address { + @TableGenerator(name="Address_Gen", + table="ID_GEN", + pkColumnName="GEN_NAME", + valueColumnName="GEN_VAL", + pkColumnValue="Addr_Gen", + initialValue=10000, + allocationSize=100) + @Id @GeneratedValue(strategy=GenerationType.TABLE, + generator="Address_Gen") + private int id; + private String street; + private String city; + private String state; + private String zip; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getStreet() { + return street; + } + + public void setStreet(String address) { + this.street = address; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getZip() { + return zip; + } + + public void setZip(String zip) { + this.zip = zip; + } + public String toString() { + return "Address id: " + getId() + + ", street: " + getStreet() + + ", city: " + getCity() + + ", state: " + getState() + + ", zip: " + getZip(); + } + +} diff --git a/examples/Chapter4/11-tableIdGeneration/src/model/examples/model/Employee.java b/examples/Chapter4/11-tableIdGeneration/src/model/examples/model/Employee.java new file mode 100644 index 0000000..aad9d2a --- /dev/null +++ b/examples/Chapter4/11-tableIdGeneration/src/model/examples/model/Employee.java @@ -0,0 +1,60 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToOne; +import javax.persistence.TableGenerator; + +@Entity +public class Employee { + @TableGenerator(name="Emp_Gen", + table="ID_GEN", + pkColumnName="GEN_NAME", + valueColumnName="GEN_VAL") + @Id @GeneratedValue(strategy=GenerationType.TABLE, + generator="Emp_Gen") + private int id; + private String name; + private long salary; + + @OneToOne + private Address address; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + " salary: " + getSalary(); + } +} diff --git a/examples/Chapter4/11-tableIdGeneration/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/11-tableIdGeneration/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..4002008 --- /dev/null +++ b/examples/Chapter4/11-tableIdGeneration/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(String name, long salary, + String street, String city, String state, String zip); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter4/11-tableIdGeneration/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/11-tableIdGeneration/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..94b67a0 --- /dev/null +++ b/examples/Chapter4/11-tableIdGeneration/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,41 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Address; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String name, long salary, + String street, String city, String state, String zip) { + Employee emp = new Employee(); + emp.setName(name); + emp.setSalary(salary); + + Address addr = new Address(); + addr.setStreet(street); + addr.setCity(city); + addr.setState(state); + addr.setZip(zip); + emp.setAddress(addr); + + em.persist(emp); + em.persist(addr); + + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/11-tableIdGeneration/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/11-tableIdGeneration/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..c0d837a --- /dev/null +++ b/examples/Chapter4/11-tableIdGeneration/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,107 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 4: Table Id Generation Example"; + + private final String DESCRIPTION = + "This example demonstates how to use table id generation.
" + + "It allows you to create/find employees."; + + + // inject a reference to the EmployeeService slsb + @EJB EmployeeService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("Create")) { + Employee emp = service.createEmployee( + request.getParameter("name"), + parseLong(request.getParameter("salary")), + request.getParameter("street"), + request.getParameter("city"), + request.getParameter("state"), + request.getParameter("zip")); + out.println("Created " + emp + " with " + emp.getAddress()); + } else if (action.equals("FindAll")) { + Collection emps = service.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + " with " + emp.getAddress() + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Address + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
Employee Salary:(long)
Address Street:(String)
Address City:(String)
Address State:(String)
Address Zip:(String)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter4/11-tableIdGeneration/undeploy.bat b/examples/Chapter4/11-tableIdGeneration/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter4/11-tableIdGeneration/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter4/12-sequenceIdGeneration/build.xml b/examples/Chapter4/12-sequenceIdGeneration/build.xml new file mode 100644 index 0000000..b92da71 --- /dev/null +++ b/examples/Chapter4/12-sequenceIdGeneration/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/12-sequenceIdGeneration/deploy.bat b/examples/Chapter4/12-sequenceIdGeneration/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter4/12-sequenceIdGeneration/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter4/12-sequenceIdGeneration/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/12-sequenceIdGeneration/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..c439b8d --- /dev/null +++ b/examples/Chapter4/12-sequenceIdGeneration/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/sequenceIdGeneration + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/12-sequenceIdGeneration/etc/sql/db.sql b/examples/Chapter4/12-sequenceIdGeneration/etc/sql/db.sql new file mode 100644 index 0000000..9b497a3 --- /dev/null +++ b/examples/Chapter4/12-sequenceIdGeneration/etc/sql/db.sql @@ -0,0 +1,7 @@ +DROP TABLE EMPLOYEE; +DROP SEQUENCE Emp_Seq; + +CREATE TABLE EMPLOYEE (ID NUMBER NOT NULL, NAME VARCHAR(255), SALARY NUMBER, PRIMARY KEY (ID)); + +CREATE SEQUENCE Emp_Seq MINVALUE 1 START WITH 100 INCREMENT BY 50; + diff --git a/examples/Chapter4/12-sequenceIdGeneration/etc/web/WEB-INF/web.xml b/examples/Chapter4/12-sequenceIdGeneration/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/12-sequenceIdGeneration/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter4/12-sequenceIdGeneration/src/model/examples/model/Employee.java b/examples/Chapter4/12-sequenceIdGeneration/src/model/examples/model/Employee.java new file mode 100644 index 0000000..a133194 --- /dev/null +++ b/examples/Chapter4/12-sequenceIdGeneration/src/model/examples/model/Employee.java @@ -0,0 +1,43 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.SequenceGenerator; +import javax.persistence.Id; + +@Entity +public class Employee { + @SequenceGenerator(name="Emp_Gen", sequenceName="Emp_Seq") + @Id @GeneratedValue(generator="Emp_Gen") + private int id; + private String name; + private long salary; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + " salary: " + getSalary(); + } +} diff --git a/examples/Chapter4/12-sequenceIdGeneration/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/12-sequenceIdGeneration/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..824af91 --- /dev/null +++ b/examples/Chapter4/12-sequenceIdGeneration/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(String name, long salary); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter4/12-sequenceIdGeneration/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/12-sequenceIdGeneration/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..e98e2fe --- /dev/null +++ b/examples/Chapter4/12-sequenceIdGeneration/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,30 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String name, long salary) { + Employee emp = new Employee(); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/12-sequenceIdGeneration/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/12-sequenceIdGeneration/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..2a8efac --- /dev/null +++ b/examples/Chapter4/12-sequenceIdGeneration/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,99 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 4: Sequence Id Generation Example"; + + private final String DESCRIPTION = + "This example demonstates how to DB sequence id generation.
" + + "It allows you to create/find employees."; + + + // inject a reference to the EmployeeService slsb + @EJB EmployeeService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("Create")) { + Employee emp = service.createEmployee( + request.getParameter("name"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("FindAll")) { + Collection emps = service.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Address + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
Employee Salary:(long)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter4/12-sequenceIdGeneration/undeploy.bat b/examples/Chapter4/12-sequenceIdGeneration/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter4/12-sequenceIdGeneration/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter4/13-dbIdentityIdGeneration/build.xml b/examples/Chapter4/13-dbIdentityIdGeneration/build.xml new file mode 100644 index 0000000..acdd6bd --- /dev/null +++ b/examples/Chapter4/13-dbIdentityIdGeneration/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/13-dbIdentityIdGeneration/deploy.bat b/examples/Chapter4/13-dbIdentityIdGeneration/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter4/13-dbIdentityIdGeneration/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter4/13-dbIdentityIdGeneration/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/13-dbIdentityIdGeneration/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..0278f2b --- /dev/null +++ b/examples/Chapter4/13-dbIdentityIdGeneration/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/dbIdentityIdGeneration + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/13-dbIdentityIdGeneration/etc/sql/db.sql b/examples/Chapter4/13-dbIdentityIdGeneration/etc/sql/db.sql new file mode 100644 index 0000000..1fb6e32 --- /dev/null +++ b/examples/Chapter4/13-dbIdentityIdGeneration/etc/sql/db.sql @@ -0,0 +1,5 @@ +DROP TABLE EMPLOYEE; + +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + NAME VARCHAR(255), SALARY BIGINT, PRIMARY KEY (ID)); + diff --git a/examples/Chapter4/13-dbIdentityIdGeneration/etc/web/WEB-INF/web.xml b/examples/Chapter4/13-dbIdentityIdGeneration/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/13-dbIdentityIdGeneration/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter4/13-dbIdentityIdGeneration/src/model/examples/model/Employee.java b/examples/Chapter4/13-dbIdentityIdGeneration/src/model/examples/model/Employee.java new file mode 100644 index 0000000..41de4d1 --- /dev/null +++ b/examples/Chapter4/13-dbIdentityIdGeneration/src/model/examples/model/Employee.java @@ -0,0 +1,42 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Employee { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + private long salary; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + " salary: " + getSalary(); + } +} diff --git a/examples/Chapter4/13-dbIdentityIdGeneration/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/13-dbIdentityIdGeneration/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..824af91 --- /dev/null +++ b/examples/Chapter4/13-dbIdentityIdGeneration/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(String name, long salary); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter4/13-dbIdentityIdGeneration/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/13-dbIdentityIdGeneration/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..e98e2fe --- /dev/null +++ b/examples/Chapter4/13-dbIdentityIdGeneration/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,30 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String name, long salary) { + Employee emp = new Employee(); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/13-dbIdentityIdGeneration/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/13-dbIdentityIdGeneration/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..b2ff9ce --- /dev/null +++ b/examples/Chapter4/13-dbIdentityIdGeneration/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,99 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 4: DB Identity Id Generation Example"; + + private final String DESCRIPTION = + "This example demonstates how to use table id generation.
" + + "It allows you to create/find employees."; + + + // inject a reference to the EmployeeService slsb + @EJB EmployeeService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("Create")) { + Employee emp = service.createEmployee( + request.getParameter("name"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("FindAll")) { + Collection emps = service.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Address + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
Employee Salary:(long)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter4/13-dbIdentityIdGeneration/undeploy.bat b/examples/Chapter4/13-dbIdentityIdGeneration/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter4/13-dbIdentityIdGeneration/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter4/14-manyToOne/build.xml b/examples/Chapter4/14-manyToOne/build.xml new file mode 100644 index 0000000..0fb1f33 --- /dev/null +++ b/examples/Chapter4/14-manyToOne/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/14-manyToOne/deploy.bat b/examples/Chapter4/14-manyToOne/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter4/14-manyToOne/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter4/14-manyToOne/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/14-manyToOne/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..95233c4 --- /dev/null +++ b/examples/Chapter4/14-manyToOne/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/manyToOne + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/14-manyToOne/etc/sql/db.sql b/examples/Chapter4/14-manyToOne/etc/sql/db.sql new file mode 100644 index 0000000..5b2112b --- /dev/null +++ b/examples/Chapter4/14-manyToOne/etc/sql/db.sql @@ -0,0 +1,10 @@ +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + NAME VARCHAR(255), SALARY BIGINT, + DEPARTMENT_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID)); + diff --git a/examples/Chapter4/14-manyToOne/etc/web/WEB-INF/web.xml b/examples/Chapter4/14-manyToOne/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/14-manyToOne/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter4/14-manyToOne/src/model/examples/model/Department.java b/examples/Chapter4/14-manyToOne/src/model/examples/model/Department.java new file mode 100644 index 0000000..42e0787 --- /dev/null +++ b/examples/Chapter4/14-manyToOne/src/model/examples/model/Department.java @@ -0,0 +1,34 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Department { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String deptName) { + this.name = deptName; + } + + public String toString() { + return "Department id: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter4/14-manyToOne/src/model/examples/model/Employee.java b/examples/Chapter4/14-manyToOne/src/model/examples/model/Employee.java new file mode 100644 index 0000000..e161138 --- /dev/null +++ b/examples/Chapter4/14-manyToOne/src/model/examples/model/Employee.java @@ -0,0 +1,55 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@Entity +public class Employee { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + private long salary; + + @ManyToOne + private Department department; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " with " + getDepartment(); + } +} diff --git a/examples/Chapter4/14-manyToOne/src/model/examples/stateless/DepartmentService.java b/examples/Chapter4/14-manyToOne/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..7003e8d --- /dev/null +++ b/examples/Chapter4/14-manyToOne/src/model/examples/stateless/DepartmentService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Department; + +public interface DepartmentService { + public Department createDepartment(String name); + public Collection findAllDepartments(); +} diff --git a/examples/Chapter4/14-manyToOne/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter4/14-manyToOne/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..7d47cb1 --- /dev/null +++ b/examples/Chapter4/14-manyToOne/src/model/examples/stateless/DepartmentServiceBean.java @@ -0,0 +1,29 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; + +@Stateless +public class DepartmentServiceBean implements DepartmentService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Department createDepartment(String name) { + Department dept = new Department(); + dept.setName(name); + em.persist(dept); + + return dept; + } + + public Collection findAllDepartments() { + Query query = em.createQuery("SELECT d FROM Department d"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/14-manyToOne/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/14-manyToOne/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..84116f6 --- /dev/null +++ b/examples/Chapter4/14-manyToOne/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(String name, long salary); + public Employee setEmployeeDepartment(int empId, int deptId); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter4/14-manyToOne/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/14-manyToOne/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..b678784 --- /dev/null +++ b/examples/Chapter4/14-manyToOne/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,38 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String name, long salary) { + Employee emp = new Employee(); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + + return emp; + } + + public Employee setEmployeeDepartment(int empId, int deptId) { + Employee emp = em.find(Employee.class, empId); + Department dept = em.find(Department.class, deptId); + emp.setDepartment(dept); + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/14-manyToOne/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/14-manyToOne/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..c1c0854 --- /dev/null +++ b/examples/Chapter4/14-manyToOne/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,143 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Department; +import examples.model.Employee; +import examples.stateless.DepartmentService; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 4: Many-to-One Example"; + + private final String DESCRIPTION = + "This example demonstates how to specify many-to-one relationships for entities.
" + + "It allows you to create/find employees & departments and associate them."; + + + @EJB EmployeeService empService; + @EJB DepartmentService deptService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("CreateEmp")) { + Employee emp = empService.createEmployee( + request.getParameter("empName"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("CreateDept")) { + Department dept = deptService.createDepartment( + request.getParameter("deptName")); + out.println("Created " + dept); + } else if (action.equals("SetEmployeeDept")) { + Employee emp = empService.setEmployeeDepartment( + parseInt(request.getParameter("empId")), + parseInt(request.getParameter("deptId"))); + out.println("Updated " + emp); + } else if (action.equals("FindAll")) { + Collection emps = empService.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + + out.println("
"); + Collection depts = deptService.findAllDepartments(); + if (depts.isEmpty()) { + out.println("No Departments found "); + } else { + out.println("Found Departments:
"); + for (Department dept : depts) { + out.println(dept + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Department + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
Employee Salary:(long)
"); + out.println("
"); + out.println("

Create a Department

"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Dept Name:(String)
"); + + out.println("
"); + out.println("

Set Employee's Department

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Emp Id:(int)
Dept Id:(int)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees & Departments

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter4/14-manyToOne/undeploy.bat b/examples/Chapter4/14-manyToOne/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter4/14-manyToOne/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter4/15-joinColumn/build.xml b/examples/Chapter4/15-joinColumn/build.xml new file mode 100644 index 0000000..b8cb4f2 --- /dev/null +++ b/examples/Chapter4/15-joinColumn/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/15-joinColumn/deploy.bat b/examples/Chapter4/15-joinColumn/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter4/15-joinColumn/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter4/15-joinColumn/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/15-joinColumn/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..8dc9cbc --- /dev/null +++ b/examples/Chapter4/15-joinColumn/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/joinColumn + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/15-joinColumn/etc/sql/db.sql b/examples/Chapter4/15-joinColumn/etc/sql/db.sql new file mode 100644 index 0000000..d58340d --- /dev/null +++ b/examples/Chapter4/15-joinColumn/etc/sql/db.sql @@ -0,0 +1,10 @@ +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + NAME VARCHAR(255), SALARY BIGINT, + DEPT_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPT_FK FOREIGN KEY (DEPT_ID) REFERENCES DEPARTMENT (ID)); + diff --git a/examples/Chapter4/15-joinColumn/etc/web/WEB-INF/web.xml b/examples/Chapter4/15-joinColumn/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/15-joinColumn/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter4/15-joinColumn/src/model/examples/model/Department.java b/examples/Chapter4/15-joinColumn/src/model/examples/model/Department.java new file mode 100644 index 0000000..42e0787 --- /dev/null +++ b/examples/Chapter4/15-joinColumn/src/model/examples/model/Department.java @@ -0,0 +1,34 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Department { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String deptName) { + this.name = deptName; + } + + public String toString() { + return "Department id: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter4/15-joinColumn/src/model/examples/model/Employee.java b/examples/Chapter4/15-joinColumn/src/model/examples/model/Employee.java new file mode 100644 index 0000000..e40fb71 --- /dev/null +++ b/examples/Chapter4/15-joinColumn/src/model/examples/model/Employee.java @@ -0,0 +1,57 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; + +@Entity +public class Employee { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + private long salary; + + @ManyToOne + @JoinColumn(name="DEPT_ID") + private Department department; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " with " + getDepartment(); + } +} diff --git a/examples/Chapter4/15-joinColumn/src/model/examples/stateless/DepartmentService.java b/examples/Chapter4/15-joinColumn/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..7003e8d --- /dev/null +++ b/examples/Chapter4/15-joinColumn/src/model/examples/stateless/DepartmentService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Department; + +public interface DepartmentService { + public Department createDepartment(String name); + public Collection findAllDepartments(); +} diff --git a/examples/Chapter4/15-joinColumn/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter4/15-joinColumn/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..7d47cb1 --- /dev/null +++ b/examples/Chapter4/15-joinColumn/src/model/examples/stateless/DepartmentServiceBean.java @@ -0,0 +1,29 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; + +@Stateless +public class DepartmentServiceBean implements DepartmentService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Department createDepartment(String name) { + Department dept = new Department(); + dept.setName(name); + em.persist(dept); + + return dept; + } + + public Collection findAllDepartments() { + Query query = em.createQuery("SELECT d FROM Department d"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/15-joinColumn/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/15-joinColumn/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..84116f6 --- /dev/null +++ b/examples/Chapter4/15-joinColumn/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(String name, long salary); + public Employee setEmployeeDepartment(int empId, int deptId); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter4/15-joinColumn/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/15-joinColumn/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..b678784 --- /dev/null +++ b/examples/Chapter4/15-joinColumn/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,38 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String name, long salary) { + Employee emp = new Employee(); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + + return emp; + } + + public Employee setEmployeeDepartment(int empId, int deptId) { + Employee emp = em.find(Employee.class, empId); + Department dept = em.find(Department.class, deptId); + emp.setDepartment(dept); + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/15-joinColumn/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/15-joinColumn/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..426b374 --- /dev/null +++ b/examples/Chapter4/15-joinColumn/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,144 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Department; +import examples.model.Employee; +import examples.stateless.DepartmentService; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 4: Many-to-One Join Column Example"; + + private final String DESCRIPTION = + "This example demonstates how to specify a join column for relationships.
" + + "It allows you to create/find employees & departments and associate them."; + + + @EJB EmployeeService empService; + @EJB DepartmentService deptService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("CreateEmp")) { + Employee emp = empService.createEmployee( + request.getParameter("empName"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("CreateDept")) { + Department dept = deptService.createDepartment( + request.getParameter("deptName")); + out.println("Created " + dept); + } else if (action.equals("SetEmployeeDept")) { + Employee emp = empService.setEmployeeDepartment( + parseInt(request.getParameter("empId")), + parseInt(request.getParameter("deptId"))); + out.println("Updated " + emp); + } else if (action.equals("FindAll")) { + Collection emps = empService.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + + out.println("
"); + Collection depts = deptService.findAllDepartments(); + if (depts.isEmpty()) { + out.println("No Departments found "); + } else { + out.println("Found Departments:
"); + for (Department dept : depts) { + out.println(dept + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Department + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
Employee Salary:(long)
"); + + out.println("
"); + out.println("

Create a Department

"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Dept Name:(String)
"); + + out.println("
"); + out.println("

Set an Employee's Department

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Emp Id:(int)
Dept Id:(int)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees & Departments

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter4/15-joinColumn/undeploy.bat b/examples/Chapter4/15-joinColumn/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter4/15-joinColumn/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter4/16-oneToOneUnidirectional/build.xml b/examples/Chapter4/16-oneToOneUnidirectional/build.xml new file mode 100644 index 0000000..0dcee43 --- /dev/null +++ b/examples/Chapter4/16-oneToOneUnidirectional/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/16-oneToOneUnidirectional/deploy.bat b/examples/Chapter4/16-oneToOneUnidirectional/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter4/16-oneToOneUnidirectional/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter4/16-oneToOneUnidirectional/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/16-oneToOneUnidirectional/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..fc3a646 --- /dev/null +++ b/examples/Chapter4/16-oneToOneUnidirectional/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/oneToOneUnidirectional + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/16-oneToOneUnidirectional/etc/sql/db.sql b/examples/Chapter4/16-oneToOneUnidirectional/etc/sql/db.sql new file mode 100644 index 0000000..c617acd --- /dev/null +++ b/examples/Chapter4/16-oneToOneUnidirectional/etc/sql/db.sql @@ -0,0 +1,10 @@ +DROP TABLE EMPLOYEE; +DROP TABLE PARKING_SPACE; + +CREATE TABLE PARKING_SPACE (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + LOT INTEGER, LOCATION VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + NAME VARCHAR(255), SALARY BIGINT, + PSPACE_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT PSPACE_FK FOREIGN KEY (PSPACE_ID) REFERENCES PARKING_SPACE(ID)); + diff --git a/examples/Chapter4/16-oneToOneUnidirectional/etc/web/WEB-INF/web.xml b/examples/Chapter4/16-oneToOneUnidirectional/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/16-oneToOneUnidirectional/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter4/16-oneToOneUnidirectional/src/model/examples/model/Employee.java b/examples/Chapter4/16-oneToOneUnidirectional/src/model/examples/model/Employee.java new file mode 100644 index 0000000..57e0ff1 --- /dev/null +++ b/examples/Chapter4/16-oneToOneUnidirectional/src/model/examples/model/Employee.java @@ -0,0 +1,57 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; + +@Entity +public class Employee { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + private long salary; + + @OneToOne + @JoinColumn(name="PSPACE_ID") + private ParkingSpace parkingSpace; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public ParkingSpace getParkingSpace() { + return parkingSpace; + } + + public void setParkingSpace(ParkingSpace parkingSpace) { + this.parkingSpace = parkingSpace; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " with " + getParkingSpace(); + } +} diff --git a/examples/Chapter4/16-oneToOneUnidirectional/src/model/examples/model/ParkingSpace.java b/examples/Chapter4/16-oneToOneUnidirectional/src/model/examples/model/ParkingSpace.java new file mode 100644 index 0000000..d9fff74 --- /dev/null +++ b/examples/Chapter4/16-oneToOneUnidirectional/src/model/examples/model/ParkingSpace.java @@ -0,0 +1,46 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name="PARKING_SPACE") +public class ParkingSpace { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private int lot; + private String location; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getLot() { + return lot; + } + + public void setLot(int lot) { + this.lot = lot; + } + + public String getLocation() { + return location; + } + + public void setLocation(String deptName) { + this.location = deptName; + } + + public String toString() { + return "ParkingSpace id: " + getId() + " lot: " + getLot() + + ", location: " + getLocation(); + } + +} diff --git a/examples/Chapter4/16-oneToOneUnidirectional/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/16-oneToOneUnidirectional/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..4768f09 --- /dev/null +++ b/examples/Chapter4/16-oneToOneUnidirectional/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(String name, long salary); + public Employee setEmployeeParkingSpace(int empId, int spaceId); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter4/16-oneToOneUnidirectional/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/16-oneToOneUnidirectional/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..678d876 --- /dev/null +++ b/examples/Chapter4/16-oneToOneUnidirectional/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,38 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.ParkingSpace; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String name, long salary) { + Employee emp = new Employee(); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + + return emp; + } + + public Employee setEmployeeParkingSpace(int empId, int spaceId) { + Employee emp = em.find(Employee.class, empId); + ParkingSpace pSpace = em.find(ParkingSpace.class, spaceId); + emp.setParkingSpace(pSpace); + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/16-oneToOneUnidirectional/src/model/examples/stateless/ParkingSpaceService.java b/examples/Chapter4/16-oneToOneUnidirectional/src/model/examples/stateless/ParkingSpaceService.java new file mode 100644 index 0000000..cb201cf --- /dev/null +++ b/examples/Chapter4/16-oneToOneUnidirectional/src/model/examples/stateless/ParkingSpaceService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.ParkingSpace; + +public interface ParkingSpaceService { + public ParkingSpace createParkingSpace(int lot, String location); + public Collection findAllParkingSpaces(); +} diff --git a/examples/Chapter4/16-oneToOneUnidirectional/src/model/examples/stateless/ParkingSpaceServiceBean.java b/examples/Chapter4/16-oneToOneUnidirectional/src/model/examples/stateless/ParkingSpaceServiceBean.java new file mode 100644 index 0000000..4c1bf24 --- /dev/null +++ b/examples/Chapter4/16-oneToOneUnidirectional/src/model/examples/stateless/ParkingSpaceServiceBean.java @@ -0,0 +1,30 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.ParkingSpace; + +@Stateless +public class ParkingSpaceServiceBean implements ParkingSpaceService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public ParkingSpace createParkingSpace(int lot, String location) { + ParkingSpace space = new ParkingSpace(); + space.setLot(lot); + space.setLocation(location); + em.persist(space); + + return space; + } + + public Collection findAllParkingSpaces() { + Query query = em.createQuery("SELECT p FROM ParkingSpace p"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/16-oneToOneUnidirectional/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/16-oneToOneUnidirectional/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..fb48110 --- /dev/null +++ b/examples/Chapter4/16-oneToOneUnidirectional/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,145 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.ParkingSpace; +import examples.model.Employee; +import examples.stateless.ParkingSpaceService; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 4: One-to-One Unidirectional Example"; + + private final String DESCRIPTION = + "This example demonstates how to specify unidirectional one-to-one relationships for entities.
" + + "It allows you to create/find employees & parking spaces and associate them."; + + + @EJB EmployeeService empService; + @EJB ParkingSpaceService pSpaceService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("CreateEmp")) { + Employee emp = empService.createEmployee( + request.getParameter("empName"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("CreateParkingSpace")) { + ParkingSpace pSpace = pSpaceService.createParkingSpace( + parseInt(request.getParameter("lot")), + request.getParameter("location")); + out.println("Created " + pSpace); + } else if (action.equals("SetEmployeeParkingSpace")) { + Employee emp = empService.setEmployeeParkingSpace( + parseInt(request.getParameter("empId")), + parseInt(request.getParameter("pSpaceId"))); + out.println("Updated " + emp); + } else if (action.equals("FindAll")) { + Collection emps = empService.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + + out.println("
"); + Collection pSpaces = pSpaceService.findAllParkingSpaces(); + if (pSpaces.isEmpty()) { + out.println("No ParkingSpaces found "); + } else { + out.println("Found ParkingSpaces:
"); + for (ParkingSpace pSpace : pSpaces) { + out.println(pSpace + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
Employee Salary:(long)
"); + + out.println("
"); + out.println("

Create a ParkingSpace

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
ParkingSpace lot#:(int)
location:(String)
"); + + out.println("
"); + out.println("

Set an Employee's ParkingSpace

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Emp Id:(int)
Parking Space Id:(int)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees & Parking Spaces

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter4/16-oneToOneUnidirectional/undeploy.bat b/examples/Chapter4/16-oneToOneUnidirectional/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter4/16-oneToOneUnidirectional/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter4/17-oneToOneBidirectional/build.xml b/examples/Chapter4/17-oneToOneBidirectional/build.xml new file mode 100644 index 0000000..2d6a9f2 --- /dev/null +++ b/examples/Chapter4/17-oneToOneBidirectional/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/17-oneToOneBidirectional/deploy.bat b/examples/Chapter4/17-oneToOneBidirectional/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter4/17-oneToOneBidirectional/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter4/17-oneToOneBidirectional/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/17-oneToOneBidirectional/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..b04c0fc --- /dev/null +++ b/examples/Chapter4/17-oneToOneBidirectional/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/oneToOneBidirectional + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/17-oneToOneBidirectional/etc/sql/db.sql b/examples/Chapter4/17-oneToOneBidirectional/etc/sql/db.sql new file mode 100644 index 0000000..80a6acd --- /dev/null +++ b/examples/Chapter4/17-oneToOneBidirectional/etc/sql/db.sql @@ -0,0 +1,16 @@ +DROP TABLE EMPLOYEE; +DROP TABLE PARKING_SPACE; + +CREATE TABLE PARKING_SPACE (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + LOT INTEGER, LOCATION VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + NAME VARCHAR(255), SALARY BIGINT, + PSPACE_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT PSPACE_FK FOREIGN KEY (PSPACE_ID) REFERENCES PARKING_SPACE(ID)); + + +INSERT INTO PARKING_SPACE (LOT, LOCATION) VALUES (1, 'East Lot'); +INSERT INTO PARKING_SPACE (LOT , LOCATION) VALUES (2, 'West Lot'); + +INSERT INTO EMPLOYEE (NAME, SALARY, PSPACE_ID) VALUES ('Joan', 59000, 1); +INSERT INTO EMPLOYEE (NAME, SALARY, PSPACE_ID) VALUES ('John', 59000, 1); diff --git a/examples/Chapter4/17-oneToOneBidirectional/etc/web/WEB-INF/web.xml b/examples/Chapter4/17-oneToOneBidirectional/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/17-oneToOneBidirectional/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter4/17-oneToOneBidirectional/src/model/examples/model/Employee.java b/examples/Chapter4/17-oneToOneBidirectional/src/model/examples/model/Employee.java new file mode 100644 index 0000000..57e0ff1 --- /dev/null +++ b/examples/Chapter4/17-oneToOneBidirectional/src/model/examples/model/Employee.java @@ -0,0 +1,57 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; + +@Entity +public class Employee { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + private long salary; + + @OneToOne + @JoinColumn(name="PSPACE_ID") + private ParkingSpace parkingSpace; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public ParkingSpace getParkingSpace() { + return parkingSpace; + } + + public void setParkingSpace(ParkingSpace parkingSpace) { + this.parkingSpace = parkingSpace; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " with " + getParkingSpace(); + } +} diff --git a/examples/Chapter4/17-oneToOneBidirectional/src/model/examples/model/ParkingSpace.java b/examples/Chapter4/17-oneToOneBidirectional/src/model/examples/model/ParkingSpace.java new file mode 100644 index 0000000..cbf9690 --- /dev/null +++ b/examples/Chapter4/17-oneToOneBidirectional/src/model/examples/model/ParkingSpace.java @@ -0,0 +1,56 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +@Entity +@Table(name="PARKING_SPACE") +public class ParkingSpace { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private int lot; + private String location; + @OneToOne(mappedBy="parkingSpace") + private Employee employee; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getLot() { + return lot; + } + + public void setLot(int lot) { + this.lot = lot; + } + + public String getLocation() { + return location; + } + + public void setLocation(String deptName) { + this.location = deptName; + } + + public Employee getEmployee() { + return employee; + } + + public void setEmployee(Employee employee) { + this.employee = employee; + } + + public String toString() { + return "ParkingSpace id: " + getId() + " lot: " + getLot() + + ", location: " + getLocation(); + } +} diff --git a/examples/Chapter4/17-oneToOneBidirectional/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/17-oneToOneBidirectional/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..4768f09 --- /dev/null +++ b/examples/Chapter4/17-oneToOneBidirectional/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(String name, long salary); + public Employee setEmployeeParkingSpace(int empId, int spaceId); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter4/17-oneToOneBidirectional/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/17-oneToOneBidirectional/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..ab7df24 --- /dev/null +++ b/examples/Chapter4/17-oneToOneBidirectional/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,39 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.ParkingSpace; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String name, long salary) { + Employee emp = new Employee(); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + + return emp; + } + + public Employee setEmployeeParkingSpace(int empId, int spaceId) { + Employee emp = em.find(Employee.class, empId); + ParkingSpace pSpace = em.find(ParkingSpace.class, spaceId); + emp.setParkingSpace(pSpace); + pSpace.setEmployee(emp); + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/17-oneToOneBidirectional/src/model/examples/stateless/ParkingSpaceService.java b/examples/Chapter4/17-oneToOneBidirectional/src/model/examples/stateless/ParkingSpaceService.java new file mode 100644 index 0000000..cb201cf --- /dev/null +++ b/examples/Chapter4/17-oneToOneBidirectional/src/model/examples/stateless/ParkingSpaceService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.ParkingSpace; + +public interface ParkingSpaceService { + public ParkingSpace createParkingSpace(int lot, String location); + public Collection findAllParkingSpaces(); +} diff --git a/examples/Chapter4/17-oneToOneBidirectional/src/model/examples/stateless/ParkingSpaceServiceBean.java b/examples/Chapter4/17-oneToOneBidirectional/src/model/examples/stateless/ParkingSpaceServiceBean.java new file mode 100644 index 0000000..4c1bf24 --- /dev/null +++ b/examples/Chapter4/17-oneToOneBidirectional/src/model/examples/stateless/ParkingSpaceServiceBean.java @@ -0,0 +1,30 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.ParkingSpace; + +@Stateless +public class ParkingSpaceServiceBean implements ParkingSpaceService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public ParkingSpace createParkingSpace(int lot, String location) { + ParkingSpace space = new ParkingSpace(); + space.setLot(lot); + space.setLocation(location); + em.persist(space); + + return space; + } + + public Collection findAllParkingSpaces() { + Query query = em.createQuery("SELECT p FROM ParkingSpace p"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/17-oneToOneBidirectional/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/17-oneToOneBidirectional/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..d8064aa --- /dev/null +++ b/examples/Chapter4/17-oneToOneBidirectional/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,146 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.ParkingSpace; +import examples.model.Employee; +import examples.stateless.ParkingSpaceService; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 4: One-to-One Bidirectional Example"; + + private final String DESCRIPTION = + "This example demonstates how to specify bidirectional one-to-one relationships for entities.
" + + "It allows you to create/find employees & parking spaces and associate them."; + + + @EJB EmployeeService empService; + @EJB ParkingSpaceService pSpaceService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("CreateEmp")) { + Employee emp = empService.createEmployee( + request.getParameter("empName"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("CreateParkingSpace")) { + ParkingSpace pSpace = pSpaceService.createParkingSpace( + parseInt(request.getParameter("lot")), + request.getParameter("location")); + out.println("Created " + pSpace); + } else if (action.equals("SetEmployeeParkingSpace")) { + Employee emp = empService.setEmployeeParkingSpace( + parseInt(request.getParameter("empId")), + parseInt(request.getParameter("pSpaceId"))); + out.println("Updated " + emp); + } else if (action.equals("FindAll")) { + Collection emps = empService.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + + out.println("
"); + Collection pSpaces = pSpaceService.findAllParkingSpaces(); + if (pSpaces.isEmpty()) { + out.println("No ParkingSpaces found "); + } else { + out.println("Found ParkingSpaces:
"); + for (ParkingSpace pSpace : pSpaces) { + out.println(pSpace + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Department + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
Employee Salary:(long)
"); + + out.println("
"); + out.println("

Create a ParkingSpace

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
ParkingSpace lot#:(int)
location:(String)
"); + + out.println("
"); + out.println("

Set an Employee's ParkingSpace

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Emp Id:(int)
Parking Space Id:(int)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees & Parking Spaces

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter4/17-oneToOneBidirectional/undeploy.bat b/examples/Chapter4/17-oneToOneBidirectional/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter4/17-oneToOneBidirectional/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter4/18-oneToOnePkMapping/build.xml b/examples/Chapter4/18-oneToOnePkMapping/build.xml new file mode 100644 index 0000000..04729d3 --- /dev/null +++ b/examples/Chapter4/18-oneToOnePkMapping/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/18-oneToOnePkMapping/deploy.bat b/examples/Chapter4/18-oneToOnePkMapping/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter4/18-oneToOnePkMapping/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter4/18-oneToOnePkMapping/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/18-oneToOnePkMapping/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..887f478 --- /dev/null +++ b/examples/Chapter4/18-oneToOnePkMapping/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/oneToOnePkMapping + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/18-oneToOnePkMapping/etc/sql/db.sql b/examples/Chapter4/18-oneToOnePkMapping/etc/sql/db.sql new file mode 100644 index 0000000..b2ebcb0 --- /dev/null +++ b/examples/Chapter4/18-oneToOnePkMapping/etc/sql/db.sql @@ -0,0 +1,6 @@ +DROP TABLE EMPLOYEE; +DROP TABLE PARKING_SPACE; + +CREATE TABLE PARKING_SPACE (ID INTEGER NOT NULL, LOT INTEGER, LOCATION VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, PRIMARY KEY (ID)); + diff --git a/examples/Chapter4/18-oneToOnePkMapping/etc/web/WEB-INF/web.xml b/examples/Chapter4/18-oneToOnePkMapping/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/18-oneToOnePkMapping/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter4/18-oneToOnePkMapping/src/model/examples/model/Employee.java b/examples/Chapter4/18-oneToOnePkMapping/src/model/examples/model/Employee.java new file mode 100644 index 0000000..c1d6162 --- /dev/null +++ b/examples/Chapter4/18-oneToOnePkMapping/src/model/examples/model/Employee.java @@ -0,0 +1,53 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToOne; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + + @OneToOne(mappedBy="employee") + private ParkingSpace parkingSpace; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public ParkingSpace getParkingSpace() { + return parkingSpace; + } + + public void setParkingSpace(ParkingSpace parkingSpace) { + this.parkingSpace = parkingSpace; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " with " + getParkingSpace(); + } +} diff --git a/examples/Chapter4/18-oneToOnePkMapping/src/model/examples/model/ParkingSpace.java b/examples/Chapter4/18-oneToOnePkMapping/src/model/examples/model/ParkingSpace.java new file mode 100644 index 0000000..809c60f --- /dev/null +++ b/examples/Chapter4/18-oneToOnePkMapping/src/model/examples/model/ParkingSpace.java @@ -0,0 +1,56 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToOne; +import javax.persistence.PrimaryKeyJoinColumn; +import javax.persistence.Table; + +@Entity +@Table(name="PARKING_SPACE") +public class ParkingSpace { + @Id + private int id; + private int lot; + private String location; + @OneToOne + @PrimaryKeyJoinColumn + private Employee employee; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getLot() { + return lot; + } + + public void setLot(int lot) { + this.lot = lot; + } + + public String getLocation() { + return location; + } + + public void setLocation(String deptName) { + this.location = deptName; + } + + public Employee getEmployee() { + return employee; + } + + public void setEmployee(Employee employee) { + this.employee = employee; + } + + public String toString() { + return "ParkingSpace id: " + getId() + " lot: " + getLot() + + ", location: " + getLocation(); + } +} diff --git a/examples/Chapter4/18-oneToOnePkMapping/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/18-oneToOnePkMapping/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..1707ef2 --- /dev/null +++ b/examples/Chapter4/18-oneToOnePkMapping/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(int id, String name, long salary); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter4/18-oneToOnePkMapping/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/18-oneToOnePkMapping/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..0815bdf --- /dev/null +++ b/examples/Chapter4/18-oneToOnePkMapping/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,31 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(int id, String name, long salary) { + Employee emp = new Employee(); + emp.setId(id); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/18-oneToOnePkMapping/src/model/examples/stateless/ParkingSpaceService.java b/examples/Chapter4/18-oneToOnePkMapping/src/model/examples/stateless/ParkingSpaceService.java new file mode 100644 index 0000000..50d6a76 --- /dev/null +++ b/examples/Chapter4/18-oneToOnePkMapping/src/model/examples/stateless/ParkingSpaceService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; +import examples.model.ParkingSpace; + +public interface ParkingSpaceService { + public ParkingSpace createParkingSpace(Employee emp, int lot, String location); + public Collection findAllParkingSpaces(); +} diff --git a/examples/Chapter4/18-oneToOnePkMapping/src/model/examples/stateless/ParkingSpaceServiceBean.java b/examples/Chapter4/18-oneToOnePkMapping/src/model/examples/stateless/ParkingSpaceServiceBean.java new file mode 100644 index 0000000..f9a9702 --- /dev/null +++ b/examples/Chapter4/18-oneToOnePkMapping/src/model/examples/stateless/ParkingSpaceServiceBean.java @@ -0,0 +1,35 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Employee; +import examples.model.ParkingSpace; + +@Stateless +public class ParkingSpaceServiceBean implements ParkingSpaceService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public ParkingSpace createParkingSpace(Employee emp, int lot, String location) { + ParkingSpace space = new ParkingSpace(); + space.setId(emp.getId()); + space.setLot(lot); + space.setLocation(location); + + emp.setParkingSpace(space); + space.setEmployee(emp); + em.persist(space); + + return space; + } + + public Collection findAllParkingSpaces() { + Query query = em.createQuery("SELECT p FROM ParkingSpace p"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/18-oneToOnePkMapping/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/18-oneToOnePkMapping/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..3efd561 --- /dev/null +++ b/examples/Chapter4/18-oneToOnePkMapping/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,138 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.annotation.Resource; +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.transaction.UserTransaction; + +import examples.model.Employee; +import examples.model.ParkingSpace; +import examples.stateless.EmployeeService; +import examples.stateless.ParkingSpaceService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 4: One-to-One Primary Key Mapping Example"; + + private final String DESCRIPTION = + "This example demonstates how to use a one-to-one pk mapping for entities.
" + + "It allows you to create/find employees & parking spaces and associates them."; + + + @EJB EmployeeService empService; + @EJB ParkingSpaceService pSpaceService; + @Resource UserTransaction tx; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("CreateEmpAndParkingSpace")) { + // make sure both operations happen in one tx + try { + tx.begin(); + Employee emp = empService.createEmployee( + parseInt(request.getParameter("id")), + request.getParameter("empName"), + parseLong(request.getParameter("salary"))); + + pSpaceService.createParkingSpace(emp, + parseInt(request.getParameter("lot")), + request.getParameter("location")); + tx.commit(); + out.println("Created " + emp); + } catch (Exception e) { + throw new ServletException(e); + } + } else if (action.equals("FindAll")) { + Collection emps = empService.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + + out.println("
"); + Collection pSpaces = pSpaceService.findAllParkingSpaces(); + if (pSpaces.isEmpty()) { + out.println("No ParkingSpaces found "); + } else { + out.println("Found ParkingSpaces:
"); + for (ParkingSpace pSpace : pSpaces) { + out.println(pSpace + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Department + out.println("

Create an Employee and ParkingSpace

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
Employee Name:(String)
Employee Salary:(long)
ParkingSpace lot#:(int)
location:(String)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees & Parking Spaces

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter4/18-oneToOnePkMapping/undeploy.bat b/examples/Chapter4/18-oneToOnePkMapping/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter4/18-oneToOnePkMapping/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter4/19-oneToManyBidirectional/build.xml b/examples/Chapter4/19-oneToManyBidirectional/build.xml new file mode 100644 index 0000000..2dc6fea --- /dev/null +++ b/examples/Chapter4/19-oneToManyBidirectional/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/19-oneToManyBidirectional/deploy.bat b/examples/Chapter4/19-oneToManyBidirectional/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter4/19-oneToManyBidirectional/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter4/19-oneToManyBidirectional/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/19-oneToManyBidirectional/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..0534c8a --- /dev/null +++ b/examples/Chapter4/19-oneToManyBidirectional/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/oneToManyBidirectional + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/19-oneToManyBidirectional/etc/sql/db.sql b/examples/Chapter4/19-oneToManyBidirectional/etc/sql/db.sql new file mode 100644 index 0000000..5b2112b --- /dev/null +++ b/examples/Chapter4/19-oneToManyBidirectional/etc/sql/db.sql @@ -0,0 +1,10 @@ +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + NAME VARCHAR(255), SALARY BIGINT, + DEPARTMENT_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID)); + diff --git a/examples/Chapter4/19-oneToManyBidirectional/etc/web/WEB-INF/web.xml b/examples/Chapter4/19-oneToManyBidirectional/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/19-oneToManyBidirectional/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter4/19-oneToManyBidirectional/src/model/examples/model/Department.java b/examples/Chapter4/19-oneToManyBidirectional/src/model/examples/model/Department.java new file mode 100644 index 0000000..78d7b9b --- /dev/null +++ b/examples/Chapter4/19-oneToManyBidirectional/src/model/examples/model/Department.java @@ -0,0 +1,58 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + @OneToMany(mappedBy="department") + private Collection employees; + + public Department() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String deptName) { + this.name = deptName; + } + + public void addEmployee(Employee employee) { + if (!getEmployees().contains(employee)) { + getEmployees().add(employee); + if (employee.getDepartment() != null) { + employee.getDepartment().getEmployees().remove(employee); + } + employee.setDepartment(this); + } + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Department id: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter4/19-oneToManyBidirectional/src/model/examples/model/Employee.java b/examples/Chapter4/19-oneToManyBidirectional/src/model/examples/model/Employee.java new file mode 100644 index 0000000..e161138 --- /dev/null +++ b/examples/Chapter4/19-oneToManyBidirectional/src/model/examples/model/Employee.java @@ -0,0 +1,55 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@Entity +public class Employee { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + private long salary; + + @ManyToOne + private Department department; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " with " + getDepartment(); + } +} diff --git a/examples/Chapter4/19-oneToManyBidirectional/src/model/examples/stateless/DepartmentService.java b/examples/Chapter4/19-oneToManyBidirectional/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..7003e8d --- /dev/null +++ b/examples/Chapter4/19-oneToManyBidirectional/src/model/examples/stateless/DepartmentService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Department; + +public interface DepartmentService { + public Department createDepartment(String name); + public Collection findAllDepartments(); +} diff --git a/examples/Chapter4/19-oneToManyBidirectional/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter4/19-oneToManyBidirectional/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..7d47cb1 --- /dev/null +++ b/examples/Chapter4/19-oneToManyBidirectional/src/model/examples/stateless/DepartmentServiceBean.java @@ -0,0 +1,29 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; + +@Stateless +public class DepartmentServiceBean implements DepartmentService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Department createDepartment(String name) { + Department dept = new Department(); + dept.setName(name); + em.persist(dept); + + return dept; + } + + public Collection findAllDepartments() { + Query query = em.createQuery("SELECT d FROM Department d"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/19-oneToManyBidirectional/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/19-oneToManyBidirectional/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..84116f6 --- /dev/null +++ b/examples/Chapter4/19-oneToManyBidirectional/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(String name, long salary); + public Employee setEmployeeDepartment(int empId, int deptId); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter4/19-oneToManyBidirectional/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/19-oneToManyBidirectional/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..3a28921 --- /dev/null +++ b/examples/Chapter4/19-oneToManyBidirectional/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,38 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String name, long salary) { + Employee emp = new Employee(); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + + return emp; + } + + public Employee setEmployeeDepartment(int empId, int deptId) { + Employee emp = em.find(Employee.class, empId); + Department dept = em.find(Department.class, deptId); + dept.addEmployee(emp); + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/19-oneToManyBidirectional/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/19-oneToManyBidirectional/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..ade70d6 --- /dev/null +++ b/examples/Chapter4/19-oneToManyBidirectional/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,146 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Department; +import examples.model.Employee; +import examples.stateless.DepartmentService; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 4: One-to-Many Bidirectional Example"; + + private final String DESCRIPTION = + "This example demonstates how to specify one-to-many bidirectional relationships for entities.
" + + "It allows you to create/find employees & departments and associate them."; + + + @EJB EmployeeService empService; + @EJB DepartmentService deptService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("CreateEmp")) { + Employee emp = empService.createEmployee( + request.getParameter("empName"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("CreateDept")) { + Department dept = deptService.createDepartment( + request.getParameter("deptName")); + out.println("Created " + dept); + } else if (action.equals("SetEmployeeDept")) { + Employee emp = empService.setEmployeeDepartment( + parseInt(request.getParameter("empId")), + parseInt(request.getParameter("deptId"))); + out.println("Updated " + emp + "
"); + out.println(emp.getDepartment() + " with Employees:
"); + out.println(emp.getDepartment().getEmployees()); + } else if (action.equals("FindAll")) { + Collection emps = empService.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + + out.println("
"); + Collection depts = deptService.findAllDepartments(); + if (depts.isEmpty()) { + out.println("No Departments found "); + } else { + out.println("Found Departments:
"); + for (Department dept : depts) { + out.println(dept + " with " + dept.getEmployees().size() + " employees
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Department + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
Employee Salary:(long)
"); + + out.println("
"); + out.println("

Create a Department

"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Dept Name:(String)
"); + + out.println("
"); + out.println("

Set an Employee's Department

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Emp Id:(int)
Dept Id:(int)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees & Departments

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter4/19-oneToManyBidirectional/undeploy.bat b/examples/Chapter4/19-oneToManyBidirectional/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter4/19-oneToManyBidirectional/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter4/20-oneToManyTargetEntity/build.xml b/examples/Chapter4/20-oneToManyTargetEntity/build.xml new file mode 100644 index 0000000..628f6d8 --- /dev/null +++ b/examples/Chapter4/20-oneToManyTargetEntity/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/20-oneToManyTargetEntity/deploy.bat b/examples/Chapter4/20-oneToManyTargetEntity/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter4/20-oneToManyTargetEntity/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter4/20-oneToManyTargetEntity/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/20-oneToManyTargetEntity/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..1558fa6 --- /dev/null +++ b/examples/Chapter4/20-oneToManyTargetEntity/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/oneToManyTargetEntity + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/20-oneToManyTargetEntity/etc/sql/db.sql b/examples/Chapter4/20-oneToManyTargetEntity/etc/sql/db.sql new file mode 100644 index 0000000..5b2112b --- /dev/null +++ b/examples/Chapter4/20-oneToManyTargetEntity/etc/sql/db.sql @@ -0,0 +1,10 @@ +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + NAME VARCHAR(255), SALARY BIGINT, + DEPARTMENT_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID)); + diff --git a/examples/Chapter4/20-oneToManyTargetEntity/etc/web/WEB-INF/web.xml b/examples/Chapter4/20-oneToManyTargetEntity/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/20-oneToManyTargetEntity/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter4/20-oneToManyTargetEntity/src/model/examples/model/Department.java b/examples/Chapter4/20-oneToManyTargetEntity/src/model/examples/model/Department.java new file mode 100644 index 0000000..6b96a87 --- /dev/null +++ b/examples/Chapter4/20-oneToManyTargetEntity/src/model/examples/model/Department.java @@ -0,0 +1,58 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + @OneToMany(targetEntity=Employee.class, mappedBy="department") + private Collection employees; + + public Department() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String deptName) { + this.name = deptName; + } + + public void addEmployee(Employee employee) { + if (!getEmployees().contains(employee)) { + getEmployees().add(employee); + if (employee.getDepartment() != null) { + employee.getDepartment().getEmployees().remove(employee); + } + employee.setDepartment(this); + } + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Department id: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter4/20-oneToManyTargetEntity/src/model/examples/model/Employee.java b/examples/Chapter4/20-oneToManyTargetEntity/src/model/examples/model/Employee.java new file mode 100644 index 0000000..e161138 --- /dev/null +++ b/examples/Chapter4/20-oneToManyTargetEntity/src/model/examples/model/Employee.java @@ -0,0 +1,55 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@Entity +public class Employee { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + private long salary; + + @ManyToOne + private Department department; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " with " + getDepartment(); + } +} diff --git a/examples/Chapter4/20-oneToManyTargetEntity/src/model/examples/stateless/DepartmentService.java b/examples/Chapter4/20-oneToManyTargetEntity/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..7003e8d --- /dev/null +++ b/examples/Chapter4/20-oneToManyTargetEntity/src/model/examples/stateless/DepartmentService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Department; + +public interface DepartmentService { + public Department createDepartment(String name); + public Collection findAllDepartments(); +} diff --git a/examples/Chapter4/20-oneToManyTargetEntity/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter4/20-oneToManyTargetEntity/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..7d47cb1 --- /dev/null +++ b/examples/Chapter4/20-oneToManyTargetEntity/src/model/examples/stateless/DepartmentServiceBean.java @@ -0,0 +1,29 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; + +@Stateless +public class DepartmentServiceBean implements DepartmentService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Department createDepartment(String name) { + Department dept = new Department(); + dept.setName(name); + em.persist(dept); + + return dept; + } + + public Collection findAllDepartments() { + Query query = em.createQuery("SELECT d FROM Department d"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/20-oneToManyTargetEntity/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/20-oneToManyTargetEntity/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..84116f6 --- /dev/null +++ b/examples/Chapter4/20-oneToManyTargetEntity/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(String name, long salary); + public Employee setEmployeeDepartment(int empId, int deptId); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter4/20-oneToManyTargetEntity/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/20-oneToManyTargetEntity/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..3a28921 --- /dev/null +++ b/examples/Chapter4/20-oneToManyTargetEntity/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,38 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String name, long salary) { + Employee emp = new Employee(); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + + return emp; + } + + public Employee setEmployeeDepartment(int empId, int deptId) { + Employee emp = em.find(Employee.class, empId); + Department dept = em.find(Department.class, deptId); + dept.addEmployee(emp); + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/20-oneToManyTargetEntity/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/20-oneToManyTargetEntity/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..2a967af --- /dev/null +++ b/examples/Chapter4/20-oneToManyTargetEntity/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,146 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Department; +import examples.model.Employee; +import examples.stateless.DepartmentService; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 4: One-to-Many Target Entity Example"; + + private final String DESCRIPTION = + "This example demonstates how to specify a target entity for one-to-many relationships for entities.
" + + "It allows you to create/find employees & departments and associate them."; + + + @EJB EmployeeService empService; + @EJB DepartmentService deptService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("CreateEmp")) { + Employee emp = empService.createEmployee( + request.getParameter("empName"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("CreateDept")) { + Department dept = deptService.createDepartment( + request.getParameter("deptName")); + out.println("Created " + dept); + } else if (action.equals("SetEmployeeDept")) { + Employee emp = empService.setEmployeeDepartment( + parseInt(request.getParameter("empId")), + parseInt(request.getParameter("deptId"))); + out.println("Updated " + emp + "
"); + out.println(emp.getDepartment() + " with Employees:
"); + out.println(emp.getDepartment().getEmployees()); + } else if (action.equals("FindAll")) { + Collection emps = empService.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + + out.println("
"); + Collection depts = deptService.findAllDepartments(); + if (depts.isEmpty()) { + out.println("No Departments found "); + } else { + out.println("Found Departments:
"); + for (Department dept : depts) { + out.println(dept + " with " + dept.getEmployees().size() + " employees
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Department + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
Employee Salary:(long)
"); + + out.println("
"); + out.println("

Create a Department

"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Dept Name:(String)
"); + + out.println("
"); + out.println("

Set an Employee's Department

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Emp Id:(int)
Dept Id:(int)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees & Departments

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter4/20-oneToManyTargetEntity/undeploy.bat b/examples/Chapter4/20-oneToManyTargetEntity/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter4/20-oneToManyTargetEntity/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter4/21-manyToManyBidirectional/build.xml b/examples/Chapter4/21-manyToManyBidirectional/build.xml new file mode 100644 index 0000000..91dee6c --- /dev/null +++ b/examples/Chapter4/21-manyToManyBidirectional/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/21-manyToManyBidirectional/deploy.bat b/examples/Chapter4/21-manyToManyBidirectional/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter4/21-manyToManyBidirectional/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter4/21-manyToManyBidirectional/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/21-manyToManyBidirectional/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..7105d75 --- /dev/null +++ b/examples/Chapter4/21-manyToManyBidirectional/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/manyToManyBidirectional + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/21-manyToManyBidirectional/etc/sql/db.sql b/examples/Chapter4/21-manyToManyBidirectional/etc/sql/db.sql new file mode 100644 index 0000000..a762ecb --- /dev/null +++ b/examples/Chapter4/21-manyToManyBidirectional/etc/sql/db.sql @@ -0,0 +1,13 @@ +DROP TABLE EMPLOYEE_PROJECT; +DROP TABLE EMPLOYEE; +DROP TABLE PROJECT; + +CREATE TABLE PROJECT (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + NAME VARCHAR(255), SALARY BIGINT, PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE_PROJECT (PROJECTS_ID INTEGER NOT NULL, EMPLOYEES_ID INTEGER NOT NULL, + CONSTRAINT PROJECTS_FK FOREIGN KEY (PROJECTS_ID) REFERENCES PROJECT (ID), + CONSTRAINT EMPLOYEES_FK FOREIGN KEY (EMPLOYEES_ID) REFERENCES EMPLOYEE (ID), + PRIMARY KEY (PROJECTS_ID, EMPLOYEES_ID)) + diff --git a/examples/Chapter4/21-manyToManyBidirectional/etc/web/WEB-INF/web.xml b/examples/Chapter4/21-manyToManyBidirectional/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/21-manyToManyBidirectional/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter4/21-manyToManyBidirectional/src/model/examples/model/Employee.java b/examples/Chapter4/21-manyToManyBidirectional/src/model/examples/model/Employee.java new file mode 100644 index 0000000..6c8f8e2 --- /dev/null +++ b/examples/Chapter4/21-manyToManyBidirectional/src/model/examples/model/Employee.java @@ -0,0 +1,67 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToMany; + +@Entity +public class Employee { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + private long salary; + + @ManyToMany + private Collection projects; + + public Employee() { + projects = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public void addProject(Project project) { + if (!getProjects().contains(project)) { + getProjects().add(project); + } + if (!project.getEmployees().contains(this)) { + project.getEmployees().add(this); + } + } + + public Collection getProjects() { + return projects; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " with " + getProjects().size() + " projects"; + } +} diff --git a/examples/Chapter4/21-manyToManyBidirectional/src/model/examples/model/Project.java b/examples/Chapter4/21-manyToManyBidirectional/src/model/examples/model/Project.java new file mode 100644 index 0000000..56635d0 --- /dev/null +++ b/examples/Chapter4/21-manyToManyBidirectional/src/model/examples/model/Project.java @@ -0,0 +1,57 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToMany; + +@Entity +public class Project { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + protected int id; + protected String name; + @ManyToMany(mappedBy="projects") + private Collection employees; + + public Project() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int projectNo) { + this.id = projectNo; + } + + public String getName() { + return name; + } + + public void setName(String projectName) { + this.name = projectName; + } + + public Collection getEmployees() { + return employees; + } + + public void addEmployee(Employee employee) { + if (!getEmployees().contains(employee)) { + getEmployees().add(employee); + } + if (!employee.getProjects().contains(this)) { + employee.getProjects().add(this); + } + } + + public String toString() { + return "Project id: " + getId() + ", name: " + getName() + + " with " + getEmployees().size() + " employees"; + } +} diff --git a/examples/Chapter4/21-manyToManyBidirectional/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/21-manyToManyBidirectional/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..0922f7a --- /dev/null +++ b/examples/Chapter4/21-manyToManyBidirectional/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(String name, long salary); + public Employee addEmployeeProject(int empId, int projId); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter4/21-manyToManyBidirectional/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/21-manyToManyBidirectional/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..a8dcc0c --- /dev/null +++ b/examples/Chapter4/21-manyToManyBidirectional/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,38 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Employee; +import examples.model.Project; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String name, long salary) { + Employee emp = new Employee(); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + + return emp; + } + + public Employee addEmployeeProject(int empId, int projId) { + Employee emp = em.find(Employee.class, empId); + Project proj = em.find(Project.class, projId); + proj.addEmployee(emp); + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/21-manyToManyBidirectional/src/model/examples/stateless/ProjectService.java b/examples/Chapter4/21-manyToManyBidirectional/src/model/examples/stateless/ProjectService.java new file mode 100644 index 0000000..5ef7dbc --- /dev/null +++ b/examples/Chapter4/21-manyToManyBidirectional/src/model/examples/stateless/ProjectService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Project; + +public interface ProjectService { + public Project createProject(String name); + public Collection findAllProjects(); +} diff --git a/examples/Chapter4/21-manyToManyBidirectional/src/model/examples/stateless/ProjectServiceBean.java b/examples/Chapter4/21-manyToManyBidirectional/src/model/examples/stateless/ProjectServiceBean.java new file mode 100644 index 0000000..40d80c4 --- /dev/null +++ b/examples/Chapter4/21-manyToManyBidirectional/src/model/examples/stateless/ProjectServiceBean.java @@ -0,0 +1,29 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Project; + +@Stateless +public class ProjectServiceBean implements ProjectService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Project createProject(String name) { + Project proj = new Project(); + proj.setName(name); + em.persist(proj); + + return proj; + } + + public Collection findAllProjects() { + Query query = em.createQuery("SELECT p FROM Project p"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/21-manyToManyBidirectional/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/21-manyToManyBidirectional/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..6c1d936 --- /dev/null +++ b/examples/Chapter4/21-manyToManyBidirectional/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,141 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.model.Project; +import examples.stateless.EmployeeService; +import examples.stateless.ProjectService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 4: Many-to-Many Bidirectional Example"; + + private final String DESCRIPTION = + "This example demonstates how to specify many-to-many bidirectional relationships for entities.
" + + "It allows you to create/find employees & projects and associate them."; + + + @EJB EmployeeService empService; + @EJB ProjectService projService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("CreateEmp")) { + Employee emp = empService.createEmployee( + request.getParameter("empName"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("CreateProject")) { + Project proj = projService.createProject( + request.getParameter("projName")); + out.println("Created " + proj); + } else if (action.equals("addEmployeeProject")) { + Employee emp = empService.addEmployeeProject( + parseInt(request.getParameter("empId")), + parseInt(request.getParameter("projId"))); + out.println("Updated " + emp + "
"); + } else if (action.equals("FindAll")) { + Collection emps = empService.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + + out.println("
"); + Collection projs = projService.findAllProjects(); + if (projs.isEmpty()) { + out.println("No Projects found "); + } else { + out.println("Found Projects:
"); + for (Project proj : projs) { + out.println(proj + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Department + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
Employee Salary:(long)
"); + out.println("
"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Project Name:(String)
"); + out.println("
"); + + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Emp Id:(int)
Project Id:(int)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees & Projects

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter4/21-manyToManyBidirectional/undeploy.bat b/examples/Chapter4/21-manyToManyBidirectional/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter4/21-manyToManyBidirectional/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter4/22-manyToManyJoinTable/build.xml b/examples/Chapter4/22-manyToManyJoinTable/build.xml new file mode 100644 index 0000000..9db59fd --- /dev/null +++ b/examples/Chapter4/22-manyToManyJoinTable/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/22-manyToManyJoinTable/deploy.bat b/examples/Chapter4/22-manyToManyJoinTable/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter4/22-manyToManyJoinTable/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter4/22-manyToManyJoinTable/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/22-manyToManyJoinTable/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..cf2efab --- /dev/null +++ b/examples/Chapter4/22-manyToManyJoinTable/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/manyToManyJoinTable + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/22-manyToManyJoinTable/etc/sql/db.sql b/examples/Chapter4/22-manyToManyJoinTable/etc/sql/db.sql new file mode 100644 index 0000000..2f536ce --- /dev/null +++ b/examples/Chapter4/22-manyToManyJoinTable/etc/sql/db.sql @@ -0,0 +1,13 @@ +DROP TABLE EMP_PROJ; +DROP TABLE EMPLOYEE; +DROP TABLE PROJECT; + +CREATE TABLE PROJECT (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + NAME VARCHAR(255), SALARY BIGINT, PRIMARY KEY (ID)); +CREATE TABLE EMP_PROJ (PROJ_ID INTEGER NOT NULL, EMP_ID INTEGER NOT NULL, + CONSTRAINT PROJ_FK FOREIGN KEY (PROJ_ID) REFERENCES PROJECT (ID), + CONSTRAINT EMP_FK FOREIGN KEY (EMP_ID) REFERENCES EMPLOYEE (ID), + PRIMARY KEY (PROJ_ID, EMP_ID)) + diff --git a/examples/Chapter4/22-manyToManyJoinTable/etc/web/WEB-INF/web.xml b/examples/Chapter4/22-manyToManyJoinTable/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/22-manyToManyJoinTable/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter4/22-manyToManyJoinTable/src/model/examples/model/Employee.java b/examples/Chapter4/22-manyToManyJoinTable/src/model/examples/model/Employee.java new file mode 100644 index 0000000..995c52f --- /dev/null +++ b/examples/Chapter4/22-manyToManyJoinTable/src/model/examples/model/Employee.java @@ -0,0 +1,73 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; + +@Entity +public class Employee { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + private long salary; + + @ManyToMany + @JoinTable(name="EMP_PROJ", + joinColumns=@JoinColumn(name="EMP_ID"), + inverseJoinColumns=@JoinColumn(name="PROJ_ID")) + private Collection projects; + + + public Employee() { + projects = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public void addProject(Project project) { + if (!getProjects().contains(project)) { + getProjects().add(project); + } + if (!project.getEmployees().contains(this)) { + project.getEmployees().add(this); + } + } + + public Collection getProjects() { + return projects; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " with " + getProjects().size() + " projects"; + } +} diff --git a/examples/Chapter4/22-manyToManyJoinTable/src/model/examples/model/Project.java b/examples/Chapter4/22-manyToManyJoinTable/src/model/examples/model/Project.java new file mode 100644 index 0000000..56635d0 --- /dev/null +++ b/examples/Chapter4/22-manyToManyJoinTable/src/model/examples/model/Project.java @@ -0,0 +1,57 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToMany; + +@Entity +public class Project { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + protected int id; + protected String name; + @ManyToMany(mappedBy="projects") + private Collection employees; + + public Project() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int projectNo) { + this.id = projectNo; + } + + public String getName() { + return name; + } + + public void setName(String projectName) { + this.name = projectName; + } + + public Collection getEmployees() { + return employees; + } + + public void addEmployee(Employee employee) { + if (!getEmployees().contains(employee)) { + getEmployees().add(employee); + } + if (!employee.getProjects().contains(this)) { + employee.getProjects().add(this); + } + } + + public String toString() { + return "Project id: " + getId() + ", name: " + getName() + + " with " + getEmployees().size() + " employees"; + } +} diff --git a/examples/Chapter4/22-manyToManyJoinTable/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/22-manyToManyJoinTable/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..0922f7a --- /dev/null +++ b/examples/Chapter4/22-manyToManyJoinTable/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(String name, long salary); + public Employee addEmployeeProject(int empId, int projId); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter4/22-manyToManyJoinTable/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/22-manyToManyJoinTable/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..a8dcc0c --- /dev/null +++ b/examples/Chapter4/22-manyToManyJoinTable/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,38 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Employee; +import examples.model.Project; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String name, long salary) { + Employee emp = new Employee(); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + + return emp; + } + + public Employee addEmployeeProject(int empId, int projId) { + Employee emp = em.find(Employee.class, empId); + Project proj = em.find(Project.class, projId); + proj.addEmployee(emp); + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/22-manyToManyJoinTable/src/model/examples/stateless/ProjectService.java b/examples/Chapter4/22-manyToManyJoinTable/src/model/examples/stateless/ProjectService.java new file mode 100644 index 0000000..5ef7dbc --- /dev/null +++ b/examples/Chapter4/22-manyToManyJoinTable/src/model/examples/stateless/ProjectService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Project; + +public interface ProjectService { + public Project createProject(String name); + public Collection findAllProjects(); +} diff --git a/examples/Chapter4/22-manyToManyJoinTable/src/model/examples/stateless/ProjectServiceBean.java b/examples/Chapter4/22-manyToManyJoinTable/src/model/examples/stateless/ProjectServiceBean.java new file mode 100644 index 0000000..40d80c4 --- /dev/null +++ b/examples/Chapter4/22-manyToManyJoinTable/src/model/examples/stateless/ProjectServiceBean.java @@ -0,0 +1,29 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Project; + +@Stateless +public class ProjectServiceBean implements ProjectService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Project createProject(String name) { + Project proj = new Project(); + proj.setName(name); + em.persist(proj); + + return proj; + } + + public Collection findAllProjects() { + Query query = em.createQuery("SELECT p FROM Project p"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/22-manyToManyJoinTable/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/22-manyToManyJoinTable/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..b6236aa --- /dev/null +++ b/examples/Chapter4/22-manyToManyJoinTable/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,141 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.model.Project; +import examples.stateless.EmployeeService; +import examples.stateless.ProjectService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 4: Many-to-Many Join Table Example"; + + private final String DESCRIPTION = + "This example demonstates how to use join tables for many-to-many relationships for entities.
" + + "It allows you to create/find employees & projects and associate them."; + + + @EJB EmployeeService empService; + @EJB ProjectService projService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("CreateEmp")) { + Employee emp = empService.createEmployee( + request.getParameter("empName"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("CreateProject")) { + Project proj = projService.createProject( + request.getParameter("projName")); + out.println("Created " + proj); + } else if (action.equals("addEmployeeProject")) { + Employee emp = empService.addEmployeeProject( + parseInt(request.getParameter("empId")), + parseInt(request.getParameter("projId"))); + out.println("Updated " + emp + "
"); + } else if (action.equals("FindAll")) { + Collection emps = empService.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + + out.println("
"); + Collection projs = projService.findAllProjects(); + if (projs.isEmpty()) { + out.println("No Projects found "); + } else { + out.println("Found Projects:
"); + for (Project proj : projs) { + out.println(proj + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Department + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
Employee Salary:(long)
"); + out.println("
"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Project Name:(String)
"); + out.println("
"); + + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Emp Id:(int)
Project Id:(int)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees & Projects

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter4/22-manyToManyJoinTable/undeploy.bat b/examples/Chapter4/22-manyToManyJoinTable/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter4/22-manyToManyJoinTable/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter4/23-oneToManyUnidirectional/build.xml b/examples/Chapter4/23-oneToManyUnidirectional/build.xml new file mode 100644 index 0000000..7516dcc --- /dev/null +++ b/examples/Chapter4/23-oneToManyUnidirectional/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/23-oneToManyUnidirectional/deploy.bat b/examples/Chapter4/23-oneToManyUnidirectional/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter4/23-oneToManyUnidirectional/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter4/23-oneToManyUnidirectional/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/23-oneToManyUnidirectional/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..f199e93 --- /dev/null +++ b/examples/Chapter4/23-oneToManyUnidirectional/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/oneToManyUnidirectional + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/23-oneToManyUnidirectional/etc/sql/db.sql b/examples/Chapter4/23-oneToManyUnidirectional/etc/sql/db.sql new file mode 100644 index 0000000..fe2e575 --- /dev/null +++ b/examples/Chapter4/23-oneToManyUnidirectional/etc/sql/db.sql @@ -0,0 +1,12 @@ +DROP TABLE EMP_PHONE; +DROP TABLE EMPLOYEE; +DROP TABLE PHONE; + +CREATE TABLE PHONE (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + TYPE VARCHAR(255), NUM VARCHAR(32), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + NAME VARCHAR(255), SALARY BIGINT, PRIMARY KEY (ID)); +CREATE TABLE EMP_PHONE (PHONE_ID INTEGER NOT NULL, EMP_ID INTEGER NOT NULL, + CONSTRAINT PHONE_FK FOREIGN KEY (PHONE_ID) REFERENCES PHONE (ID), + CONSTRAINT EMP_FK FOREIGN KEY (EMP_ID) REFERENCES EMPLOYEE (ID), + PRIMARY KEY (PHONE_ID, EMP_ID)) \ No newline at end of file diff --git a/examples/Chapter4/23-oneToManyUnidirectional/etc/web/WEB-INF/web.xml b/examples/Chapter4/23-oneToManyUnidirectional/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/23-oneToManyUnidirectional/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter4/23-oneToManyUnidirectional/src/model/examples/model/Employee.java b/examples/Chapter4/23-oneToManyUnidirectional/src/model/examples/model/Employee.java new file mode 100644 index 0000000..30a7238 --- /dev/null +++ b/examples/Chapter4/23-oneToManyUnidirectional/src/model/examples/model/Employee.java @@ -0,0 +1,69 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.OneToMany; + +@Entity +public class Employee { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + private long salary; + + @OneToMany + @JoinTable(name="EMP_PHONE", + joinColumns=@JoinColumn(name="EMP_ID"), + inverseJoinColumns=@JoinColumn(name="PHONE_ID")) + private Collection phones; + + public Employee() { + phones = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public void addPhone(Phone phone) { + if (!getPhones().contains(phone)) { + getPhones().add(phone); + } + } + + public Collection getPhones() { + return phones; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " with " + getPhones().size() + " phones"; + } +} diff --git a/examples/Chapter4/23-oneToManyUnidirectional/src/model/examples/model/Phone.java b/examples/Chapter4/23-oneToManyUnidirectional/src/model/examples/model/Phone.java new file mode 100644 index 0000000..343cd07 --- /dev/null +++ b/examples/Chapter4/23-oneToManyUnidirectional/src/model/examples/model/Phone.java @@ -0,0 +1,46 @@ +package examples.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Phone { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + @Column(name="NUM") + private String number; + private String type; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getNumber() { + return number; + } + + public void setNumber(String phoneNo) { + this.number = phoneNo; + } + + public String getType() { + return type; + } + + public void setType(String phoneType) { + this.type = phoneType; + } + + public String toString() { + return "Phone id: " + getId() + + ", no: " + getNumber() + + ", type: " + getType(); + } +} diff --git a/examples/Chapter4/23-oneToManyUnidirectional/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/23-oneToManyUnidirectional/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..ee66ad9 --- /dev/null +++ b/examples/Chapter4/23-oneToManyUnidirectional/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(String name, long salary); + public Employee addEmployeePhone(int empId, int phoneId); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter4/23-oneToManyUnidirectional/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/23-oneToManyUnidirectional/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..c803d82 --- /dev/null +++ b/examples/Chapter4/23-oneToManyUnidirectional/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,38 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Phone; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String name, long salary) { + Employee emp = new Employee(); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + + return emp; + } + + public Employee addEmployeePhone(int empId, int phoneId) { + Employee emp = em.find(Employee.class, empId); + Phone phone = em.find(Phone.class, phoneId); + emp.addPhone(phone); + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/23-oneToManyUnidirectional/src/model/examples/stateless/PhoneService.java b/examples/Chapter4/23-oneToManyUnidirectional/src/model/examples/stateless/PhoneService.java new file mode 100644 index 0000000..447675b --- /dev/null +++ b/examples/Chapter4/23-oneToManyUnidirectional/src/model/examples/stateless/PhoneService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Phone; + +public interface PhoneService { + public Phone createPhone(String num, String type); + public Collection findAllPhones(); +} diff --git a/examples/Chapter4/23-oneToManyUnidirectional/src/model/examples/stateless/PhoneServiceBean.java b/examples/Chapter4/23-oneToManyUnidirectional/src/model/examples/stateless/PhoneServiceBean.java new file mode 100644 index 0000000..e12ef2f --- /dev/null +++ b/examples/Chapter4/23-oneToManyUnidirectional/src/model/examples/stateless/PhoneServiceBean.java @@ -0,0 +1,30 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Phone; + +@Stateless +public class PhoneServiceBean implements PhoneService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Phone createPhone(String num, String type) { + Phone phone = new Phone(); + phone.setNumber(num); + phone.setType(type); + em.persist(phone); + + return phone; + } + + public Collection findAllPhones() { + Query query = em.createQuery("SELECT p FROM Phone p"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/23-oneToManyUnidirectional/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/23-oneToManyUnidirectional/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..eaf0fe6 --- /dev/null +++ b/examples/Chapter4/23-oneToManyUnidirectional/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,145 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.model.Phone; +import examples.stateless.EmployeeService; +import examples.stateless.PhoneService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 4: One-to-Many Unidirectional Example"; + + private final String DESCRIPTION = + "This example demonstates how to specify one-to-many unidirectional relationships for entities.
" + + "It allows you to create/find employees & phones and associate them."; + + + @EJB EmployeeService empService; + @EJB PhoneService phoneService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("CreateEmp")) { + Employee emp = empService.createEmployee( + request.getParameter("empName"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("CreatePhone")) { + Phone phone = phoneService.createPhone( + request.getParameter("phoneNum"), + request.getParameter("phoneType")); + out.println("Created " + phone); + } else if (action.equals("addEmpPhone")) { + Employee emp = empService.addEmployeePhone( + parseInt(request.getParameter("empId")), + parseInt(request.getParameter("phoneId"))); + out.println("Updated " + emp + "
"); + } else if (action.equals("FindAll")) { + Collection emps = empService.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + + out.println("
"); + Collection phones = phoneService.findAllPhones(); + if (phones.isEmpty()) { + out.println("No Phones found "); + } else { + out.println("Found Phones:
"); + for (Phone phone : phones) { + out.println(phone + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
Employee Salary:(long)
"); + + out.println("
"); + out.println("

Create a Phone

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Phone No:(String)
Phone Type:(String)
"); + + out.println("
"); + out.println("

Add a Phone to an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Emp Id:(int)
Phone Id:(int)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees & Phones

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter4/23-oneToManyUnidirectional/undeploy.bat b/examples/Chapter4/23-oneToManyUnidirectional/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter4/23-oneToManyUnidirectional/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter4/24-oneToOneLazy/build.xml b/examples/Chapter4/24-oneToOneLazy/build.xml new file mode 100644 index 0000000..cfb17ff --- /dev/null +++ b/examples/Chapter4/24-oneToOneLazy/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/24-oneToOneLazy/deploy.bat b/examples/Chapter4/24-oneToOneLazy/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter4/24-oneToOneLazy/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter4/24-oneToOneLazy/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/24-oneToOneLazy/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..73b430b --- /dev/null +++ b/examples/Chapter4/24-oneToOneLazy/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/oneToOneLazy + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/24-oneToOneLazy/etc/sql/db.sql b/examples/Chapter4/24-oneToOneLazy/etc/sql/db.sql new file mode 100644 index 0000000..90a6791 --- /dev/null +++ b/examples/Chapter4/24-oneToOneLazy/etc/sql/db.sql @@ -0,0 +1,15 @@ +DROP TABLE EMPLOYEE; +DROP TABLE PARKING_SPACE; + +CREATE TABLE PARKING_SPACE (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + LOT INTEGER, LOCATION VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + NAME VARCHAR(255), SALARY BIGINT, + PARKINGSPACE_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT PSPACE_FK FOREIGN KEY (PARKINGSPACE_ID) REFERENCES PARKING_SPACE(ID)); + +INSERT INTO PARKING_SPACE (LOT, LOCATION) VALUES (1, 'East Lot'); +INSERT INTO PARKING_SPACE (LOT , LOCATION) VALUES (2, 'West Lot'); + +INSERT INTO EMPLOYEE (NAME, SALARY, PARKINGSPACE_ID) VALUES ('Joan', 59000, 1); +INSERT INTO EMPLOYEE (NAME, SALARY, PARKINGSPACE_ID) VALUES ('John', 59000, 1); diff --git a/examples/Chapter4/24-oneToOneLazy/etc/web/WEB-INF/web.xml b/examples/Chapter4/24-oneToOneLazy/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/24-oneToOneLazy/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter4/24-oneToOneLazy/src/model/examples/model/Employee.java b/examples/Chapter4/24-oneToOneLazy/src/model/examples/model/Employee.java new file mode 100644 index 0000000..cff90fe --- /dev/null +++ b/examples/Chapter4/24-oneToOneLazy/src/model/examples/model/Employee.java @@ -0,0 +1,57 @@ +package examples.model; + +import static javax.persistence.FetchType.LAZY; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToOne; + +@Entity +public class Employee { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + private long salary; + + @OneToOne(fetch=LAZY) + private ParkingSpace parkingSpace; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public ParkingSpace getParkingSpace() { + return parkingSpace; + } + + public void setParkingSpace(ParkingSpace parkingSpace) { + this.parkingSpace = parkingSpace; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " with " + getParkingSpace(); + } +} diff --git a/examples/Chapter4/24-oneToOneLazy/src/model/examples/model/ParkingSpace.java b/examples/Chapter4/24-oneToOneLazy/src/model/examples/model/ParkingSpace.java new file mode 100644 index 0000000..d9fff74 --- /dev/null +++ b/examples/Chapter4/24-oneToOneLazy/src/model/examples/model/ParkingSpace.java @@ -0,0 +1,46 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name="PARKING_SPACE") +public class ParkingSpace { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private int lot; + private String location; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getLot() { + return lot; + } + + public void setLot(int lot) { + this.lot = lot; + } + + public String getLocation() { + return location; + } + + public void setLocation(String deptName) { + this.location = deptName; + } + + public String toString() { + return "ParkingSpace id: " + getId() + " lot: " + getLot() + + ", location: " + getLocation(); + } + +} diff --git a/examples/Chapter4/24-oneToOneLazy/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/24-oneToOneLazy/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..4768f09 --- /dev/null +++ b/examples/Chapter4/24-oneToOneLazy/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(String name, long salary); + public Employee setEmployeeParkingSpace(int empId, int spaceId); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter4/24-oneToOneLazy/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/24-oneToOneLazy/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..678d876 --- /dev/null +++ b/examples/Chapter4/24-oneToOneLazy/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,38 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.ParkingSpace; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String name, long salary) { + Employee emp = new Employee(); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + + return emp; + } + + public Employee setEmployeeParkingSpace(int empId, int spaceId) { + Employee emp = em.find(Employee.class, empId); + ParkingSpace pSpace = em.find(ParkingSpace.class, spaceId); + emp.setParkingSpace(pSpace); + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/24-oneToOneLazy/src/model/examples/stateless/ParkingSpaceService.java b/examples/Chapter4/24-oneToOneLazy/src/model/examples/stateless/ParkingSpaceService.java new file mode 100644 index 0000000..cb201cf --- /dev/null +++ b/examples/Chapter4/24-oneToOneLazy/src/model/examples/stateless/ParkingSpaceService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.ParkingSpace; + +public interface ParkingSpaceService { + public ParkingSpace createParkingSpace(int lot, String location); + public Collection findAllParkingSpaces(); +} diff --git a/examples/Chapter4/24-oneToOneLazy/src/model/examples/stateless/ParkingSpaceServiceBean.java b/examples/Chapter4/24-oneToOneLazy/src/model/examples/stateless/ParkingSpaceServiceBean.java new file mode 100644 index 0000000..4c1bf24 --- /dev/null +++ b/examples/Chapter4/24-oneToOneLazy/src/model/examples/stateless/ParkingSpaceServiceBean.java @@ -0,0 +1,30 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.ParkingSpace; + +@Stateless +public class ParkingSpaceServiceBean implements ParkingSpaceService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public ParkingSpace createParkingSpace(int lot, String location) { + ParkingSpace space = new ParkingSpace(); + space.setLot(lot); + space.setLocation(location); + em.persist(space); + + return space; + } + + public Collection findAllParkingSpaces() { + Query query = em.createQuery("SELECT p FROM ParkingSpace p"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/24-oneToOneLazy/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/24-oneToOneLazy/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..728ce4b --- /dev/null +++ b/examples/Chapter4/24-oneToOneLazy/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,143 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.ParkingSpace; +import examples.model.Employee; +import examples.stateless.ParkingSpaceService; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 4: One-to-One Lazy Fetching Example"; + + private final String DESCRIPTION = + "This example demonstates how to specify lazy fetching for one-to-one relationships for entities.
" + + "It allows you to create/find employees & parking spaces and associate them."; + + + @EJB EmployeeService empService; + @EJB ParkingSpaceService pSpaceService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("CreateEmp")) { + Employee emp = empService.createEmployee( + request.getParameter("empName"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("CreateParkingSpace")) { + ParkingSpace pSpace = pSpaceService.createParkingSpace( + parseInt(request.getParameter("lot")), + request.getParameter("location")); + out.println("Created " + pSpace); + } else if (action.equals("SetEmployeeParkingSpace")) { + Employee emp = empService.setEmployeeParkingSpace( + parseInt(request.getParameter("empId")), + parseInt(request.getParameter("pSpaceId"))); + out.println("Updated " + emp); + } else if (action.equals("FindAll")) { + Collection emps = empService.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + + out.println("
"); + Collection pSpaces = pSpaceService.findAllParkingSpaces(); + if (pSpaces.isEmpty()) { + out.println("No ParkingSpaces found "); + } else { + out.println("Found ParkingSpaces:
"); + for (ParkingSpace pSpace : pSpaces) { + out.println(pSpace + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Department + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
Employee Salary:(long)
"); + out.println("
"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
ParkingSpace lot#:(int)
location:(String)
"); + out.println("
"); + + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Emp Id:(int)
Parking Space Id:(int)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees & Parking Spaces

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter4/24-oneToOneLazy/undeploy.bat b/examples/Chapter4/24-oneToOneLazy/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter4/24-oneToOneLazy/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter4/25-embeddedObjects/build.xml b/examples/Chapter4/25-embeddedObjects/build.xml new file mode 100644 index 0000000..49e7552 --- /dev/null +++ b/examples/Chapter4/25-embeddedObjects/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/25-embeddedObjects/deploy.bat b/examples/Chapter4/25-embeddedObjects/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter4/25-embeddedObjects/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter4/25-embeddedObjects/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/25-embeddedObjects/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..736e924 --- /dev/null +++ b/examples/Chapter4/25-embeddedObjects/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/embeddedObjects + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/25-embeddedObjects/etc/sql/db.sql b/examples/Chapter4/25-embeddedObjects/etc/sql/db.sql new file mode 100644 index 0000000..4a75195 --- /dev/null +++ b/examples/Chapter4/25-embeddedObjects/etc/sql/db.sql @@ -0,0 +1,2 @@ +DROP TABLE EMPLOYEE; +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, STREET VARCHAR(255), CITY VARCHAR(255), STATE VARCHAR(255), ZIP_CODE VARCHAR(255), PRIMARY KEY (ID)); diff --git a/examples/Chapter4/25-embeddedObjects/etc/web/WEB-INF/web.xml b/examples/Chapter4/25-embeddedObjects/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter4/25-embeddedObjects/etc/web/WEB-INF/web.xml @@ -0,0 +1,16 @@ + + + + EmployeeServiceServlet + examples.servlet.EmployeeServiceServlet + + + + EmployeeServiceServlet + /EmployeeServiceServlet + + + \ No newline at end of file diff --git a/examples/Chapter4/25-embeddedObjects/src/model/examples/model/Address.java b/examples/Chapter4/25-embeddedObjects/src/model/examples/model/Address.java new file mode 100644 index 0000000..d569a20 --- /dev/null +++ b/examples/Chapter4/25-embeddedObjects/src/model/examples/model/Address.java @@ -0,0 +1,54 @@ +package examples.model; + +import javax.persistence.Access; +import javax.persistence.AccessType; +import javax.persistence.Column; +import javax.persistence.Embeddable; + +@Embeddable @Access(AccessType.FIELD) +public class Address { + private String street; + private String city; + private String state; + @Column(name="ZIP_CODE") + private String zip; + + public String getStreet() { + return street; + } + + public void setStreet(String address) { + this.street = address; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getZip() { + return zip; + } + + public void setZip(String zip) { + this.zip = zip; + } + public String toString() { + return "Address street: " + getStreet() + + ", city: " + getCity() + + ", state: " + getState() + + ", zip: " + getZip(); + } + +} diff --git a/examples/Chapter4/25-embeddedObjects/src/model/examples/model/Employee.java b/examples/Chapter4/25-embeddedObjects/src/model/examples/model/Employee.java new file mode 100644 index 0000000..ea02307 --- /dev/null +++ b/examples/Chapter4/25-embeddedObjects/src/model/examples/model/Employee.java @@ -0,0 +1,54 @@ +package examples.model; + +import javax.persistence.Embedded; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Employee { + @Id private int id; + private String name; + private long salary; + + @Embedded + private Address address; + + public Employee() {} + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " salary: " + getSalary() + " address: " + getAddress(); + } +} diff --git a/examples/Chapter4/25-embeddedObjects/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/25-embeddedObjects/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..a63a3a2 --- /dev/null +++ b/examples/Chapter4/25-embeddedObjects/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployeeAndAddress(int id, String name, long salary, + String street, String city, String state, String zip); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter4/25-embeddedObjects/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/25-embeddedObjects/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..b85a779 --- /dev/null +++ b/examples/Chapter4/25-embeddedObjects/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,41 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Address; +import examples.model.Employee; + + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployeeAndAddress(int id, String name, long salary, + String street, String city, String state, String zip) { + Employee emp = new Employee(); + emp.setId(id); + emp.setName(name); + emp.setSalary(salary); + Address addr = new Address(); + addr.setStreet(street); + addr.setCity(city); + addr.setState(state); + addr.setZip(zip); + emp.setAddress(addr); + + em.persist(emp); + + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/25-embeddedObjects/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter4/25-embeddedObjects/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..7d8c4bc --- /dev/null +++ b/examples/Chapter4/25-embeddedObjects/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,102 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.stateless.EmployeeService; + +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 4: Using Embedded Objects Example"; + + private final String DESCRIPTION = + "This example demonstrates the basics of using embedded objects."; + + @EJB EmployeeService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("Create")) { + service.createEmployeeAndAddress( + parseInt(request.getParameter("empId")), + request.getParameter("name"), + parseLong(request.getParameter("salary")), + request.getParameter("street"), + request.getParameter("city"), + request.getParameter("state"), + request.getParameter("zip")); + } + + out.println("Employees and Addresses:
"); + for (Employee emp : service.findAllEmployees()) { + out.print(emp + "
"); + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Address + out.println("

Create an Employee and Address

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("" + + ""); + out.println("
Employee Id:(int)
Employee Name:(String)
Employee Salary:(long)
Address Street:(String)
Address City:(String)
Address State:(String)
Address Zip:(String)
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter4/25-embeddedObjects/undeploy.bat b/examples/Chapter4/25-embeddedObjects/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter4/25-embeddedObjects/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter4/26-sharingEmbeddedObjects/build.xml b/examples/Chapter4/26-sharingEmbeddedObjects/build.xml new file mode 100644 index 0000000..f5770bd --- /dev/null +++ b/examples/Chapter4/26-sharingEmbeddedObjects/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/26-sharingEmbeddedObjects/deploy.bat b/examples/Chapter4/26-sharingEmbeddedObjects/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter4/26-sharingEmbeddedObjects/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter4/26-sharingEmbeddedObjects/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/26-sharingEmbeddedObjects/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..946fc42 --- /dev/null +++ b/examples/Chapter4/26-sharingEmbeddedObjects/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/sharingEmbeddedObjects + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/26-sharingEmbeddedObjects/etc/sql/db.sql b/examples/Chapter4/26-sharingEmbeddedObjects/etc/sql/db.sql new file mode 100644 index 0000000..7838e81 --- /dev/null +++ b/examples/Chapter4/26-sharingEmbeddedObjects/etc/sql/db.sql @@ -0,0 +1,4 @@ +DROP TABLE EMPLOYEE; +DROP TABLE COMPANY; +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, STREET VARCHAR(255), CITY VARCHAR(255), PROVINCE VARCHAR(255), POSTAL_CODE VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE COMPANY (ID INTEGER NOT NULL, STREET VARCHAR(255), CITY VARCHAR(255), STATE VARCHAR(255), ZIP_CODE VARCHAR(255), PRIMARY KEY (ID)); diff --git a/examples/Chapter4/26-sharingEmbeddedObjects/etc/web/WEB-INF/web.xml b/examples/Chapter4/26-sharingEmbeddedObjects/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter4/26-sharingEmbeddedObjects/etc/web/WEB-INF/web.xml @@ -0,0 +1,16 @@ + + + + EmployeeServiceServlet + examples.servlet.EmployeeServiceServlet + + + + EmployeeServiceServlet + /EmployeeServiceServlet + + + \ No newline at end of file diff --git a/examples/Chapter4/26-sharingEmbeddedObjects/src/model/examples/model/Address.java b/examples/Chapter4/26-sharingEmbeddedObjects/src/model/examples/model/Address.java new file mode 100644 index 0000000..c7d9481 --- /dev/null +++ b/examples/Chapter4/26-sharingEmbeddedObjects/src/model/examples/model/Address.java @@ -0,0 +1,54 @@ +package examples.model; + +import javax.persistence.Access; +import javax.persistence.AccessType; +import javax.persistence.Column; +import javax.persistence.Embeddable; + +@Embeddable @Access(AccessType.FIELD) +public class Address { + private String street; + private String city; + private String state; + @Column(name="ZIP_CODE") + private String zip; + + public String getStreet() { + return street; + } + + public void setStreet(String address) { + this.street = address; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getZip() { + return zip; + } + + public void setZip(String zip) { + this.zip = zip; + } + public String toString() { + return "Address street: " + getStreet() + + " city: " + getCity() + + " state: " + getState() + + " zip: " + getZip(); + } + +} diff --git a/examples/Chapter4/26-sharingEmbeddedObjects/src/model/examples/model/Company.java b/examples/Chapter4/26-sharingEmbeddedObjects/src/model/examples/model/Company.java new file mode 100644 index 0000000..4ec08c6 --- /dev/null +++ b/examples/Chapter4/26-sharingEmbeddedObjects/src/model/examples/model/Company.java @@ -0,0 +1,33 @@ +package examples.model; + +import javax.persistence.Embedded; +import javax.persistence.Entity; +import javax.persistence.Id; + + +@Entity +public class Company { + @Id private int id; + + @Embedded + private Address address; + + public int getId() { + return id; + } + public void setId(int id) { + this.id = id; + } + public Address getAddress() { + return this.address; + } + public void setAddress(Address address) { + this.address = address; + } + + public String toString() { + return "Company id: " + getId() + " address: " + getAddress(); + + } + +} \ No newline at end of file diff --git a/examples/Chapter4/26-sharingEmbeddedObjects/src/model/examples/model/Employee.java b/examples/Chapter4/26-sharingEmbeddedObjects/src/model/examples/model/Employee.java new file mode 100644 index 0000000..fa45d88 --- /dev/null +++ b/examples/Chapter4/26-sharingEmbeddedObjects/src/model/examples/model/Employee.java @@ -0,0 +1,61 @@ +package examples.model; + +import javax.persistence.AttributeOverrides; +import javax.persistence.AttributeOverride; +import javax.persistence.Column; +import javax.persistence.Embedded; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Employee { + @Id private int id; + private String name; + private long salary; + + @Embedded + @AttributeOverrides({ + @AttributeOverride(name = "state", column = @Column(name = "PROVINCE")), + @AttributeOverride(name = "zip", column = @Column(name = "POSTAL_CODE")) + }) + private Address address; + + public Employee() {} + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " salary: " + getSalary() + " address: " + getAddress(); + } +} diff --git a/examples/Chapter4/26-sharingEmbeddedObjects/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/26-sharingEmbeddedObjects/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..5cc5c40 --- /dev/null +++ b/examples/Chapter4/26-sharingEmbeddedObjects/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,15 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Company; +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployeeAndAddress(int id, String name, long salary, + String street, String city, String state, String zip); + public Company createCompanyAndAddress(int id, + String street, String city, String state, String zip); + public Collection findAllEmployees(); + public Collection findAllCompanies(); +} diff --git a/examples/Chapter4/26-sharingEmbeddedObjects/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/26-sharingEmbeddedObjects/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..65ed649 --- /dev/null +++ b/examples/Chapter4/26-sharingEmbeddedObjects/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,65 @@ +package examples.stateless; + +import java.util.Collection; +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Address; +import examples.model.Employee; +import examples.model.Company; + + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployeeAndAddress(int id, String name, long salary, + String street, String city, String state, String zip) { + Employee emp = new Employee(); + emp.setId(id); + emp.setName(name); + emp.setSalary(salary); + Address addr = new Address(); + addr.setStreet(street); + addr.setCity(city); + addr.setState(state); + addr.setZip(zip); + emp.setAddress(addr); + em.persist(emp); + + return emp; + } + + public Company createCompanyAndAddress(int id, + String street, String city, String state, String zip) { + Company c = new Company(); + c.setId(id); + Address addr = new Address(); + addr.setStreet(street); + addr.setCity(city); + addr.setState(state); + addr.setZip(zip); + c.setAddress(addr); + + em.persist(c); + return c; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } + + public Collection findAllCompanies() { + Query query = em.createQuery("SELECT c FROM Company c"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter4/26-sharingEmbeddedObjects/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter4/26-sharingEmbeddedObjects/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..17a6c77 --- /dev/null +++ b/examples/Chapter4/26-sharingEmbeddedObjects/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,127 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Company; +import examples.model.Employee; +import examples.model.Address; +import examples.stateless.EmployeeService; + +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 4: Sharing Embedded Objects Example"; + + private final String DESCRIPTION = + "This example demonstrates the basics of sharing embedded objects between entities."; + + @EJB EmployeeService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("CreateEmployee")) { + service.createEmployeeAndAddress( + parseInt(request.getParameter("empId")), + request.getParameter("name"), + parseLong(request.getParameter("salary")), + request.getParameter("street"), + request.getParameter("city"), + request.getParameter("state"), + request.getParameter("zip")); + } else if (action.equals("CreateCompany")) { + service.createCompanyAndAddress( + parseInt(request.getParameter("cId")), + request.getParameter("cStreet"), + request.getParameter("cCity"), + request.getParameter("cState"), + request.getParameter("cZip")); + } + + out.println("Employees and Addresses:
"); + for (Employee emp : service.findAllEmployees()) { + out.print(emp + "
"); + } + + out.println("
Companies and Addresses:
"); + for (Company c : service.findAllCompanies()) { + out.print(c + "
"); + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println(""); + // form to create and Employee and Address + out.println("

Create an Employee and Address

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("" + + ""); + out.println("
Employee Id:(int)
Employee Name:(String)
Employee Salary:(long)
Address Street:(String)
Address City:(String)
Address State:(String)
Address Zip:(String)
"); + out.println("
"); + + out.println("

Create a Company and Address

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("" + + ""); + out.println("
Company Id:(int)
Address Street:(String)
Address City:(String)
Address State:(String)
Address Zip:(String)
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter4/26-sharingEmbeddedObjects/undeploy.bat b/examples/Chapter4/26-sharingEmbeddedObjects/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter4/26-sharingEmbeddedObjects/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter5/1-elementCollection/build.xml b/examples/Chapter5/1-elementCollection/build.xml new file mode 100644 index 0000000..fbd0f19 --- /dev/null +++ b/examples/Chapter5/1-elementCollection/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/1-elementCollection/deploy.bat b/examples/Chapter5/1-elementCollection/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter5/1-elementCollection/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter5/1-elementCollection/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/1-elementCollection/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..a60b9e6 --- /dev/null +++ b/examples/Chapter5/1-elementCollection/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,13 @@ + + + jdbc/elementCollection + NONE + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/1-elementCollection/etc/sql/db.sql b/examples/Chapter5/1-elementCollection/etc/sql/db.sql new file mode 100644 index 0000000..6db593d --- /dev/null +++ b/examples/Chapter5/1-elementCollection/etc/sql/db.sql @@ -0,0 +1,6 @@ +DROP TABLE Employee_VACATIONBOOKINGS; +DROP TABLE Employee_NICKNAMES; +DROP TABLE EMPLOYEE; +CREATE TABLE EMPLOYEE (ID INTEGER GENERATED ALWAYS AS IDENTITY NOT NULL, NAME VARCHAR(255), SALARY BIGINT, PRIMARY KEY (ID)); +CREATE TABLE Employee_VACATIONBOOKINGS (Employee_ID INTEGER NOT NULL, STARTDATE VARCHAR(255), DAYS INTEGER); +CREATE TABLE Employee_NICKNAMES (Employee_ID INTEGER NOT NULL, NICKNAMES VARCHAR(255)); diff --git a/examples/Chapter5/1-elementCollection/etc/web/WEB-INF/web.xml b/examples/Chapter5/1-elementCollection/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter5/1-elementCollection/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter5/1-elementCollection/src/model/examples/model/Employee.java b/examples/Chapter5/1-elementCollection/src/model/examples/model/Employee.java new file mode 100644 index 0000000..938d408 --- /dev/null +++ b/examples/Chapter5/1-elementCollection/src/model/examples/model/Employee.java @@ -0,0 +1,73 @@ +package examples.model; + +import java.util.Collection; +import java.util.Set; + +import javax.persistence.ElementCollection; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@Entity +public class Employee { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + private long salary; + + // Using a targetClass instead of generics + @ElementCollection(targetClass=VacationEntry.class) + private Collection vacationBookings; + + // Using generics in place of a targetClass + @ElementCollection + private Set nickNames; + + public Collection getVacationBookings() { + return vacationBookings; + } + + public void setVacationBookings(Collection vacationBookings) { + this.vacationBookings = vacationBookings; + } + + public Set getNickNames() { + return nickNames; + } + + public void setNickNames(Set nickNames) { + this.nickNames = nickNames; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " salary: " + getSalary() + + " nickNames: " + nickNames; + } +} diff --git a/examples/Chapter5/1-elementCollection/src/model/examples/model/VacationEntry.java b/examples/Chapter5/1-elementCollection/src/model/examples/model/VacationEntry.java new file mode 100644 index 0000000..c9607ab --- /dev/null +++ b/examples/Chapter5/1-elementCollection/src/model/examples/model/VacationEntry.java @@ -0,0 +1,41 @@ +package examples.model; + +import java.util.Calendar; + +import javax.persistence.Column; +import javax.persistence.Embeddable; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Embeddable +public class VacationEntry { + @Temporal(TemporalType.DATE) + private Calendar startDate; + @Column(name="DAYS") + private int daysTaken; + + public VacationEntry() {} + + public VacationEntry(Calendar aStartDate, int daysTakenInt) { + startDate = aStartDate; + daysTaken = daysTakenInt; + } + + public Calendar getStartDate() { + return startDate; + } + public void setStartDate(Calendar startDate) { + this.startDate = startDate; + } + public int getDaysTaken() { + return daysTaken; + } + public void setDaysTaken(int daysTaken) { + this.daysTaken = daysTaken; + } + + public String toString() { + return "VacationEntry startDate: " + getStartDate().getTime() + + ", daysTaken: " + getDaysTaken(); + } +} \ No newline at end of file diff --git a/examples/Chapter5/1-elementCollection/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/1-elementCollection/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..a333a14 --- /dev/null +++ b/examples/Chapter5/1-elementCollection/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(String name, long salary); + public Employee addEmployeeNickname(int empId, String nickname); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter5/1-elementCollection/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/1-elementCollection/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..f5115fd --- /dev/null +++ b/examples/Chapter5/1-elementCollection/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,48 @@ +package examples.stateless; + +import java.util.Collection; +import java.util.GregorianCalendar; +import java.util.HashSet; +import java.util.Set; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Employee; +import examples.model.VacationEntry; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String name, long salary) { + Employee emp = new Employee(); + emp.setName(name); + emp.setSalary(salary); + + em.persist(emp); + return emp; + } + + public Employee addEmployeeNickname(int empId, String nickname) { + Employee emp = em.find(Employee.class, empId); + if (emp != null) { + emp.getNickNames().add(nickname); + } + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + Collection emps = (Collection) query.getResultList(); + // trigger lazy collections + for (Employee emp : emps) { + emp.getVacationBookings().size(); + emp.getNickNames().size(); + } + return emps; + } +} diff --git a/examples/Chapter5/1-elementCollection/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter5/1-elementCollection/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..8d73d4e --- /dev/null +++ b/examples/Chapter5/1-elementCollection/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,121 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 5: ElementCollection Example"; + + private final String DESCRIPTION = + "This example demonstrates how to specify an ElementCollection of Embeddables or Basic types.
"; + + + @EJB EmployeeService empService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("CreateEmp")) { + Employee emp = empService.createEmployee( + request.getParameter("empName"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("AddNickname")) { + Employee emp = empService.addEmployeeNickname( + parseInt(request.getParameter("id")), + request.getParameter("nickname")); + if (emp != null) { + out.println("Added nickname to Employee " + emp); + } + } else if (action.equals("FindAll")) { + Collection emps = empService.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + + out.println("
"); + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println(""); + // form to create Employee + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
Employee Salary:(long)
"); + out.println("
"); + // form to Add a nickname + out.println("

Add a Nickname

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
Nickname:(String)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees

"); + out.println(""); + out.println(""); + out.println("
"); + } + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter5/1-elementCollection/undeploy.bat b/examples/Chapter5/1-elementCollection/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter5/1-elementCollection/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter5/10-embeddableKeyMapping/build.xml b/examples/Chapter5/10-embeddableKeyMapping/build.xml new file mode 100644 index 0000000..d63d458 --- /dev/null +++ b/examples/Chapter5/10-embeddableKeyMapping/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/10-embeddableKeyMapping/deploy.bat b/examples/Chapter5/10-embeddableKeyMapping/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter5/10-embeddableKeyMapping/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter5/10-embeddableKeyMapping/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/10-embeddableKeyMapping/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..e685cfc --- /dev/null +++ b/examples/Chapter5/10-embeddableKeyMapping/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,13 @@ + + + jdbc/embeddableKey + NONE + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/10-embeddableKeyMapping/etc/sql/db.sql b/examples/Chapter5/10-embeddableKeyMapping/etc/sql/db.sql new file mode 100644 index 0000000..184f352 --- /dev/null +++ b/examples/Chapter5/10-embeddableKeyMapping/etc/sql/db.sql @@ -0,0 +1,6 @@ +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; +CREATE TABLE EMPLOYEE (ID INTEGER GENERATED ALWAYS AS IDENTITY NOT NULL, F_NAME VARCHAR(255), L_NAME VARCHAR(255), SALARY BIGINT, + DEPARTMENT_ID INTEGER, PRIMARY KEY (ID)); +CREATE TABLE DEPARTMENT (ID INTEGER GENERATED ALWAYS AS IDENTITY NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +ALTER TABLE EMPLOYEE ADD CONSTRAINT MPLOYEEDPARTMENTID FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID); diff --git a/examples/Chapter5/10-embeddableKeyMapping/etc/web/WEB-INF/web.xml b/examples/Chapter5/10-embeddableKeyMapping/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter5/10-embeddableKeyMapping/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter5/10-embeddableKeyMapping/src/model/examples/model/Department.java b/examples/Chapter5/10-embeddableKeyMapping/src/model/examples/model/Department.java new file mode 100644 index 0000000..415f5b8 --- /dev/null +++ b/examples/Chapter5/10-embeddableKeyMapping/src/model/examples/model/Department.java @@ -0,0 +1,82 @@ +package examples.model; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +import javax.persistence.MapKey; +import javax.persistence.OneToMany; + + +@Entity +public class Department { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + + @OneToMany(mappedBy="department") + private Map employeesByName; + + + public Department() { + employeesByName = new HashMap(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String deptName) { + this.name = deptName; + } + + public Map getEmployees() { + return employeesByName; + } + + public void addEmployee(Employee employee) { + EmployeeName empName = new EmployeeName(); + empName.setFirst_Name(employee.getFirstName()); + empName.setLast_Name(employee.getLastName()); + employeesByName.put(empName, employee); + if (employee.getDepartment() != null) { + employee.getDepartment().removeEmployee(employee); + } + employee.setDepartment(this); + } + + public void removeEmployee(Employee employee) { + Iterator iter = employeesByName.entrySet().iterator(); + while (iter.hasNext()) { + Employee current = ((Map.Entry) iter.next()).getValue(); + if (current.getId() == employee.getId()) { + iter.remove(); + current.setDepartment(null); + } + } + } + + public String toString() { + StringBuffer aBuffer = new StringBuffer("Department "); + aBuffer.append(" id: "); + aBuffer.append(id); + aBuffer.append(" name: "); + aBuffer.append(name); + aBuffer.append(" employeeCount: "); + aBuffer.append(employeesByName.size()); + return aBuffer.toString(); + } +} \ No newline at end of file diff --git a/examples/Chapter5/10-embeddableKeyMapping/src/model/examples/model/Employee.java b/examples/Chapter5/10-embeddableKeyMapping/src/model/examples/model/Employee.java new file mode 100644 index 0000000..42d47f6 --- /dev/null +++ b/examples/Chapter5/10-embeddableKeyMapping/src/model/examples/model/Employee.java @@ -0,0 +1,85 @@ +package examples.model; + +import java.util.Map; + +import javax.persistence.CollectionTable; +import javax.persistence.Column; +import javax.persistence.ElementCollection; +import javax.persistence.Embedded; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import javax.persistence.MapKeyColumn; + +@Entity +public class Employee { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + @Column(name="F_NAME") + private String firstName; + @Column(name="L_NAME") + private String lastName; + private long salary; + + @ManyToOne + private Department department; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + + public String toString() { + StringBuffer aBuffer = new StringBuffer("Employee "); + aBuffer.append(" id: "); + aBuffer.append(id); + aBuffer.append(" name: "); + aBuffer.append(lastName); + aBuffer.append(", "); + aBuffer.append(firstName); + aBuffer.append(" with dept: "); + if(null != department) { + aBuffer.append(department.getName()); + } + return aBuffer.toString(); + } +} \ No newline at end of file diff --git a/examples/Chapter5/10-embeddableKeyMapping/src/model/examples/model/EmployeeName.java b/examples/Chapter5/10-embeddableKeyMapping/src/model/examples/model/EmployeeName.java new file mode 100644 index 0000000..81dbc30 --- /dev/null +++ b/examples/Chapter5/10-embeddableKeyMapping/src/model/examples/model/EmployeeName.java @@ -0,0 +1,25 @@ +package examples.model; + +import javax.persistence.Column; +import javax.persistence.Embeddable; + +@Embeddable +public class EmployeeName { + @Column(name="F_NAME", insertable=false, updatable=false) + private String first_Name; + @Column(name="L_NAME", insertable=false, updatable=false) + private String last_Name; + + public String getFirst_Name() { + return first_Name; + } + public void setFirst_Name(String firstName) { + first_Name = firstName; + } + public String getLast_Name() { + return last_Name; + } + public void setLast_Name(String lastName) { + last_Name = lastName; + } +} diff --git a/examples/Chapter5/10-embeddableKeyMapping/src/model/examples/stateless/DepartmentService.java b/examples/Chapter5/10-embeddableKeyMapping/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..7003e8d --- /dev/null +++ b/examples/Chapter5/10-embeddableKeyMapping/src/model/examples/stateless/DepartmentService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Department; + +public interface DepartmentService { + public Department createDepartment(String name); + public Collection findAllDepartments(); +} diff --git a/examples/Chapter5/10-embeddableKeyMapping/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter5/10-embeddableKeyMapping/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..7d47cb1 --- /dev/null +++ b/examples/Chapter5/10-embeddableKeyMapping/src/model/examples/stateless/DepartmentServiceBean.java @@ -0,0 +1,29 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; + +@Stateless +public class DepartmentServiceBean implements DepartmentService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Department createDepartment(String name) { + Department dept = new Department(); + dept.setName(name); + em.persist(dept); + + return dept; + } + + public Collection findAllDepartments() { + Query query = em.createQuery("SELECT d FROM Department d"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter5/10-embeddableKeyMapping/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/10-embeddableKeyMapping/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..9bb624b --- /dev/null +++ b/examples/Chapter5/10-embeddableKeyMapping/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(String fname, String lname, long salary); + public Employee setEmployeeDepartment(int empId, int deptId); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter5/10-embeddableKeyMapping/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/10-embeddableKeyMapping/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..12d4e3c --- /dev/null +++ b/examples/Chapter5/10-embeddableKeyMapping/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,41 @@ +package examples.stateless; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String fname, String lname, long salary) { + Employee emp = new Employee(); + emp.setFirstName(fname); + emp.setLastName(lname); + emp.setSalary(salary); + em.persist(emp); + return emp; + } + + public Employee setEmployeeDepartment(int empId, int deptId) { + Employee emp = em.find(Employee.class, empId); + Department dept = em.find(Department.class, deptId); + dept.addEmployee(emp); + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + Collection aCollection = (Collection) query.getResultList(); + return aCollection; + } +} diff --git a/examples/Chapter5/10-embeddableKeyMapping/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter5/10-embeddableKeyMapping/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..bcda486 --- /dev/null +++ b/examples/Chapter5/10-embeddableKeyMapping/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,144 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Department; +import examples.model.Employee; +import examples.stateless.DepartmentService; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 5: One-To-Many Map Keyed By Embeddable"; + + private final String DESCRIPTION = + "This example demonstrates how to work with relationship Maps.
" + + "The Map contains embeddable keys and entity values."; + + + @EJB EmployeeService empService; + @EJB DepartmentService deptService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("CreateEmp")) { + Employee emp = empService.createEmployee( + request.getParameter("empFName"), + request.getParameter("empLName"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("CreateDept")) { + Department dept = deptService.createDepartment( + request.getParameter("deptName")); + out.println("Created " + dept); + } else if (action.equals("SetEmployeeDept")) { + Employee emp = empService.setEmployeeDepartment( + parseInt(request.getParameter("empId")), + parseInt(request.getParameter("deptId"))); + out.println("Updated " + emp + "
"); + } else if (action.equals("FindAll")) { + Collection emps = empService.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + + out.println("
"); + Collection depts = deptService.findAllDepartments(); + if (depts.isEmpty()) { + out.println("No Departments found "); + } else { + out.println("Found Departments:
"); + for (Department dept : depts) { + out.println(dept + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Department + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee First Name:(String)
Employee Last Name:(String)
Employee Salary:(long)
"); + out.println("
"); + + out.println(""); + out.println(""); + out.println(""); + out.println("
Dept Name:(String)
"); + out.println("
"); + + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Emp Id:(int)
Dept Id:(int)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees & Departments

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter5/10-embeddableKeyMapping/undeploy.bat b/examples/Chapter5/10-embeddableKeyMapping/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter5/10-embeddableKeyMapping/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/build.xml b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/build.xml new file mode 100644 index 0000000..fd4b7ef --- /dev/null +++ b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/build.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/deploy.bat b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..1b5a931 --- /dev/null +++ b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,13 @@ + + + jdbc/manyToManyEmbeddableKeyOverride + NONE + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/etc/sql/db.sql b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/etc/sql/db.sql new file mode 100644 index 0000000..ba94992 --- /dev/null +++ b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/etc/sql/db.sql @@ -0,0 +1,8 @@ +DROP TABLE DEPT_EMP; +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; +CREATE TABLE EMPLOYEE (ID INTEGER GENERATED ALWAYS AS IDENTITY NOT NULL, F_NAME VARCHAR(255), L_NAME VARCHAR(255), SALARY BIGINT, PRIMARY KEY (ID)); +CREATE TABLE DEPARTMENT (ID INTEGER GENERATED ALWAYS AS IDENTITY NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE DEPT_EMP (DEPT_ID INTEGER NOT NULL, EMP_ID INTEGER NOT NULL, EMP_FNAME VARCHAR(255), EMP_LNAME VARCHAR(255), PRIMARY KEY (DEPT_ID, EMP_ID)); +ALTER TABLE DEPT_EMP ADD CONSTRAINT DEPTREF FOREIGN KEY (DEPT_ID) REFERENCES DEPARTMENT (ID); +ALTER TABLE DEPT_EMP ADD CONSTRAINT EMPREF FOREIGN KEY (EMP_ID) REFERENCES EMPLOYEE (ID); diff --git a/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/etc/web/WEB-INF/web.xml b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/src/model/examples/model/Department.java b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/src/model/examples/model/Department.java new file mode 100644 index 0000000..954d235 --- /dev/null +++ b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/src/model/examples/model/Department.java @@ -0,0 +1,89 @@ +package examples.model; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import javax.persistence.AttributeOverride; +import javax.persistence.AttributeOverrides; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; + + +@Entity +public class Department { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + + @ManyToMany + @JoinTable(name="DEPT_EMP", + joinColumns=@JoinColumn(name="DEPT_ID"), + inverseJoinColumns=@JoinColumn(name="EMP_ID")) + @AttributeOverrides({ + @AttributeOverride( + name="first_Name", + column=@Column(name="EMP_FNAME")), + @AttributeOverride( + name="last_Name", + column=@Column(name="EMP_LNAME")) + }) + private Map employeesByName; + + + public Department() { + employeesByName = new HashMap(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String deptName) { + this.name = deptName; + } + + public Map getEmployees() { + return employeesByName; + } + + public void addEmployee(Employee employee) { + EmployeeName empName = employee.getName(); + employeesByName.put(empName, employee); + } + + public void removeEmployee(Employee employee) { + Iterator iter = employeesByName.entrySet().iterator(); + while (iter.hasNext()) { + Employee current = ((Map.Entry) iter.next()).getValue(); + if (current.getId() == employee.getId()) { + iter.remove(); + } + } + } + + public String toString() { + StringBuffer aBuffer = new StringBuffer("Department "); + aBuffer.append(" id: "); + aBuffer.append(id); + aBuffer.append(" name: "); + aBuffer.append(name); + aBuffer.append(" employeeCount: "); + aBuffer.append(employeesByName.size()); + return aBuffer.toString(); + } +} \ No newline at end of file diff --git a/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/src/model/examples/model/Employee.java b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/src/model/examples/model/Employee.java new file mode 100644 index 0000000..75aec4f --- /dev/null +++ b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/src/model/examples/model/Employee.java @@ -0,0 +1,97 @@ +package examples.model; + +import java.util.Collection; +import java.util.ArrayList; + +import javax.persistence.CollectionTable; +import javax.persistence.Column; +import javax.persistence.ElementCollection; +import javax.persistence.Embedded; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToMany; + +@Entity +public class Employee { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + + @Embedded + private EmployeeName name; + + private long salary; + + @ManyToMany(mappedBy="employeesByName") + private Collection departments; + + public Employee() { + name = new EmployeeName(); + departments = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public EmployeeName getName() { + return name; + } + + public void setName(EmployeeName name) { + this.name = name; + } + + public String getFirstName() { + return name.getFirst_Name(); + } + + public void setFirstName(String firstName) { + this.name.setFirst_Name(firstName); + } + + public String getLastName() { + return name.getLast_Name(); + } + + public void setLastName(String lastName) { + this.name.setLast_Name(lastName); + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public Collection getDepartments() { + return departments; + } + + public void setDepartments(Collection departments) { + this.departments = departments; + } + + + public String toString() { + StringBuffer aBuffer = new StringBuffer("Employee "); + aBuffer.append(" id: "); + aBuffer.append(id); + aBuffer.append(" name: "); + aBuffer.append(getLastName()); + aBuffer.append(", "); + aBuffer.append(getFirstName()); + aBuffer.append(" with deptCount: "); + if(null != departments) { + aBuffer.append(departments.size()); + } + return aBuffer.toString(); + } +} \ No newline at end of file diff --git a/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/src/model/examples/model/EmployeeName.java b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/src/model/examples/model/EmployeeName.java new file mode 100644 index 0000000..8cf8800 --- /dev/null +++ b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/src/model/examples/model/EmployeeName.java @@ -0,0 +1,25 @@ +package examples.model; + +import javax.persistence.Column; +import javax.persistence.Embeddable; + +@Embeddable +public class EmployeeName { + @Column(name="F_NAME") + private String first_Name; + @Column(name="L_NAME") + private String last_Name; + + public String getFirst_Name() { + return first_Name; + } + public void setFirst_Name(String firstName) { + first_Name = firstName; + } + public String getLast_Name() { + return last_Name; + } + public void setLast_Name(String lastName) { + last_Name = lastName; + } +} diff --git a/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/src/model/examples/stateless/DepartmentService.java b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..7003e8d --- /dev/null +++ b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/src/model/examples/stateless/DepartmentService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Department; + +public interface DepartmentService { + public Department createDepartment(String name); + public Collection findAllDepartments(); +} diff --git a/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..7d47cb1 --- /dev/null +++ b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/src/model/examples/stateless/DepartmentServiceBean.java @@ -0,0 +1,29 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; + +@Stateless +public class DepartmentServiceBean implements DepartmentService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Department createDepartment(String name) { + Department dept = new Department(); + dept.setName(name); + em.persist(dept); + + return dept; + } + + public Collection findAllDepartments() { + Query query = em.createQuery("SELECT d FROM Department d"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..9bb624b --- /dev/null +++ b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(String fname, String lname, long salary); + public Employee setEmployeeDepartment(int empId, int deptId); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..782ea48 --- /dev/null +++ b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,42 @@ +package examples.stateless; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String fname, String lname, long salary) { + Employee emp = new Employee(); + emp.setFirstName(fname); + emp.setLastName(lname); + emp.setSalary(salary); + em.persist(emp); + return emp; + } + + public Employee setEmployeeDepartment(int empId, int deptId) { + Employee emp = em.find(Employee.class, empId); + Department dept = em.find(Department.class, deptId); + dept.addEmployee(emp); + emp.getDepartments().add(dept); + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + Collection aCollection = (Collection) query.getResultList(); + return aCollection; + } +} diff --git a/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..2a426e0 --- /dev/null +++ b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,144 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Department; +import examples.model.Employee; +import examples.stateless.DepartmentService; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 5: Many-To-Many Map Example With Embeddable Key Override"; + + private final String DESCRIPTION = + "This example demonstrates how to work with relationship Maps.
" + + "The Map contains embeddable keys and entity values."; + + + @EJB EmployeeService empService; + @EJB DepartmentService deptService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("CreateEmp")) { + Employee emp = empService.createEmployee( + request.getParameter("empFName"), + request.getParameter("empLName"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("CreateDept")) { + Department dept = deptService.createDepartment( + request.getParameter("deptName")); + out.println("Created " + dept); + } else if (action.equals("SetEmployeeDept")) { + Employee emp = empService.setEmployeeDepartment( + parseInt(request.getParameter("empId")), + parseInt(request.getParameter("deptId"))); + out.println("Updated " + emp + "
"); + } else if (action.equals("FindAll")) { + Collection emps = empService.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + + out.println("
"); + Collection depts = deptService.findAllDepartments(); + if (depts.isEmpty()) { + out.println("No Departments found "); + } else { + out.println("Found Departments:
"); + for (Department dept : depts) { + out.println(dept + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Department + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee First Name:(String)
Employee Last Name:(String)
Employee Salary:(long)
"); + out.println("
"); + + out.println(""); + out.println(""); + out.println(""); + out.println("
Dept Name:(String)
"); + out.println("
"); + + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Emp Id:(int)
Dept Id:(int)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees & Departments

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/undeploy.bat b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter5/11-manyToManyEmbeddableKeyOverride/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter5/12-elementCollectionMapKeyEntity/build.xml b/examples/Chapter5/12-elementCollectionMapKeyEntity/build.xml new file mode 100644 index 0000000..2f97d3e --- /dev/null +++ b/examples/Chapter5/12-elementCollectionMapKeyEntity/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/12-elementCollectionMapKeyEntity/deploy.bat b/examples/Chapter5/12-elementCollectionMapKeyEntity/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter5/12-elementCollectionMapKeyEntity/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter5/12-elementCollectionMapKeyEntity/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/12-elementCollectionMapKeyEntity/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..50fe019 --- /dev/null +++ b/examples/Chapter5/12-elementCollectionMapKeyEntity/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,13 @@ + + + jdbc/elementCollectionMapKeyEntity + NONE + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/12-elementCollectionMapKeyEntity/etc/sql/db.sql b/examples/Chapter5/12-elementCollectionMapKeyEntity/etc/sql/db.sql new file mode 100644 index 0000000..8683423 --- /dev/null +++ b/examples/Chapter5/12-elementCollectionMapKeyEntity/etc/sql/db.sql @@ -0,0 +1,8 @@ +DROP TABLE EMP_SENIORITY; +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; +CREATE TABLE EMPLOYEE (ID INTEGER GENERATED ALWAYS AS IDENTITY NOT NULL, NAME VARCHAR(255), SALARY BIGINT, PRIMARY KEY (ID)); +CREATE TABLE DEPARTMENT (ID INTEGER GENERATED ALWAYS AS IDENTITY NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMP_SENIORITY (DEPARTMENT_ID INTEGER NOT NULL, EMP_ID INTEGER NOT NULL, SENIORITY INTEGER, PRIMARY KEY (DEPARTMENT_ID, EMP_ID)); +ALTER TABLE EMP_SENIORITY ADD CONSTRAINT DEPTREF FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID); +ALTER TABLE EMP_SENIORITY ADD CONSTRAINT EMPREF FOREIGN KEY (EMP_ID) REFERENCES EMPLOYEE (ID); diff --git a/examples/Chapter5/12-elementCollectionMapKeyEntity/etc/web/WEB-INF/web.xml b/examples/Chapter5/12-elementCollectionMapKeyEntity/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter5/12-elementCollectionMapKeyEntity/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter5/12-elementCollectionMapKeyEntity/src/model/examples/model/Department.java b/examples/Chapter5/12-elementCollectionMapKeyEntity/src/model/examples/model/Department.java new file mode 100644 index 0000000..a8812e6 --- /dev/null +++ b/examples/Chapter5/12-elementCollectionMapKeyEntity/src/model/examples/model/Department.java @@ -0,0 +1,69 @@ +package examples.model; + +import java.util.HashMap; +import java.util.Map; + +import javax.persistence.CollectionTable; +import javax.persistence.Column; +import javax.persistence.ElementCollection; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.MapKeyJoinColumn; + +@Entity +public class Department { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + + @ElementCollection + @CollectionTable(name="EMP_SENIORITY") + @MapKeyJoinColumn(name="EMP_ID") + @Column(name="SENIORITY") + private Map seniorities; + + public Department() { + seniorities = new HashMap(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String deptName) { + this.name = deptName; + } + + public Map getEmployees() { + return seniorities; + } + + public void setEmployeeSeniority(Employee employee, int seniority) { + seniorities.put(employee, seniority); + } + + public void removeEmployee(Employee employee) { + seniorities.remove(employee); + } + + public String toString() { + StringBuffer aBuffer = new StringBuffer("Department "); + aBuffer.append(" id: "); + aBuffer.append(id); + aBuffer.append(" name: "); + aBuffer.append(name); + aBuffer.append(" employeeCount: "); + aBuffer.append(seniorities.size()); + return aBuffer.toString(); + } +} \ No newline at end of file diff --git a/examples/Chapter5/12-elementCollectionMapKeyEntity/src/model/examples/model/Employee.java b/examples/Chapter5/12-elementCollectionMapKeyEntity/src/model/examples/model/Employee.java new file mode 100644 index 0000000..5d5eb54 --- /dev/null +++ b/examples/Chapter5/12-elementCollectionMapKeyEntity/src/model/examples/model/Employee.java @@ -0,0 +1,45 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Employee { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + private long salary; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public String toString() { + StringBuffer aBuffer = new StringBuffer("Employee "); + aBuffer.append(" id: "); + aBuffer.append(id); + return aBuffer.toString(); + } +} \ No newline at end of file diff --git a/examples/Chapter5/12-elementCollectionMapKeyEntity/src/model/examples/stateless/DepartmentService.java b/examples/Chapter5/12-elementCollectionMapKeyEntity/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..4f97edc --- /dev/null +++ b/examples/Chapter5/12-elementCollectionMapKeyEntity/src/model/examples/stateless/DepartmentService.java @@ -0,0 +1,12 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Department; +import examples.model.Employee; + +public interface DepartmentService { + public Department createDepartment(String name); + public Employee setEmployeeSeniority(int deptId, int empId, int seniority); + public Collection findAllDepartments(); +} diff --git a/examples/Chapter5/12-elementCollectionMapKeyEntity/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter5/12-elementCollectionMapKeyEntity/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..8dacb50 --- /dev/null +++ b/examples/Chapter5/12-elementCollectionMapKeyEntity/src/model/examples/stateless/DepartmentServiceBean.java @@ -0,0 +1,38 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; +import examples.model.Employee; + + +@Stateless +public class DepartmentServiceBean implements DepartmentService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Department createDepartment(String name) { + Department dept = new Department(); + dept.setName(name); + em.persist(dept); + + return dept; + } + + public Employee setEmployeeSeniority(int deptId, int empId, int seniority) { + Department dept = em.find(Department.class, deptId); + Employee emp = em.find(Employee.class, empId); + dept.setEmployeeSeniority(emp, seniority); + return emp; + } + + public Collection findAllDepartments() { + Query query = em.createQuery("SELECT d FROM Department d"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter5/12-elementCollectionMapKeyEntity/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/12-elementCollectionMapKeyEntity/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..824af91 --- /dev/null +++ b/examples/Chapter5/12-elementCollectionMapKeyEntity/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(String name, long salary); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter5/12-elementCollectionMapKeyEntity/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/12-elementCollectionMapKeyEntity/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..da734dd --- /dev/null +++ b/examples/Chapter5/12-elementCollectionMapKeyEntity/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,33 @@ +package examples.stateless; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String name, long salary) { + Employee emp = new Employee(); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + Collection aCollection = (Collection) query.getResultList(); + return aCollection; + } +} diff --git a/examples/Chapter5/12-elementCollectionMapKeyEntity/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter5/12-elementCollectionMapKeyEntity/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..33ce095 --- /dev/null +++ b/examples/Chapter5/12-elementCollectionMapKeyEntity/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,144 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Department; +import examples.model.Employee; +import examples.stateless.DepartmentService; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 5: Element Collection Map Example Keyed by Entity"; + + private final String DESCRIPTION = + "This example demonstrates how to work with element collection Maps.
" + + "The Map contains entity keys and integer values."; + + + @EJB EmployeeService empService; + @EJB DepartmentService deptService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("CreateEmp")) { + Employee emp = empService.createEmployee( + request.getParameter("empName"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("CreateDept")) { + Department dept = deptService.createDepartment( + request.getParameter("deptName")); + out.println("Created " + dept); + } else if (action.equals("SetEmployeeSeniority")) { + Employee emp = deptService.setEmployeeSeniority( + parseInt(request.getParameter("deptId")), + parseInt(request.getParameter("empId")), + parseInt(request.getParameter("seniority"))); + out.println("Updated seniority of " + emp + "
"); + } else if (action.equals("FindAll")) { + Collection emps = empService.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + + out.println("
"); + Collection depts = deptService.findAllDepartments(); + if (depts.isEmpty()) { + out.println("No Departments found "); + } else { + out.println("Found Departments:
"); + for (Department dept : depts) { + out.println(dept + " with employees " + dept.getEmployees() + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Department + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
Employee Salary:(long)
"); + out.println("
"); + + out.println(""); + out.println(""); + out.println(""); + out.println("
Dept Name:(String)
"); + out.println("
"); + + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Dept Id:(int)
Emp Id:(int)
Seniority:(String)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees & Departments

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter5/12-elementCollectionMapKeyEntity/undeploy.bat b/examples/Chapter5/12-elementCollectionMapKeyEntity/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter5/12-elementCollectionMapKeyEntity/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter5/13-untypedMaps/build.xml b/examples/Chapter5/13-untypedMaps/build.xml new file mode 100644 index 0000000..3e3fc80 --- /dev/null +++ b/examples/Chapter5/13-untypedMaps/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/13-untypedMaps/deploy.bat b/examples/Chapter5/13-untypedMaps/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter5/13-untypedMaps/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter5/13-untypedMaps/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/13-untypedMaps/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..5c3ff3b --- /dev/null +++ b/examples/Chapter5/13-untypedMaps/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,13 @@ + + + jdbc/untypedMaps + NONE + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/13-untypedMaps/etc/sql/db.sql b/examples/Chapter5/13-untypedMaps/etc/sql/db.sql new file mode 100644 index 0000000..7d91ac3 --- /dev/null +++ b/examples/Chapter5/13-untypedMaps/etc/sql/db.sql @@ -0,0 +1,8 @@ +DROP TABLE EMP_PHONE; +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; +CREATE TABLE EMP_PHONE (Employee_ID INTEGER NOT NULL, PHONE_NUM VARCHAR(255), PHONE_TYPE VARCHAR(255)); +CREATE TABLE EMPLOYEE (ID INTEGER GENERATED ALWAYS AS IDENTITY NOT NULL, NAME VARCHAR(255), SALARY BIGINT, DEPARTMENT_ID INTEGER, PRIMARY KEY (ID)); +CREATE TABLE DEPARTMENT (ID INTEGER GENERATED ALWAYS AS IDENTITY NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +ALTER TABLE EMP_PHONE ADD CONSTRAINT EMPPHONEID FOREIGN KEY (Employee_ID) REFERENCES EMPLOYEE (ID); +ALTER TABLE EMPLOYEE ADD CONSTRAINT MPLOYEEDPARTMENTID FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID); diff --git a/examples/Chapter5/13-untypedMaps/etc/web/WEB-INF/web.xml b/examples/Chapter5/13-untypedMaps/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter5/13-untypedMaps/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter5/13-untypedMaps/src/model/examples/model/Department.java b/examples/Chapter5/13-untypedMaps/src/model/examples/model/Department.java new file mode 100644 index 0000000..58e28cb --- /dev/null +++ b/examples/Chapter5/13-untypedMaps/src/model/examples/model/Department.java @@ -0,0 +1,67 @@ +package examples.model; + +import java.util.HashMap; +import java.util.Map; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.MapKey; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + + @OneToMany(targetEntity=Employee.class, mappedBy="department") + @MapKey + private Map employees; + + public Department() { + employees = new HashMap(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String deptName) { + this.name = deptName; + } + + public void addEmployee(Employee employee) { + employees.put(employee.getId(), employee); + if (employee.getDepartment() != null) { + employee.getDepartment().getEmployees().remove(employee.getId()); + } + employee.setDepartment(this); + } + + public Map getEmployees() { + return employees; + } + + public String toString() { + StringBuffer aBuffer = new StringBuffer("Department "); + aBuffer.append(" id: "); + aBuffer.append(id); + aBuffer.append(" name: "); + aBuffer.append(name); + aBuffer.append(" employeeCount: "); + if(null != employees) { + aBuffer.append(employees.size()); + } + return aBuffer.toString(); + } +} \ No newline at end of file diff --git a/examples/Chapter5/13-untypedMaps/src/model/examples/model/Employee.java b/examples/Chapter5/13-untypedMaps/src/model/examples/model/Employee.java new file mode 100644 index 0000000..7831ef6 --- /dev/null +++ b/examples/Chapter5/13-untypedMaps/src/model/examples/model/Employee.java @@ -0,0 +1,89 @@ +package examples.model; + +import java.util.Map; +import java.util.Set; + +import javax.persistence.CollectionTable; +import javax.persistence.Column; +import javax.persistence.ElementCollection; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import javax.persistence.MapKeyClass; +import javax.persistence.MapKeyColumn; + +@Entity +public class Employee { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + private long salary; + + @ElementCollection(targetClass=String.class) + @CollectionTable(name="EMP_PHONE") + @MapKeyColumn(name="PHONE_TYPE") + @MapKeyClass(String.class) + @Column(name="PHONE_NUM") + private Map phoneNumbers; + + @ManyToOne + private Department department; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + public Map getPhoneNumbers() { + return phoneNumbers; + } + + public void setPhoneNumbers(Map phoneNumbers) { + this.phoneNumbers = phoneNumbers; + } + + public String toString() { + StringBuffer aBuffer = new StringBuffer("Employee "); + aBuffer.append(" id: "); + aBuffer.append(id); + aBuffer.append(" with dept: "); + if(null != department) { + aBuffer.append(department.getName()); + } + aBuffer.append(" phoneNumbers: "); + for (Map.Entry e : (Set)phoneNumbers.entrySet()) { + aBuffer.append(e.getKey() + "[" + e.getValue() + "] "); + } + return aBuffer.toString(); + } +} \ No newline at end of file diff --git a/examples/Chapter5/13-untypedMaps/src/model/examples/stateless/DepartmentService.java b/examples/Chapter5/13-untypedMaps/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..7003e8d --- /dev/null +++ b/examples/Chapter5/13-untypedMaps/src/model/examples/stateless/DepartmentService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Department; + +public interface DepartmentService { + public Department createDepartment(String name); + public Collection findAllDepartments(); +} diff --git a/examples/Chapter5/13-untypedMaps/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter5/13-untypedMaps/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..7d47cb1 --- /dev/null +++ b/examples/Chapter5/13-untypedMaps/src/model/examples/stateless/DepartmentServiceBean.java @@ -0,0 +1,29 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; + +@Stateless +public class DepartmentServiceBean implements DepartmentService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Department createDepartment(String name) { + Department dept = new Department(); + dept.setName(name); + em.persist(dept); + + return dept; + } + + public Collection findAllDepartments() { + Query query = em.createQuery("SELECT d FROM Department d"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter5/13-untypedMaps/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/13-untypedMaps/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..84116f6 --- /dev/null +++ b/examples/Chapter5/13-untypedMaps/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(String name, long salary); + public Employee setEmployeeDepartment(int empId, int deptId); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter5/13-untypedMaps/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/13-untypedMaps/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..385a7c9 --- /dev/null +++ b/examples/Chapter5/13-untypedMaps/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,55 @@ +package examples.stateless; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.List; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String name, long salary) { + Employee emp = new Employee(); + emp.setName(name); + emp.setSalary(salary); + Map phoneMap = new HashMap(); + phoneMap.put("home","613-289-3214"); + phoneMap.put("mobile","613-760-2332"); + emp.setPhoneNumbers(phoneMap); + em.persist(emp); + return emp; + } + + public Employee setEmployeeDepartment(int empId, int deptId) { + Employee emp = em.find(Employee.class, empId); + Department dept = em.find(Department.class, deptId); + dept.addEmployee(emp); + emp.setDepartment(dept); + // trigger indirection + emp.getPhoneNumbers().size(); + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + Collection aCollection = (Collection) query.getResultList(); + // trigger indirection + for(Employee anEmployee : aCollection) { + anEmployee.getPhoneNumbers().size(); + } + return aCollection; + } +} diff --git a/examples/Chapter5/13-untypedMaps/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter5/13-untypedMaps/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..7bac907 --- /dev/null +++ b/examples/Chapter5/13-untypedMaps/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,143 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Department; +import examples.model.Employee; +import examples.stateless.DepartmentService; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 5: Non-Parameterized Types Example"; + + private final String DESCRIPTION = + "This example demonstrates how to work with collections that are untyped."; + + + @EJB EmployeeService empService; + @EJB DepartmentService deptService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("CreateEmp")) { + Employee emp = empService.createEmployee( + request.getParameter("empName"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("CreateDept")) { + Department dept = deptService.createDepartment( + request.getParameter("deptName")); + out.println("Created " + dept); + } else if (action.equals("SetEmployeeDept")) { + Employee emp = empService.setEmployeeDepartment( + parseInt(request.getParameter("empId")), + parseInt(request.getParameter("deptId"))); + out.println("Updated " + emp + "
"); + out.println(emp.getDepartment() + " with Employees:
"); + out.println(emp.getDepartment().getEmployees()); + } else if (action.equals("FindAll")) { + Collection emps = empService.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + + out.println("
"); + Collection depts = deptService.findAllDepartments(); + if (depts.isEmpty()) { + out.println("No Departments found "); + } else { + out.println("Found Departments:
"); + for (Department dept : depts) { + out.println(dept + " with " + dept.getEmployees().size() + + " employees " + dept.getEmployees() + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Department + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
Employee Salary:(long)
"); + out.println("
"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Dept Name:(String)
"); + out.println("
"); + + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Emp Id:(int)
Dept Id:(int)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees & Departments

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter5/13-untypedMaps/undeploy.bat b/examples/Chapter5/13-untypedMaps/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter5/13-untypedMaps/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter5/2-overrideCollectionTableColumn/build.xml b/examples/Chapter5/2-overrideCollectionTableColumn/build.xml new file mode 100644 index 0000000..b4f909a --- /dev/null +++ b/examples/Chapter5/2-overrideCollectionTableColumn/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/2-overrideCollectionTableColumn/deploy.bat b/examples/Chapter5/2-overrideCollectionTableColumn/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter5/2-overrideCollectionTableColumn/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter5/2-overrideCollectionTableColumn/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/2-overrideCollectionTableColumn/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..a707a8b --- /dev/null +++ b/examples/Chapter5/2-overrideCollectionTableColumn/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,13 @@ + + + jdbc/elementCollectionOverride + NONE + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/2-overrideCollectionTableColumn/etc/sql/db.sql b/examples/Chapter5/2-overrideCollectionTableColumn/etc/sql/db.sql new file mode 100644 index 0000000..41c4e99 --- /dev/null +++ b/examples/Chapter5/2-overrideCollectionTableColumn/etc/sql/db.sql @@ -0,0 +1,6 @@ +DROP TABLE Employee_VACATION; +DROP TABLE Employee_NICKNAMES; +DROP TABLE EMPLOYEE; +CREATE TABLE EMPLOYEE (ID INTEGER GENERATED ALWAYS AS IDENTITY NOT NULL, NAME VARCHAR(255), SALARY BIGINT, PRIMARY KEY (ID)); +CREATE TABLE Employee_VACATION (EMP_ID INTEGER NOT NULL, STARTDATE VARCHAR(255), DAYS_ABS INTEGER); +CREATE TABLE Employee_NICKNAMES (Employee_ID INTEGER NOT NULL, NICKNAME VARCHAR(255)); diff --git a/examples/Chapter5/2-overrideCollectionTableColumn/etc/web/WEB-INF/web.xml b/examples/Chapter5/2-overrideCollectionTableColumn/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter5/2-overrideCollectionTableColumn/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter5/2-overrideCollectionTableColumn/src/model/examples/model/Employee.java b/examples/Chapter5/2-overrideCollectionTableColumn/src/model/examples/model/Employee.java new file mode 100644 index 0000000..f5e2092 --- /dev/null +++ b/examples/Chapter5/2-overrideCollectionTableColumn/src/model/examples/model/Employee.java @@ -0,0 +1,82 @@ +package examples.model; + +import java.util.Collection; +import java.util.Set; + +import javax.persistence.AttributeOverride; +import javax.persistence.CollectionTable; +import javax.persistence.Column; +import javax.persistence.ElementCollection; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; + +@Entity +public class Employee { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + private long salary; + + // Using a targetClass instead of generics + @ElementCollection(targetClass=VacationEntry.class) + @CollectionTable(name="VACATION", + joinColumns=@JoinColumn(name="EMP_ID")) + @AttributeOverride(name="daysTaken", + column=@Column(name="DAYS_ABS")) + private Collection vacationBookings; + + // Using generics in place of a targetClass + @ElementCollection + @Column(name="NICKNAME") + private Set nickNames; + + public Collection getVacationBookings() { + return vacationBookings; + } + + public void setVacationBookings(Collection vacationBookings) { + this.vacationBookings = vacationBookings; + } + + public Set getNickNames() { + return nickNames; + } + + public void setNickNames(Set nickNames) { + this.nickNames = nickNames; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " salary: " + getSalary() + + " nickNames: " + nickNames; + } +} diff --git a/examples/Chapter5/2-overrideCollectionTableColumn/src/model/examples/model/VacationEntry.java b/examples/Chapter5/2-overrideCollectionTableColumn/src/model/examples/model/VacationEntry.java new file mode 100644 index 0000000..c9607ab --- /dev/null +++ b/examples/Chapter5/2-overrideCollectionTableColumn/src/model/examples/model/VacationEntry.java @@ -0,0 +1,41 @@ +package examples.model; + +import java.util.Calendar; + +import javax.persistence.Column; +import javax.persistence.Embeddable; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Embeddable +public class VacationEntry { + @Temporal(TemporalType.DATE) + private Calendar startDate; + @Column(name="DAYS") + private int daysTaken; + + public VacationEntry() {} + + public VacationEntry(Calendar aStartDate, int daysTakenInt) { + startDate = aStartDate; + daysTaken = daysTakenInt; + } + + public Calendar getStartDate() { + return startDate; + } + public void setStartDate(Calendar startDate) { + this.startDate = startDate; + } + public int getDaysTaken() { + return daysTaken; + } + public void setDaysTaken(int daysTaken) { + this.daysTaken = daysTaken; + } + + public String toString() { + return "VacationEntry startDate: " + getStartDate().getTime() + + ", daysTaken: " + getDaysTaken(); + } +} \ No newline at end of file diff --git a/examples/Chapter5/2-overrideCollectionTableColumn/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/2-overrideCollectionTableColumn/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..a333a14 --- /dev/null +++ b/examples/Chapter5/2-overrideCollectionTableColumn/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(String name, long salary); + public Employee addEmployeeNickname(int empId, String nickname); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter5/2-overrideCollectionTableColumn/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/2-overrideCollectionTableColumn/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..f5115fd --- /dev/null +++ b/examples/Chapter5/2-overrideCollectionTableColumn/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,48 @@ +package examples.stateless; + +import java.util.Collection; +import java.util.GregorianCalendar; +import java.util.HashSet; +import java.util.Set; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Employee; +import examples.model.VacationEntry; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String name, long salary) { + Employee emp = new Employee(); + emp.setName(name); + emp.setSalary(salary); + + em.persist(emp); + return emp; + } + + public Employee addEmployeeNickname(int empId, String nickname) { + Employee emp = em.find(Employee.class, empId); + if (emp != null) { + emp.getNickNames().add(nickname); + } + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + Collection emps = (Collection) query.getResultList(); + // trigger lazy collections + for (Employee emp : emps) { + emp.getVacationBookings().size(); + emp.getNickNames().size(); + } + return emps; + } +} diff --git a/examples/Chapter5/2-overrideCollectionTableColumn/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter5/2-overrideCollectionTableColumn/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..d66d3e2 --- /dev/null +++ b/examples/Chapter5/2-overrideCollectionTableColumn/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,121 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 5: Overriding ElementCollection Tables and Columns Example"; + + private final String DESCRIPTION = + "This example demonstrates how to override the mapping information for an ElementCollection.
"; + + + @EJB EmployeeService empService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("CreateEmp")) { + Employee emp = empService.createEmployee( + request.getParameter("empName"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("AddNickname")) { + Employee emp = empService.addEmployeeNickname( + parseInt(request.getParameter("id")), + request.getParameter("nickname")); + if (emp != null) { + out.println("Added nickname to Employee " + emp); + } + } else if (action.equals("FindAll")) { + Collection emps = empService.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + + out.println("
"); + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create Employee + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
Employee Salary:(long)
"); + out.println("
"); + // form to Add a nickname + out.println("

Add a Nickname

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
Nickname:(String)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter5/2-overrideCollectionTableColumn/undeploy.bat b/examples/Chapter5/2-overrideCollectionTableColumn/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter5/2-overrideCollectionTableColumn/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter5/3-oneToManyList/build.xml b/examples/Chapter5/3-oneToManyList/build.xml new file mode 100644 index 0000000..4cff465 --- /dev/null +++ b/examples/Chapter5/3-oneToManyList/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/3-oneToManyList/deploy.bat b/examples/Chapter5/3-oneToManyList/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter5/3-oneToManyList/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter5/3-oneToManyList/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/3-oneToManyList/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..4e42995 --- /dev/null +++ b/examples/Chapter5/3-oneToManyList/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,13 @@ + + + jdbc/oneToManyList + NONE + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/3-oneToManyList/etc/sql/db.sql b/examples/Chapter5/3-oneToManyList/etc/sql/db.sql new file mode 100644 index 0000000..34bfa60 --- /dev/null +++ b/examples/Chapter5/3-oneToManyList/etc/sql/db.sql @@ -0,0 +1,9 @@ +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + NAME VARCHAR(255), SALARY BIGINT, + DEPARTMENT_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID)); + diff --git a/examples/Chapter5/3-oneToManyList/etc/web/WEB-INF/web.xml b/examples/Chapter5/3-oneToManyList/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter5/3-oneToManyList/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter5/3-oneToManyList/src/model/examples/model/Department.java b/examples/Chapter5/3-oneToManyList/src/model/examples/model/Department.java new file mode 100644 index 0000000..69b73a4 --- /dev/null +++ b/examples/Chapter5/3-oneToManyList/src/model/examples/model/Department.java @@ -0,0 +1,70 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import javax.persistence.OrderBy; + +@Entity +public class Department { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + @OneToMany(mappedBy="department") + @OrderBy("name ASC") + private List employees; + + public Department() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String deptName) { + this.name = deptName; + } + + public void addEmployee(Employee employee) { + // Need to add it in the correct position to maintain the order + int initialSize = employees.size(); + if (!employees.contains(employee)) { + for (int i=0; i < initialSize; i++) { + if (employees.get(i).getName().compareTo(employee.getName()) > 0) { + employees.add(i, employee); + break; + } + } + if (employees.size() == initialSize) { + employees.add(employee); + } + if (employee.getDepartment() != null) { + employee.getDepartment().getEmployees().remove(employee); + } + employee.setDepartment(this); + } + } + + public List getEmployees() { + return employees; + } + + public String toString() { + return "Department id: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter5/3-oneToManyList/src/model/examples/model/Employee.java b/examples/Chapter5/3-oneToManyList/src/model/examples/model/Employee.java new file mode 100644 index 0000000..e161138 --- /dev/null +++ b/examples/Chapter5/3-oneToManyList/src/model/examples/model/Employee.java @@ -0,0 +1,55 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@Entity +public class Employee { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + private long salary; + + @ManyToOne + private Department department; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " with " + getDepartment(); + } +} diff --git a/examples/Chapter5/3-oneToManyList/src/model/examples/stateless/DepartmentService.java b/examples/Chapter5/3-oneToManyList/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..7003e8d --- /dev/null +++ b/examples/Chapter5/3-oneToManyList/src/model/examples/stateless/DepartmentService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Department; + +public interface DepartmentService { + public Department createDepartment(String name); + public Collection findAllDepartments(); +} diff --git a/examples/Chapter5/3-oneToManyList/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter5/3-oneToManyList/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..7d47cb1 --- /dev/null +++ b/examples/Chapter5/3-oneToManyList/src/model/examples/stateless/DepartmentServiceBean.java @@ -0,0 +1,29 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; + +@Stateless +public class DepartmentServiceBean implements DepartmentService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Department createDepartment(String name) { + Department dept = new Department(); + dept.setName(name); + em.persist(dept); + + return dept; + } + + public Collection findAllDepartments() { + Query query = em.createQuery("SELECT d FROM Department d"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter5/3-oneToManyList/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/3-oneToManyList/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..84116f6 --- /dev/null +++ b/examples/Chapter5/3-oneToManyList/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(String name, long salary); + public Employee setEmployeeDepartment(int empId, int deptId); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter5/3-oneToManyList/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/3-oneToManyList/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..3a28921 --- /dev/null +++ b/examples/Chapter5/3-oneToManyList/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,38 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String name, long salary) { + Employee emp = new Employee(); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + + return emp; + } + + public Employee setEmployeeDepartment(int empId, int deptId) { + Employee emp = em.find(Employee.class, empId); + Department dept = em.find(Department.class, deptId); + dept.addEmployee(emp); + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter5/3-oneToManyList/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter5/3-oneToManyList/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..f25847c --- /dev/null +++ b/examples/Chapter5/3-oneToManyList/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,144 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Department; +import examples.model.Employee; +import examples.stateless.DepartmentService; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 5: One-to-Many List Example"; + + private final String DESCRIPTION = + "This example demonstates how to specify one-to-many bidirectional relationships using a List.
"; + + @EJB EmployeeService empService; + @EJB DepartmentService deptService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("CreateEmp")) { + Employee emp = empService.createEmployee( + request.getParameter("empName"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("CreateDept")) { + Department dept = deptService.createDepartment( + request.getParameter("deptName")); + out.println("Created " + dept); + } else if (action.equals("SetEmployeeDept")) { + Employee emp = empService.setEmployeeDepartment( + parseInt(request.getParameter("empId")), + parseInt(request.getParameter("deptId"))); + out.println("Updated " + emp + "
"); + out.println(emp.getDepartment() + " with Employees:
"); + out.println(emp.getDepartment().getEmployees()); + } else if (action.equals("FindAll")) { + Collection emps = empService.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + + out.println("
"); + Collection depts = deptService.findAllDepartments(); + if (depts.isEmpty()) { + out.println("No Departments found "); + } else { + out.println("Found Departments:
"); + for (Department dept : depts) { + out.println(dept + " with " + dept.getEmployees().size() + " employees
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Department + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
Employee Salary:(long)
"); + + out.println("
"); + out.println("

Create a Department

"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Dept Name:(String)
"); + + out.println("
"); + out.println("

Set an Employee's Department

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Emp Id:(int)
Dept Id:(int)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees & Departments

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter5/3-oneToManyList/undeploy.bat b/examples/Chapter5/3-oneToManyList/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter5/3-oneToManyList/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter5/4-persistentlyOrderedList/build.xml b/examples/Chapter5/4-persistentlyOrderedList/build.xml new file mode 100644 index 0000000..5c71896 --- /dev/null +++ b/examples/Chapter5/4-persistentlyOrderedList/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/4-persistentlyOrderedList/deploy.bat b/examples/Chapter5/4-persistentlyOrderedList/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter5/4-persistentlyOrderedList/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter5/4-persistentlyOrderedList/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/4-persistentlyOrderedList/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..26b5e14 --- /dev/null +++ b/examples/Chapter5/4-persistentlyOrderedList/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,13 @@ + + + jdbc/persistentlyOrderedList + NONE + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/4-persistentlyOrderedList/etc/sql/db.sql b/examples/Chapter5/4-persistentlyOrderedList/etc/sql/db.sql new file mode 100644 index 0000000..6cb4cfa --- /dev/null +++ b/examples/Chapter5/4-persistentlyOrderedList/etc/sql/db.sql @@ -0,0 +1,5 @@ +DROP TABLE PRINTJOB; +DROP TABLE PRINTQUEUE; +CREATE TABLE PRINTJOB (ID INTEGER, QUEUE_NAME VARCHAR(255), PRINT_ORDER INTEGER, PRIMARY KEY (ID)); +CREATE TABLE PRINTQUEUE (NAME VARCHAR(255), PRIMARY KEY (NAME)); +ALTER TABLE PRINTJOB ADD CONSTRAINT JOB_QUEUE FOREIGN KEY (QUEUE_NAME) REFERENCES PRINTQUEUE (NAME); \ No newline at end of file diff --git a/examples/Chapter5/4-persistentlyOrderedList/etc/web/WEB-INF/web.xml b/examples/Chapter5/4-persistentlyOrderedList/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..b7c0c82 --- /dev/null +++ b/examples/Chapter5/4-persistentlyOrderedList/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + PrinterServlet + examples.servlet.PrinterServlet + + + + PrinterServlet + /PrinterServlet + + \ No newline at end of file diff --git a/examples/Chapter5/4-persistentlyOrderedList/src/model/examples/model/PrintJob.java b/examples/Chapter5/4-persistentlyOrderedList/src/model/examples/model/PrintJob.java new file mode 100644 index 0000000..90115bb --- /dev/null +++ b/examples/Chapter5/4-persistentlyOrderedList/src/model/examples/model/PrintJob.java @@ -0,0 +1,29 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@Entity +public class PrintJob { + @Id private int id; + + @ManyToOne + private PrintQueue queue; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public PrintQueue getQueue() { + return queue; + } + + public void setQueue(PrintQueue queue) { + this.queue = queue; + } +} \ No newline at end of file diff --git a/examples/Chapter5/4-persistentlyOrderedList/src/model/examples/model/PrintQueue.java b/examples/Chapter5/4-persistentlyOrderedList/src/model/examples/model/PrintQueue.java new file mode 100644 index 0000000..f3478d7 --- /dev/null +++ b/examples/Chapter5/4-persistentlyOrderedList/src/model/examples/model/PrintQueue.java @@ -0,0 +1,43 @@ +package examples.model; + +import java.util.List; +import java.util.ArrayList; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import javax.persistence.OrderColumn; + +@Entity +public class PrintQueue { + @Id private String name; + + @OneToMany(mappedBy="queue") + @OrderColumn(name="PRINT_ORDER") + private List jobs; + + public PrintQueue() { + jobs = new ArrayList(); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getJobs() { + return jobs; + } + + public void addJob(PrintJob job) { + this.jobs.add(job); + job.setQueue(this); + } + + public String toString() { + return "PrintQueue: " + name; + } +} diff --git a/examples/Chapter5/4-persistentlyOrderedList/src/model/examples/stateless/PrintService.java b/examples/Chapter5/4-persistentlyOrderedList/src/model/examples/stateless/PrintService.java new file mode 100644 index 0000000..7d82b27 --- /dev/null +++ b/examples/Chapter5/4-persistentlyOrderedList/src/model/examples/stateless/PrintService.java @@ -0,0 +1,14 @@ +package examples.stateless; + +import java.util.List; + +import examples.model.PrintJob; +import examples.model.PrintQueue; + +public interface PrintService { + public PrintQueue createPrinter(String name); + public PrintJob createPrintJob(int jobId, String queueName); + public PrintJob removePrintJob(int jobId, String queueName); + public List listAllPrintQueues(); + public List listAllJobs(String queueName); +} diff --git a/examples/Chapter5/4-persistentlyOrderedList/src/model/examples/stateless/PrintServiceBean.java b/examples/Chapter5/4-persistentlyOrderedList/src/model/examples/stateless/PrintServiceBean.java new file mode 100644 index 0000000..8ffdfe6 --- /dev/null +++ b/examples/Chapter5/4-persistentlyOrderedList/src/model/examples/stateless/PrintServiceBean.java @@ -0,0 +1,73 @@ +package examples.stateless; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.PrintJob; +import examples.model.PrintQueue; + +@Stateless +public class PrintServiceBean implements PrintService { + @PersistenceContext(unitName="PrintService") + protected EntityManager em; + + public PrintQueue createPrinter(String name) { + if (em.find(PrintQueue.class, name) != null) + return null; + PrintQueue q = new PrintQueue(); + q.setName(name); + em.persist(q); + return q; + } + + public PrintJob createPrintJob(int jobId, String queueName) { + PrintJob job = null; + PrintQueue q = em.find(PrintQueue.class, queueName); + if (q != null) { + job = new PrintJob(); + job.setId(jobId); + q.addJob(job); + em.persist(job); + } + return job; + } + + public PrintJob removePrintJob(int jobId, String queueName) { + PrintJob job = null; + PrintQueue q = em.find(PrintQueue.class, queueName); + if (q != null) { + Iterator iter = q.getJobs().iterator(); + while (iter.hasNext()) { + PrintJob current = (PrintJob) iter.next(); + if (current.getId() == jobId) { + job = current; + iter.remove(); + job.setQueue(null); + em.remove(job); + } + } + } + return job; + } + + public List listAllPrintQueues() { + return em.createQuery("SELECT p FROM PrintQueue p").getResultList(); + } + + public List listAllJobs(String queueName) { + PrintQueue q = em.find(PrintQueue.class, queueName); + if (q != null) { + // trigger loading before returning + q.getJobs().size(); + return q.getJobs(); + } else { + return new ArrayList(); + } + } +} diff --git a/examples/Chapter5/4-persistentlyOrderedList/src/servlet/examples/servlet/PrinterServlet.java b/examples/Chapter5/4-persistentlyOrderedList/src/servlet/examples/servlet/PrinterServlet.java new file mode 100644 index 0000000..362a8fc --- /dev/null +++ b/examples/Chapter5/4-persistentlyOrderedList/src/servlet/examples/servlet/PrinterServlet.java @@ -0,0 +1,149 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.List; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.PrintQueue; +import examples.model.PrintJob; +import examples.stateless.PrintService; + +public class PrinterServlet extends HttpServlet { + + private final String TITLE = + "Chapter 5: Persistently Ordered List Example"; + + private final String DESCRIPTION = + "This example demonstrates how to work with Lists that maintain their order in the database.
"; + + @EJB PrintService printService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("CreatePrinter")) { + PrintQueue printer = printService.createPrinter( + request.getParameter("pName")); + out.println("Created " + printer); + } else if (action.equals("AddToQueue")) { + PrintJob job = printService.createPrintJob( + parseInt(request.getParameter("jobId")), + request.getParameter("schedName")); + if (job != null) + out.println("Sent job " + job.getId() + " to printer queue " + job.getQueue().getName()); + } else if (action.equals("CancelFromQueue")) { + PrintJob job = printService.removePrintJob( + parseInt(request.getParameter("xjobId")), + request.getParameter("cancelName")); + out.println("Removed job " + job.getId() + " from printer queue " + request.getParameter("cancelName")); + } else if (action.equals("ListQueues")) { + List queues = printService.listAllPrintQueues(); + if (queues.isEmpty()) { + out.println("No printers"); + } else { + out.println("Printers:
"); + for (PrintQueue q : queues) { + out.println("Print Queue: " + q.getName() + "
"); + } + } + out.println("
"); + } else if (action.equals("ListJobs")) { + List jobs = printService.listAllJobs( + request.getParameter("listName")); + if (jobs.isEmpty()) { + out.println("No jobs queued "); + } else { + out.println("Jobs queued:
"); + for (PrintJob job : jobs) { + out.println("Job " + job.getId() + "
"); + } + } + out.println("
"); + } + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create a Printer + out.println("

Create a Printer

"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Printer Name:(String)
"); + out.println("
"); + // form to enqueue a job + out.println("

Schedule Print Job

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Job Id:(int)
Printer Name:(String)
"); + out.println("
"); + // form to cancel a job + out.println("

Cancel Print Job

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Job Id:(int)
Printer Name:(String)
"); + out.println("
"); + // form to list queues + out.println("

List all Print Queues

"); + out.println(""); + out.println(""); + out.println("
"); + out.println("
"); + // form to find jobs + out.println("

List all Jobs in a Queue

"); + out.println("Printer Name:(String)"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter5/4-persistentlyOrderedList/undeploy.bat b/examples/Chapter5/4-persistentlyOrderedList/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter5/4-persistentlyOrderedList/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter5/5-elementCollectionStringMap/build.xml b/examples/Chapter5/5-elementCollectionStringMap/build.xml new file mode 100644 index 0000000..879943a --- /dev/null +++ b/examples/Chapter5/5-elementCollectionStringMap/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/5-elementCollectionStringMap/deploy.bat b/examples/Chapter5/5-elementCollectionStringMap/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter5/5-elementCollectionStringMap/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter5/5-elementCollectionStringMap/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/5-elementCollectionStringMap/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..d17e625 --- /dev/null +++ b/examples/Chapter5/5-elementCollectionStringMap/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/elementCollectionStringMap + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/5-elementCollectionStringMap/etc/sql/db.sql b/examples/Chapter5/5-elementCollectionStringMap/etc/sql/db.sql new file mode 100644 index 0000000..7d91ac3 --- /dev/null +++ b/examples/Chapter5/5-elementCollectionStringMap/etc/sql/db.sql @@ -0,0 +1,8 @@ +DROP TABLE EMP_PHONE; +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; +CREATE TABLE EMP_PHONE (Employee_ID INTEGER NOT NULL, PHONE_NUM VARCHAR(255), PHONE_TYPE VARCHAR(255)); +CREATE TABLE EMPLOYEE (ID INTEGER GENERATED ALWAYS AS IDENTITY NOT NULL, NAME VARCHAR(255), SALARY BIGINT, DEPARTMENT_ID INTEGER, PRIMARY KEY (ID)); +CREATE TABLE DEPARTMENT (ID INTEGER GENERATED ALWAYS AS IDENTITY NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +ALTER TABLE EMP_PHONE ADD CONSTRAINT EMPPHONEID FOREIGN KEY (Employee_ID) REFERENCES EMPLOYEE (ID); +ALTER TABLE EMPLOYEE ADD CONSTRAINT MPLOYEEDPARTMENTID FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID); diff --git a/examples/Chapter5/5-elementCollectionStringMap/etc/web/WEB-INF/web.xml b/examples/Chapter5/5-elementCollectionStringMap/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter5/5-elementCollectionStringMap/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter5/5-elementCollectionStringMap/src/model/examples/model/Department.java b/examples/Chapter5/5-elementCollectionStringMap/src/model/examples/model/Department.java new file mode 100644 index 0000000..a48d835 --- /dev/null +++ b/examples/Chapter5/5-elementCollectionStringMap/src/model/examples/model/Department.java @@ -0,0 +1,68 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +import javax.persistence.OneToMany; +import javax.persistence.OrderBy; + +@Entity +public class Department { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + + @OneToMany(mappedBy="department") + @OrderBy("name ASC") + private List employees; + + public Department() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String deptName) { + this.name = deptName; + } + + public void addEmployee(Employee employee) { + getEmployees().add( employee); + if (employee.getDepartment() != null) { + employee.getDepartment().getEmployees().remove(employee.getName()); + } + employee.setDepartment(this); + } + + public List getEmployees() { + return employees; + } + + public String toString() { + StringBuffer aBuffer = new StringBuffer("Department "); + aBuffer.append(" id: "); + aBuffer.append(id); + aBuffer.append(" name: "); + aBuffer.append(name); + aBuffer.append(" employeeCount: "); + if(null != employees) { + aBuffer.append(employees.size()); + } + return aBuffer.toString(); + } +} \ No newline at end of file diff --git a/examples/Chapter5/5-elementCollectionStringMap/src/model/examples/model/Employee.java b/examples/Chapter5/5-elementCollectionStringMap/src/model/examples/model/Employee.java new file mode 100644 index 0000000..edd408b --- /dev/null +++ b/examples/Chapter5/5-elementCollectionStringMap/src/model/examples/model/Employee.java @@ -0,0 +1,86 @@ +package examples.model; + +import java.util.Map; + +import javax.persistence.CollectionTable; +import javax.persistence.Column; +import javax.persistence.ElementCollection; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import javax.persistence.MapKeyColumn; + +@Entity +public class Employee { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + private long salary; + + @ElementCollection + @CollectionTable(name="EMP_PHONE") + @MapKeyColumn(name="PHONE_TYPE") + @Column(name="PHONE_NUM") + private Map phoneNumbers; + + @ManyToOne + private Department department; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + public Map getPhoneNumbers() { + return phoneNumbers; + } + + public void setPhoneNumbers(Map phoneNumbers) { + this.phoneNumbers = phoneNumbers; + } + + public String toString() { + StringBuffer aBuffer = new StringBuffer("Employee "); + aBuffer.append(" id: "); + aBuffer.append(id); + aBuffer.append(" with dept: "); + if(null != department) { + aBuffer.append(department.getName()); + } + aBuffer.append(" phoneNumbers: "); + for (Map.Entry e : phoneNumbers.entrySet()) { + aBuffer.append(e.getKey() + "[" + e.getValue() + "] "); + } + return aBuffer.toString(); + } +} \ No newline at end of file diff --git a/examples/Chapter5/5-elementCollectionStringMap/src/model/examples/stateless/DepartmentService.java b/examples/Chapter5/5-elementCollectionStringMap/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..7003e8d --- /dev/null +++ b/examples/Chapter5/5-elementCollectionStringMap/src/model/examples/stateless/DepartmentService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Department; + +public interface DepartmentService { + public Department createDepartment(String name); + public Collection findAllDepartments(); +} diff --git a/examples/Chapter5/5-elementCollectionStringMap/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter5/5-elementCollectionStringMap/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..7d47cb1 --- /dev/null +++ b/examples/Chapter5/5-elementCollectionStringMap/src/model/examples/stateless/DepartmentServiceBean.java @@ -0,0 +1,29 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; + +@Stateless +public class DepartmentServiceBean implements DepartmentService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Department createDepartment(String name) { + Department dept = new Department(); + dept.setName(name); + em.persist(dept); + + return dept; + } + + public Collection findAllDepartments() { + Query query = em.createQuery("SELECT d FROM Department d"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter5/5-elementCollectionStringMap/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/5-elementCollectionStringMap/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..84116f6 --- /dev/null +++ b/examples/Chapter5/5-elementCollectionStringMap/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(String name, long salary); + public Employee setEmployeeDepartment(int empId, int deptId); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter5/5-elementCollectionStringMap/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/5-elementCollectionStringMap/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..22d669e --- /dev/null +++ b/examples/Chapter5/5-elementCollectionStringMap/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,55 @@ +package examples.stateless; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.List; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String name, long salary) { + Employee emp = new Employee(); + emp.setName(name); + emp.setSalary(salary); + Map phoneMap = new HashMap(); + phoneMap.put("home","613-289-3214"); + phoneMap.put("mobile","613-760-2332"); + emp.setPhoneNumbers(phoneMap); + em.persist(emp); + return emp; + } + + public Employee setEmployeeDepartment(int empId, int deptId) { + Employee emp = em.find(Employee.class, empId); + Department dept = em.find(Department.class, deptId); + dept.addEmployee(emp); + emp.setDepartment(dept); + // trigger indirection + emp.getPhoneNumbers().size(); + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + Collection aCollection = (Collection) query.getResultList(); + // trigger indirection + for(Employee anEmployee : aCollection) { + anEmployee.getPhoneNumbers().size(); + } + return aCollection; + } +} diff --git a/examples/Chapter5/5-elementCollectionStringMap/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter5/5-elementCollectionStringMap/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..307da26 --- /dev/null +++ b/examples/Chapter5/5-elementCollectionStringMap/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,144 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Department; +import examples.model.Employee; +import examples.stateless.DepartmentService; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 5: ElementCollection Map of Strings Example"; + + private final String DESCRIPTION = + "This example demonstrates how to work with ElementCollections that are Maps.
" + + "The Map contains String keys and String values."; + + + @EJB EmployeeService empService; + @EJB DepartmentService deptService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("CreateEmp")) { + Employee emp = empService.createEmployee( + request.getParameter("empName"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("CreateDept")) { + Department dept = deptService.createDepartment( + request.getParameter("deptName")); + out.println("Created " + dept); + } else if (action.equals("SetEmployeeDept")) { + Employee emp = empService.setEmployeeDepartment( + parseInt(request.getParameter("empId")), + parseInt(request.getParameter("deptId"))); + out.println("Updated " + emp + "
"); + out.println(emp.getDepartment() + " with Employees:
"); + out.println(emp.getDepartment().getEmployees()); + } else if (action.equals("FindAll")) { + Collection emps = empService.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + + out.println("
"); + Collection depts = deptService.findAllDepartments(); + if (depts.isEmpty()) { + out.println("No Departments found "); + } else { + out.println("Found Departments:
"); + for (Department dept : depts) { + out.println(dept + " with " + dept.getEmployees().size() + + " employees " + dept.getEmployees() + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Department + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
Employee Salary:(long)
"); + out.println("
"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Dept Name:(String)
"); + out.println("
"); + + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Emp Id:(int)
Dept Id:(int)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees & Departments

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter5/5-elementCollectionStringMap/undeploy.bat b/examples/Chapter5/5-elementCollectionStringMap/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter5/5-elementCollectionStringMap/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter5/6-elementCollectionEnumMap/build.xml b/examples/Chapter5/6-elementCollectionEnumMap/build.xml new file mode 100644 index 0000000..5354e82 --- /dev/null +++ b/examples/Chapter5/6-elementCollectionEnumMap/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/6-elementCollectionEnumMap/deploy.bat b/examples/Chapter5/6-elementCollectionEnumMap/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter5/6-elementCollectionEnumMap/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter5/6-elementCollectionEnumMap/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/6-elementCollectionEnumMap/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..ba680b7 --- /dev/null +++ b/examples/Chapter5/6-elementCollectionEnumMap/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,13 @@ + + + jdbc/elementCollectionEnumMap + NONE + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/6-elementCollectionEnumMap/etc/sql/db.sql b/examples/Chapter5/6-elementCollectionEnumMap/etc/sql/db.sql new file mode 100644 index 0000000..7d91ac3 --- /dev/null +++ b/examples/Chapter5/6-elementCollectionEnumMap/etc/sql/db.sql @@ -0,0 +1,8 @@ +DROP TABLE EMP_PHONE; +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; +CREATE TABLE EMP_PHONE (Employee_ID INTEGER NOT NULL, PHONE_NUM VARCHAR(255), PHONE_TYPE VARCHAR(255)); +CREATE TABLE EMPLOYEE (ID INTEGER GENERATED ALWAYS AS IDENTITY NOT NULL, NAME VARCHAR(255), SALARY BIGINT, DEPARTMENT_ID INTEGER, PRIMARY KEY (ID)); +CREATE TABLE DEPARTMENT (ID INTEGER GENERATED ALWAYS AS IDENTITY NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +ALTER TABLE EMP_PHONE ADD CONSTRAINT EMPPHONEID FOREIGN KEY (Employee_ID) REFERENCES EMPLOYEE (ID); +ALTER TABLE EMPLOYEE ADD CONSTRAINT MPLOYEEDPARTMENTID FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID); diff --git a/examples/Chapter5/6-elementCollectionEnumMap/etc/web/WEB-INF/web.xml b/examples/Chapter5/6-elementCollectionEnumMap/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter5/6-elementCollectionEnumMap/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter5/6-elementCollectionEnumMap/src/model/examples/model/Department.java b/examples/Chapter5/6-elementCollectionEnumMap/src/model/examples/model/Department.java new file mode 100644 index 0000000..a48d835 --- /dev/null +++ b/examples/Chapter5/6-elementCollectionEnumMap/src/model/examples/model/Department.java @@ -0,0 +1,68 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +import javax.persistence.OneToMany; +import javax.persistence.OrderBy; + +@Entity +public class Department { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + + @OneToMany(mappedBy="department") + @OrderBy("name ASC") + private List employees; + + public Department() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String deptName) { + this.name = deptName; + } + + public void addEmployee(Employee employee) { + getEmployees().add( employee); + if (employee.getDepartment() != null) { + employee.getDepartment().getEmployees().remove(employee.getName()); + } + employee.setDepartment(this); + } + + public List getEmployees() { + return employees; + } + + public String toString() { + StringBuffer aBuffer = new StringBuffer("Department "); + aBuffer.append(" id: "); + aBuffer.append(id); + aBuffer.append(" name: "); + aBuffer.append(name); + aBuffer.append(" employeeCount: "); + if(null != employees) { + aBuffer.append(employees.size()); + } + return aBuffer.toString(); + } +} \ No newline at end of file diff --git a/examples/Chapter5/6-elementCollectionEnumMap/src/model/examples/model/Employee.java b/examples/Chapter5/6-elementCollectionEnumMap/src/model/examples/model/Employee.java new file mode 100644 index 0000000..d93f98b --- /dev/null +++ b/examples/Chapter5/6-elementCollectionEnumMap/src/model/examples/model/Employee.java @@ -0,0 +1,90 @@ +package examples.model; + +import java.util.Map; + +import javax.persistence.CollectionTable; +import javax.persistence.Column; +import javax.persistence.ElementCollection; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import javax.persistence.MapKeyColumn; +import javax.persistence.MapKeyEnumerated; + + +@Entity +public class Employee { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + private long salary; + + @ElementCollection + @CollectionTable(name="EMP_PHONE") + @MapKeyEnumerated(EnumType.STRING) + @MapKeyColumn(name="PHONE_TYPE") + @Column(name="PHONE_NUM") + private Map phoneNumbers; + + @ManyToOne + private Department department; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + public Map getPhoneNumbers() { + return phoneNumbers; + } + + public void setPhoneNumbers(Map phoneNumbers) { + this.phoneNumbers = phoneNumbers; + } + + public String toString() { + StringBuffer aBuffer = new StringBuffer("Employee "); + aBuffer.append(" id: "); + aBuffer.append(id); + aBuffer.append(" with dept: "); + if(null != department) { + aBuffer.append(department.getName()); + } + aBuffer.append(" phoneNumbers: "); + for (Map.Entry e : phoneNumbers.entrySet()) { + aBuffer.append(e.getKey().toString() + "[" + e.getValue() + "] "); + } + return aBuffer.toString(); + } +} \ No newline at end of file diff --git a/examples/Chapter5/6-elementCollectionEnumMap/src/model/examples/model/PhoneType.java b/examples/Chapter5/6-elementCollectionEnumMap/src/model/examples/model/PhoneType.java new file mode 100644 index 0000000..9f1a1cd --- /dev/null +++ b/examples/Chapter5/6-elementCollectionEnumMap/src/model/examples/model/PhoneType.java @@ -0,0 +1,5 @@ +package examples.model; + +public enum PhoneType { + Home, Mobile, Work +} diff --git a/examples/Chapter5/6-elementCollectionEnumMap/src/model/examples/stateless/DepartmentService.java b/examples/Chapter5/6-elementCollectionEnumMap/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..7003e8d --- /dev/null +++ b/examples/Chapter5/6-elementCollectionEnumMap/src/model/examples/stateless/DepartmentService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Department; + +public interface DepartmentService { + public Department createDepartment(String name); + public Collection findAllDepartments(); +} diff --git a/examples/Chapter5/6-elementCollectionEnumMap/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter5/6-elementCollectionEnumMap/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..7d47cb1 --- /dev/null +++ b/examples/Chapter5/6-elementCollectionEnumMap/src/model/examples/stateless/DepartmentServiceBean.java @@ -0,0 +1,29 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; + +@Stateless +public class DepartmentServiceBean implements DepartmentService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Department createDepartment(String name) { + Department dept = new Department(); + dept.setName(name); + em.persist(dept); + + return dept; + } + + public Collection findAllDepartments() { + Query query = em.createQuery("SELECT d FROM Department d"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter5/6-elementCollectionEnumMap/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/6-elementCollectionEnumMap/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..84116f6 --- /dev/null +++ b/examples/Chapter5/6-elementCollectionEnumMap/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(String name, long salary); + public Employee setEmployeeDepartment(int empId, int deptId); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter5/6-elementCollectionEnumMap/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/6-elementCollectionEnumMap/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..85a2fb2 --- /dev/null +++ b/examples/Chapter5/6-elementCollectionEnumMap/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,56 @@ +package examples.stateless; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.List; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; +import examples.model.Employee; +import examples.model.PhoneType; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String name, long salary) { + Employee emp = new Employee(); + emp.setName(name); + emp.setSalary(salary); + Map phoneMap = new HashMap(); + phoneMap.put(PhoneType.Home,"613-289-3214"); + phoneMap.put(PhoneType.Mobile,"613-760-2332"); + emp.setPhoneNumbers(phoneMap); + em.persist(emp); + return emp; + } + + public Employee setEmployeeDepartment(int empId, int deptId) { + Employee emp = em.find(Employee.class, empId); + Department dept = em.find(Department.class, deptId); + dept.addEmployee(emp); + emp.setDepartment(dept); + // trigger indirection + emp.getPhoneNumbers().size(); + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + Collection aCollection = (Collection) query.getResultList(); + // trigger indirection + for(Employee anEmployee : aCollection) { + anEmployee.getPhoneNumbers().size(); + } + return aCollection; + } +} diff --git a/examples/Chapter5/6-elementCollectionEnumMap/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter5/6-elementCollectionEnumMap/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..424e17a --- /dev/null +++ b/examples/Chapter5/6-elementCollectionEnumMap/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,144 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Department; +import examples.model.Employee; +import examples.stateless.DepartmentService; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 5: ElementCollection Map Keyed by Enumerated Type Example"; + + private final String DESCRIPTION = + "This example demonstrates how to work with ElementCollections that are Maps.
" + + "The Map contains keys that are of an enumerated type and String values."; + + + @EJB EmployeeService empService; + @EJB DepartmentService deptService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("CreateEmp")) { + Employee emp = empService.createEmployee( + request.getParameter("empName"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("CreateDept")) { + Department dept = deptService.createDepartment( + request.getParameter("deptName")); + out.println("Created " + dept); + } else if (action.equals("SetEmployeeDept")) { + Employee emp = empService.setEmployeeDepartment( + parseInt(request.getParameter("empId")), + parseInt(request.getParameter("deptId"))); + out.println("Updated " + emp + "
"); + out.println(emp.getDepartment() + " with Employees:
"); + out.println(emp.getDepartment().getEmployees()); + } else if (action.equals("FindAll")) { + Collection emps = empService.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + + out.println("
"); + Collection depts = deptService.findAllDepartments(); + if (depts.isEmpty()) { + out.println("No Departments found "); + } else { + out.println("Found Departments:
"); + for (Department dept : depts) { + out.println(dept + " with " + dept.getEmployees().size() + + " employees " + dept.getEmployees() + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Department + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
Employee Salary:(long)
"); + out.println("
"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Dept Name:(String)
"); + out.println("
"); + + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Emp Id:(int)
Dept Id:(int)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees & Departments

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter5/6-elementCollectionEnumMap/undeploy.bat b/examples/Chapter5/6-elementCollectionEnumMap/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter5/6-elementCollectionEnumMap/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter5/7-oneToManyMap/build.xml b/examples/Chapter5/7-oneToManyMap/build.xml new file mode 100644 index 0000000..bbc21ff --- /dev/null +++ b/examples/Chapter5/7-oneToManyMap/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/7-oneToManyMap/deploy.bat b/examples/Chapter5/7-oneToManyMap/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter5/7-oneToManyMap/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter5/7-oneToManyMap/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/7-oneToManyMap/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..3b945b9 --- /dev/null +++ b/examples/Chapter5/7-oneToManyMap/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,13 @@ + + + jdbc/oneToManyMap + NONE + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/7-oneToManyMap/etc/sql/db.sql b/examples/Chapter5/7-oneToManyMap/etc/sql/db.sql new file mode 100644 index 0000000..8f74fed --- /dev/null +++ b/examples/Chapter5/7-oneToManyMap/etc/sql/db.sql @@ -0,0 +1,6 @@ +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; +CREATE TABLE EMPLOYEE (ID INTEGER GENERATED ALWAYS AS IDENTITY NOT NULL, NAME VARCHAR(255), SALARY BIGINT, + CUB_ID VARCHAR(255), DEPARTMENT_ID INTEGER, PRIMARY KEY (ID)); +CREATE TABLE DEPARTMENT (ID INTEGER GENERATED ALWAYS AS IDENTITY NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +ALTER TABLE EMPLOYEE ADD CONSTRAINT MPLOYEEDPARTMENTID FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID); diff --git a/examples/Chapter5/7-oneToManyMap/etc/web/WEB-INF/web.xml b/examples/Chapter5/7-oneToManyMap/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter5/7-oneToManyMap/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter5/7-oneToManyMap/src/model/examples/model/Department.java b/examples/Chapter5/7-oneToManyMap/src/model/examples/model/Department.java new file mode 100644 index 0000000..6572b8a --- /dev/null +++ b/examples/Chapter5/7-oneToManyMap/src/model/examples/model/Department.java @@ -0,0 +1,79 @@ +package examples.model; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +import javax.persistence.MapKeyColumn; +import javax.persistence.OneToMany; + + +@Entity +public class Department { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + + @OneToMany(mappedBy="department") + @MapKeyColumn(name="CUB_ID") + private Map employeesByCubicle; + + public Department() { + employeesByCubicle = new HashMap(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String deptName) { + this.name = deptName; + } + + public Map getEmployees() { + return employeesByCubicle; + } + + public void addEmployee(String cubeId, Employee employee) { + employeesByCubicle.put(cubeId, employee); + if (employee.getDepartment() != null) { + employee.getDepartment().removeEmployee(employee); + } + employee.setDepartment(this); + } + + public void removeEmployee(Employee employee) { + Iterator iter = employeesByCubicle.entrySet().iterator(); + while (iter.hasNext()) { + Employee current = ((Map.Entry) iter.next()).getValue(); + if (current.getId() == employee.getId()) { + iter.remove(); + current.setDepartment(null); + } + } + } + + public String toString() { + StringBuffer aBuffer = new StringBuffer("Department "); + aBuffer.append(" id: "); + aBuffer.append(id); + aBuffer.append(" name: "); + aBuffer.append(name); + aBuffer.append(" employeeCount: "); + aBuffer.append(employeesByCubicle.size()); + return aBuffer.toString(); + } +} \ No newline at end of file diff --git a/examples/Chapter5/7-oneToManyMap/src/model/examples/model/Employee.java b/examples/Chapter5/7-oneToManyMap/src/model/examples/model/Employee.java new file mode 100644 index 0000000..95a8ad3 --- /dev/null +++ b/examples/Chapter5/7-oneToManyMap/src/model/examples/model/Employee.java @@ -0,0 +1,69 @@ +package examples.model; + +import java.util.Map; + +import javax.persistence.CollectionTable; +import javax.persistence.Column; +import javax.persistence.ElementCollection; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import javax.persistence.MapKeyColumn; + +@Entity +public class Employee { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + private long salary; + + @ManyToOne + private Department department; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + + public String toString() { + StringBuffer aBuffer = new StringBuffer("Employee "); + aBuffer.append(" id: "); + aBuffer.append(id); + aBuffer.append(" with dept: "); + if(null != department) { + aBuffer.append(department.getName()); + } + return aBuffer.toString(); + } +} \ No newline at end of file diff --git a/examples/Chapter5/7-oneToManyMap/src/model/examples/stateless/DepartmentService.java b/examples/Chapter5/7-oneToManyMap/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..7003e8d --- /dev/null +++ b/examples/Chapter5/7-oneToManyMap/src/model/examples/stateless/DepartmentService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Department; + +public interface DepartmentService { + public Department createDepartment(String name); + public Collection findAllDepartments(); +} diff --git a/examples/Chapter5/7-oneToManyMap/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter5/7-oneToManyMap/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..7d47cb1 --- /dev/null +++ b/examples/Chapter5/7-oneToManyMap/src/model/examples/stateless/DepartmentServiceBean.java @@ -0,0 +1,29 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; + +@Stateless +public class DepartmentServiceBean implements DepartmentService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Department createDepartment(String name) { + Department dept = new Department(); + dept.setName(name); + em.persist(dept); + + return dept; + } + + public Collection findAllDepartments() { + Query query = em.createQuery("SELECT d FROM Department d"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter5/7-oneToManyMap/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/7-oneToManyMap/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..fdd980e --- /dev/null +++ b/examples/Chapter5/7-oneToManyMap/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(String name, long salary); + public Employee setEmployeeDepartment(int empId, String cubeId, int deptId); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter5/7-oneToManyMap/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/7-oneToManyMap/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..ce65aaf --- /dev/null +++ b/examples/Chapter5/7-oneToManyMap/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,40 @@ +package examples.stateless; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String name, long salary) { + Employee emp = new Employee(); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + return emp; + } + + public Employee setEmployeeDepartment(int empId, String cubeId, int deptId) { + Employee emp = em.find(Employee.class, empId); + Department dept = em.find(Department.class, deptId); + dept.addEmployee(cubeId, emp); + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + Collection aCollection = (Collection) query.getResultList(); + return aCollection; + } +} diff --git a/examples/Chapter5/7-oneToManyMap/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter5/7-oneToManyMap/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..c706367 --- /dev/null +++ b/examples/Chapter5/7-oneToManyMap/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,147 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Department; +import examples.model.Employee; +import examples.stateless.DepartmentService; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 5: One-To-Many Map Keyed By String Example"; + + private final String DESCRIPTION = + "This example demonstrates how to work with relationship Maps.
" + + "The Map contains String keys and entity values."; + + + @EJB EmployeeService empService; + @EJB DepartmentService deptService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("CreateEmp")) { + Employee emp = empService.createEmployee( + request.getParameter("empName"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("CreateDept")) { + Department dept = deptService.createDepartment( + request.getParameter("deptName")); + out.println("Created " + dept); + } else if (action.equals("SetEmployeeDept")) { + Employee emp = empService.setEmployeeDepartment( + parseInt(request.getParameter("empId")), + request.getParameter("cubeId"), + parseInt(request.getParameter("deptId"))); + out.println("Updated " + emp + "
"); + out.println(emp.getDepartment() + " with Employees:
"); + out.println(emp.getDepartment().getEmployees()); + } else if (action.equals("FindAll")) { + Collection emps = empService.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + + out.println("
"); + Collection depts = deptService.findAllDepartments(); + if (depts.isEmpty()) { + out.println("No Departments found "); + } else { + out.println("Found Departments:
"); + for (Department dept : depts) { + out.println(dept + " with " + dept.getEmployees().size() + + " employees " + dept.getEmployees() + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Department + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
Employee Salary:(long)
"); + out.println("
"); + + out.println(""); + out.println(""); + out.println(""); + out.println("
Dept Name:(String)
"); + out.println("
"); + + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Emp Id:(int)
Cube Id:(String)
Dept Id:(int)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees & Departments

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter5/7-oneToManyMap/undeploy.bat b/examples/Chapter5/7-oneToManyMap/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter5/7-oneToManyMap/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter5/8-manyToManyMap/build.xml b/examples/Chapter5/8-manyToManyMap/build.xml new file mode 100644 index 0000000..1e0d542 --- /dev/null +++ b/examples/Chapter5/8-manyToManyMap/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/8-manyToManyMap/deploy.bat b/examples/Chapter5/8-manyToManyMap/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter5/8-manyToManyMap/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter5/8-manyToManyMap/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/8-manyToManyMap/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..9941122 --- /dev/null +++ b/examples/Chapter5/8-manyToManyMap/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,13 @@ + + + jdbc/manyToManyMap + NONE + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/8-manyToManyMap/etc/sql/db.sql b/examples/Chapter5/8-manyToManyMap/etc/sql/db.sql new file mode 100644 index 0000000..3525055 --- /dev/null +++ b/examples/Chapter5/8-manyToManyMap/etc/sql/db.sql @@ -0,0 +1,8 @@ +DROP TABLE DEPT_EMP; +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; +CREATE TABLE EMPLOYEE (ID INTEGER GENERATED ALWAYS AS IDENTITY NOT NULL, NAME VARCHAR(255), SALARY BIGINT, PRIMARY KEY (ID)); +CREATE TABLE DEPARTMENT (ID INTEGER GENERATED ALWAYS AS IDENTITY NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE DEPT_EMP (DEPT_ID INTEGER NOT NULL, EMP_ID INTEGER NOT NULL, CUB_ID VARCHAR(255), PRIMARY KEY (DEPT_ID, EMP_ID)); +ALTER TABLE DEPT_EMP ADD CONSTRAINT DEPTREF FOREIGN KEY (DEPT_ID) REFERENCES DEPARTMENT (ID); +ALTER TABLE DEPT_EMP ADD CONSTRAINT EMPREF FOREIGN KEY (EMP_ID) REFERENCES EMPLOYEE (ID); diff --git a/examples/Chapter5/8-manyToManyMap/etc/web/WEB-INF/web.xml b/examples/Chapter5/8-manyToManyMap/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter5/8-manyToManyMap/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter5/8-manyToManyMap/src/model/examples/model/Department.java b/examples/Chapter5/8-manyToManyMap/src/model/examples/model/Department.java new file mode 100644 index 0000000..cdbc442 --- /dev/null +++ b/examples/Chapter5/8-manyToManyMap/src/model/examples/model/Department.java @@ -0,0 +1,78 @@ +package examples.model; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +import javax.persistence.MapKeyColumn; +import javax.persistence.ManyToMany; +import javax.persistence.JoinTable; +import javax.persistence.JoinColumn; + +@Entity +public class Department { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + + @ManyToMany + @JoinTable(name="DEPT_EMP", + joinColumns=@JoinColumn(name="DEPT_ID"), + inverseJoinColumns=@JoinColumn(name="EMP_ID")) + @MapKeyColumn(name="CUB_ID") + private Map employeesByCubicle; + + public Department() { + employeesByCubicle = new HashMap(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String deptName) { + this.name = deptName; + } + + public Map getEmployees() { + return employeesByCubicle; + } + + public void addEmployee(String cubeId, Employee employee) { + employeesByCubicle.put(cubeId, employee); + } + + public void removeEmployee(Employee employee) { + Iterator iter = employeesByCubicle.entrySet().iterator(); + while (iter.hasNext()) { + Employee current = ((Map.Entry) iter.next()).getValue(); + if (current.getId() == employee.getId()) { + iter.remove(); + } + } + } + + public String toString() { + StringBuffer aBuffer = new StringBuffer("Department "); + aBuffer.append(" id: "); + aBuffer.append(id); + aBuffer.append(" name: "); + aBuffer.append(name); + aBuffer.append(" employeeCount: "); + aBuffer.append(employeesByCubicle.size()); + return aBuffer.toString(); + } +} \ No newline at end of file diff --git a/examples/Chapter5/8-manyToManyMap/src/model/examples/model/Employee.java b/examples/Chapter5/8-manyToManyMap/src/model/examples/model/Employee.java new file mode 100644 index 0000000..e2a4827 --- /dev/null +++ b/examples/Chapter5/8-manyToManyMap/src/model/examples/model/Employee.java @@ -0,0 +1,66 @@ +package examples.model; + +import java.util.Collection; + +import javax.persistence.CollectionTable; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToMany; + +@Entity +public class Employee { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + private long salary; + + @ManyToMany(mappedBy="employeesByCubicle") + private Collection departments; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public Collection getDepartments() { + return departments; + } + + public void setDepartments(Collection departments) { + this.departments = departments; + } + + + public String toString() { + StringBuffer aBuffer = new StringBuffer("Employee "); + aBuffer.append(" id: "); + aBuffer.append(id); + aBuffer.append(" with deptCount: "); + if(null != departments) { + aBuffer.append(departments.size()); + } + return aBuffer.toString(); + } +} \ No newline at end of file diff --git a/examples/Chapter5/8-manyToManyMap/src/model/examples/stateless/DepartmentService.java b/examples/Chapter5/8-manyToManyMap/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..7003e8d --- /dev/null +++ b/examples/Chapter5/8-manyToManyMap/src/model/examples/stateless/DepartmentService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Department; + +public interface DepartmentService { + public Department createDepartment(String name); + public Collection findAllDepartments(); +} diff --git a/examples/Chapter5/8-manyToManyMap/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter5/8-manyToManyMap/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..7d47cb1 --- /dev/null +++ b/examples/Chapter5/8-manyToManyMap/src/model/examples/stateless/DepartmentServiceBean.java @@ -0,0 +1,29 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; + +@Stateless +public class DepartmentServiceBean implements DepartmentService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Department createDepartment(String name) { + Department dept = new Department(); + dept.setName(name); + em.persist(dept); + + return dept; + } + + public Collection findAllDepartments() { + Query query = em.createQuery("SELECT d FROM Department d"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter5/8-manyToManyMap/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/8-manyToManyMap/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..29d4b1f --- /dev/null +++ b/examples/Chapter5/8-manyToManyMap/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(String name, long salary); + public Employee addEmployeeDepartment(int empId, String cubeId, int deptId); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter5/8-manyToManyMap/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/8-manyToManyMap/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..a2f399f --- /dev/null +++ b/examples/Chapter5/8-manyToManyMap/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,41 @@ +package examples.stateless; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String name, long salary) { + Employee emp = new Employee(); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + return emp; + } + + public Employee addEmployeeDepartment(int empId, String cubeId, int deptId) { + Employee emp = em.find(Employee.class, empId); + Department dept = em.find(Department.class, deptId); + dept.addEmployee(cubeId, emp); + emp.getDepartments().add(dept); + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + Collection aCollection = (Collection) query.getResultList(); + return aCollection; + } +} diff --git a/examples/Chapter5/8-manyToManyMap/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter5/8-manyToManyMap/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..fb3a653 --- /dev/null +++ b/examples/Chapter5/8-manyToManyMap/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,145 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Department; +import examples.model.Employee; +import examples.stateless.DepartmentService; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 5: Many-To-Many Map Example Keyed by String and Enumerated Type"; + + private final String DESCRIPTION = + "This example demonstrates how to work with relationship Maps.
" + + "The Map contains String keys and entity values."; + + + @EJB EmployeeService empService; + @EJB DepartmentService deptService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("CreateEmp")) { + Employee emp = empService.createEmployee( + request.getParameter("empName"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("CreateDept")) { + Department dept = deptService.createDepartment( + request.getParameter("deptName")); + out.println("Created " + dept); + } else if (action.equals("AddEmployeeDept")) { + Employee emp = empService.addEmployeeDepartment( + parseInt(request.getParameter("empId")), + request.getParameter("cubeId"), + parseInt(request.getParameter("deptId"))); + out.println("Updated " + emp + "
"); + } else if (action.equals("FindAll")) { + Collection emps = empService.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + + out.println("
"); + Collection depts = deptService.findAllDepartments(); + if (depts.isEmpty()) { + out.println("No Departments found "); + } else { + out.println("Found Departments:
"); + for (Department dept : depts) { + out.println(dept + " with " + dept.getEmployees().size() + + " employees " + dept.getEmployees() + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Department + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
Employee Salary:(long)
"); + out.println("
"); + + out.println(""); + out.println(""); + out.println(""); + out.println("
Dept Name:(String)
"); + out.println("
"); + + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Emp Id:(int)
Cube Id:(String)
Dept Id:(int)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees & Departments

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter5/8-manyToManyMap/undeploy.bat b/examples/Chapter5/8-manyToManyMap/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter5/8-manyToManyMap/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter5/9-oneToManyEntityAttributeKey/build.xml b/examples/Chapter5/9-oneToManyEntityAttributeKey/build.xml new file mode 100644 index 0000000..1722965 --- /dev/null +++ b/examples/Chapter5/9-oneToManyEntityAttributeKey/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/9-oneToManyEntityAttributeKey/deploy.bat b/examples/Chapter5/9-oneToManyEntityAttributeKey/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter5/9-oneToManyEntityAttributeKey/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter5/9-oneToManyEntityAttributeKey/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/9-oneToManyEntityAttributeKey/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..376dc60 --- /dev/null +++ b/examples/Chapter5/9-oneToManyEntityAttributeKey/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,13 @@ + + + jdbc/oneToManyEntityAttributeKey + NONE + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/9-oneToManyEntityAttributeKey/etc/sql/db.sql b/examples/Chapter5/9-oneToManyEntityAttributeKey/etc/sql/db.sql new file mode 100644 index 0000000..e360651 --- /dev/null +++ b/examples/Chapter5/9-oneToManyEntityAttributeKey/etc/sql/db.sql @@ -0,0 +1,6 @@ +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; +CREATE TABLE EMPLOYEE (ID INTEGER GENERATED ALWAYS AS IDENTITY NOT NULL, NAME VARCHAR(255), SALARY BIGINT, + DEPARTMENT_ID INTEGER, PRIMARY KEY (ID)); +CREATE TABLE DEPARTMENT (ID INTEGER GENERATED ALWAYS AS IDENTITY NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +ALTER TABLE EMPLOYEE ADD CONSTRAINT MPLOYEEDPARTMENTID FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID); diff --git a/examples/Chapter5/9-oneToManyEntityAttributeKey/etc/web/WEB-INF/web.xml b/examples/Chapter5/9-oneToManyEntityAttributeKey/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter5/9-oneToManyEntityAttributeKey/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter5/9-oneToManyEntityAttributeKey/src/model/examples/model/Department.java b/examples/Chapter5/9-oneToManyEntityAttributeKey/src/model/examples/model/Department.java new file mode 100644 index 0000000..a01069e --- /dev/null +++ b/examples/Chapter5/9-oneToManyEntityAttributeKey/src/model/examples/model/Department.java @@ -0,0 +1,79 @@ +package examples.model; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +import javax.persistence.MapKey; +import javax.persistence.OneToMany; + + +@Entity +public class Department { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + + @OneToMany(mappedBy="department") + @MapKey(name="id") + private Map employeesById; + + public Department() { + employeesById = new HashMap(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String deptName) { + this.name = deptName; + } + + public Map getEmployees() { + return employeesById; + } + + public void addEmployee(Employee employee) { + employeesById.put(employee.getId(), employee); + if (employee.getDepartment() != null) { + employee.getDepartment().removeEmployee(employee); + } + employee.setDepartment(this); + } + + public void removeEmployee(Employee employee) { + Iterator iter = employeesById.entrySet().iterator(); + while (iter.hasNext()) { + Employee current = ((Map.Entry) iter.next()).getValue(); + if (current.getId() == employee.getId()) { + iter.remove(); + current.setDepartment(null); + } + } + } + + public String toString() { + StringBuffer aBuffer = new StringBuffer("Department "); + aBuffer.append(" id: "); + aBuffer.append(id); + aBuffer.append(" name: "); + aBuffer.append(name); + aBuffer.append(" employeeCount: "); + aBuffer.append(employeesById.size()); + return aBuffer.toString(); + } +} \ No newline at end of file diff --git a/examples/Chapter5/9-oneToManyEntityAttributeKey/src/model/examples/model/Employee.java b/examples/Chapter5/9-oneToManyEntityAttributeKey/src/model/examples/model/Employee.java new file mode 100644 index 0000000..95a8ad3 --- /dev/null +++ b/examples/Chapter5/9-oneToManyEntityAttributeKey/src/model/examples/model/Employee.java @@ -0,0 +1,69 @@ +package examples.model; + +import java.util.Map; + +import javax.persistence.CollectionTable; +import javax.persistence.Column; +import javax.persistence.ElementCollection; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import javax.persistence.MapKeyColumn; + +@Entity +public class Employee { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private String name; + private long salary; + + @ManyToOne + private Department department; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + + public String toString() { + StringBuffer aBuffer = new StringBuffer("Employee "); + aBuffer.append(" id: "); + aBuffer.append(id); + aBuffer.append(" with dept: "); + if(null != department) { + aBuffer.append(department.getName()); + } + return aBuffer.toString(); + } +} \ No newline at end of file diff --git a/examples/Chapter5/9-oneToManyEntityAttributeKey/src/model/examples/stateless/DepartmentService.java b/examples/Chapter5/9-oneToManyEntityAttributeKey/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..7003e8d --- /dev/null +++ b/examples/Chapter5/9-oneToManyEntityAttributeKey/src/model/examples/stateless/DepartmentService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Department; + +public interface DepartmentService { + public Department createDepartment(String name); + public Collection findAllDepartments(); +} diff --git a/examples/Chapter5/9-oneToManyEntityAttributeKey/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter5/9-oneToManyEntityAttributeKey/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..7d47cb1 --- /dev/null +++ b/examples/Chapter5/9-oneToManyEntityAttributeKey/src/model/examples/stateless/DepartmentServiceBean.java @@ -0,0 +1,29 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; + +@Stateless +public class DepartmentServiceBean implements DepartmentService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Department createDepartment(String name) { + Department dept = new Department(); + dept.setName(name); + em.persist(dept); + + return dept; + } + + public Collection findAllDepartments() { + Query query = em.createQuery("SELECT d FROM Department d"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter5/9-oneToManyEntityAttributeKey/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/9-oneToManyEntityAttributeKey/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..84116f6 --- /dev/null +++ b/examples/Chapter5/9-oneToManyEntityAttributeKey/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(String name, long salary); + public Employee setEmployeeDepartment(int empId, int deptId); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter5/9-oneToManyEntityAttributeKey/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/9-oneToManyEntityAttributeKey/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..b310ac7 --- /dev/null +++ b/examples/Chapter5/9-oneToManyEntityAttributeKey/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,40 @@ +package examples.stateless; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String name, long salary) { + Employee emp = new Employee(); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + return emp; + } + + public Employee setEmployeeDepartment(int empId, int deptId) { + Employee emp = em.find(Employee.class, empId); + Department dept = em.find(Department.class, deptId); + dept.addEmployee(emp); + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + Collection aCollection = (Collection) query.getResultList(); + return aCollection; + } +} diff --git a/examples/Chapter5/9-oneToManyEntityAttributeKey/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter5/9-oneToManyEntityAttributeKey/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..22b230b --- /dev/null +++ b/examples/Chapter5/9-oneToManyEntityAttributeKey/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,143 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Department; +import examples.model.Employee; +import examples.stateless.DepartmentService; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 5: One-To-Many Map Keyed By Entity Attribute"; + + private final String DESCRIPTION = + "This example demonstrates how to work with relationship Maps.
" + + "The Map contains entity attribute keys and entity values."; + + + @EJB EmployeeService empService; + @EJB DepartmentService deptService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("CreateEmp")) { + Employee emp = empService.createEmployee( + request.getParameter("empName"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("CreateDept")) { + Department dept = deptService.createDepartment( + request.getParameter("deptName")); + out.println("Created " + dept); + } else if (action.equals("SetEmployeeDept")) { + Employee emp = empService.setEmployeeDepartment( + parseInt(request.getParameter("empId")), + parseInt(request.getParameter("deptId"))); + out.println("Updated " + emp + "
"); + } else if (action.equals("FindAll")) { + Collection emps = empService.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + + out.println("
"); + Collection depts = deptService.findAllDepartments(); + if (depts.isEmpty()) { + out.println("No Departments found "); + } else { + out.println("Found Departments:
"); + for (Department dept : depts) { + out.println(dept + " with " + dept.getEmployees().size() + + " employees " + dept.getEmployees() + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create and Employee and Department + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
Employee Salary:(long)
"); + out.println("
"); + + out.println(""); + out.println(""); + out.println(""); + out.println("
Dept Name:(String)
"); + out.println("
"); + + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Emp Id:(int)
Dept Id:(int)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees & Departments

"); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter5/9-oneToManyEntityAttributeKey/undeploy.bat b/examples/Chapter5/9-oneToManyEntityAttributeKey/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter5/9-oneToManyEntityAttributeKey/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter6/01-txScopedEmExample/build.xml b/examples/Chapter6/01-txScopedEmExample/build.xml new file mode 100644 index 0000000..d5191fc --- /dev/null +++ b/examples/Chapter6/01-txScopedEmExample/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/01-txScopedEmExample/deploy.bat b/examples/Chapter6/01-txScopedEmExample/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter6/01-txScopedEmExample/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter6/01-txScopedEmExample/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/01-txScopedEmExample/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..fdae6cf --- /dev/null +++ b/examples/Chapter6/01-txScopedEmExample/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/txScopedEmExample + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/01-txScopedEmExample/etc/sql/db.sql b/examples/Chapter6/01-txScopedEmExample/etc/sql/db.sql new file mode 100644 index 0000000..3cd19ae --- /dev/null +++ b/examples/Chapter6/01-txScopedEmExample/etc/sql/db.sql @@ -0,0 +1,29 @@ +DROP TABLE EMPLOYEE_PROJECT; +DROP TABLE PROJECT; +DROP TABLE EMPLOYEE; + + +CREATE TABLE PROJECT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), STARTDATE DATE, SALARY BIGINT, PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE_PROJECT (PROJECTS_ID INTEGER NOT NULL, EMPLOYEES_ID INTEGER NOT NULL, + CONSTRAINT PROJECTS_FK FOREIGN KEY (PROJECTS_ID) REFERENCES PROJECT (ID), + CONSTRAINT EMPLOYEES_FK FOREIGN KEY (EMPLOYEES_ID) REFERENCES EMPLOYEE (ID), + PRIMARY KEY (PROJECTS_ID, EMPLOYEES_ID)); + + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE) VALUES (1, 'Joan', 59000, {d '2003-04-16'}); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE) VALUES (2, 'Sarah', 52000, {d '2002-04-26'}); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE) VALUES (3, 'John', 55000, {d '2001-01-01'}); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE) VALUES (4, 'Roberts', 53000, {d '2001-05-23'}); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE) VALUES (5, 'Peter', 50000, {d '2002-08-06'}); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE) VALUES (6, 'Frank', 51000, {d '2003-02-17'}); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE) VALUES (7, 'Scott', 60000, {d '2004-11-14'}); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE) VALUES (8, 'Sue', 62000, {d '2005-08-18'}); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE) VALUES (9, 'Stephanie', 54000, {d '2006-06-07'}); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE) VALUES (10, 'Jennifer', 55000, {d '1999-08-11'}); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE) VALUES (11, 'Marcus', 35000, {d '1995-07-22'}); + +INSERT INTO PROJECT (ID, NAME) VALUES (1, 'Design Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (2, 'Implement Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (3, 'Test Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (4, 'Release3'); \ No newline at end of file diff --git a/examples/Chapter6/01-txScopedEmExample/etc/web/WEB-INF/web.xml b/examples/Chapter6/01-txScopedEmExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter6/01-txScopedEmExample/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServiceServlet + examples.servlet.EmployeeServiceServlet + + + + EmployeeServiceServlet + /EmployeeServiceServlet + + \ No newline at end of file diff --git a/examples/Chapter6/01-txScopedEmExample/src/model/examples/model/Employee.java b/examples/Chapter6/01-txScopedEmExample/src/model/examples/model/Employee.java new file mode 100644 index 0000000..e94ea3e --- /dev/null +++ b/examples/Chapter6/01-txScopedEmExample/src/model/examples/model/Employee.java @@ -0,0 +1,58 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToMany; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + @Temporal(TemporalType.DATE) + private Date startDate; + + @ManyToMany + private Collection projects; + + public Employee() { + projects = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public long getSalary() { + return salary; + } + + public Date getStartDate() { + return startDate; + } + + public Collection getProjects() { + return projects; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary(); + } +} diff --git a/examples/Chapter6/01-txScopedEmExample/src/model/examples/model/Project.java b/examples/Chapter6/01-txScopedEmExample/src/model/examples/model/Project.java new file mode 100644 index 0000000..8226327 --- /dev/null +++ b/examples/Chapter6/01-txScopedEmExample/src/model/examples/model/Project.java @@ -0,0 +1,37 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToMany; + +@Entity +public class Project { + @Id + protected int id; + protected String name; + @ManyToMany(mappedBy="projects") + private Collection employees; + + public Project() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Project id: " + getId() + ", name: " + getName(); + } +} diff --git a/examples/Chapter6/01-txScopedEmExample/src/model/examples/stateless/EmployeeService.java b/examples/Chapter6/01-txScopedEmExample/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..938e90d --- /dev/null +++ b/examples/Chapter6/01-txScopedEmExample/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,9 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Collection findAllEmployees(); +} diff --git a/examples/Chapter6/01-txScopedEmExample/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter6/01-txScopedEmExample/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..adb12c0 --- /dev/null +++ b/examples/Chapter6/01-txScopedEmExample/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,20 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + EntityManager em; + + public Collection findAllEmployees() { + return (Collection) em.createQuery( + "SELECT e FROM Employee e").getResultList(); + } +} diff --git a/examples/Chapter6/01-txScopedEmExample/src/model/examples/stateless/ProjectService.java b/examples/Chapter6/01-txScopedEmExample/src/model/examples/stateless/ProjectService.java new file mode 100644 index 0000000..24e37e1 --- /dev/null +++ b/examples/Chapter6/01-txScopedEmExample/src/model/examples/stateless/ProjectService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Project; + +public interface ProjectService { + public void assignEmployeeToProject(int empId, int projectId); + public Collection findAllProjects(); +} diff --git a/examples/Chapter6/01-txScopedEmExample/src/model/examples/stateless/ProjectServiceBean.java b/examples/Chapter6/01-txScopedEmExample/src/model/examples/stateless/ProjectServiceBean.java new file mode 100644 index 0000000..aa8a648 --- /dev/null +++ b/examples/Chapter6/01-txScopedEmExample/src/model/examples/stateless/ProjectServiceBean.java @@ -0,0 +1,28 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Employee; +import examples.model.Project; + +@Stateless +public class ProjectServiceBean implements ProjectService { + @PersistenceContext(unitName="EmployeeService") + EntityManager em; + + public void assignEmployeeToProject(int empId, int projectId) { + Project project = em.find(Project.class, projectId); + Employee employee = em.find(Employee.class, empId); + project.getEmployees().add(employee); + employee.getProjects().add(project); + } + + public Collection findAllProjects() { + return (Collection) em.createQuery( + "SELECT p FROM Project p").getResultList(); + } +} diff --git a/examples/Chapter6/01-txScopedEmExample/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter6/01-txScopedEmExample/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..7b63fa1 --- /dev/null +++ b/examples/Chapter6/01-txScopedEmExample/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,96 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateless.EmployeeService; +import examples.stateless.ProjectService; + +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 6: Transaction-scoped Container Managed EntityManager Example"; + + private final String DESCRIPTION = + "This example demonstrates the basic use of a tx-scoped EntityManager.
" + + "The example allows you to assign employees to projects."; + + + @EJB + private EmployeeService empService; + @EJB + private ProjectService projService; + + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action != null) { + if (action.equals("AssignProject")) { + projService.assignEmployeeToProject( + parseInt(request.getParameter("empId")), + parseInt(request.getParameter("projId"))); + } + } + out.println("Employees:
"); + printCollection(empService.findAllEmployees(), out); + out.println("Projects:
"); + printCollection(projService.findAllProjects(), out); + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printCollection(Collection c, PrintWriter out) { + for (Object o : c) { + out.print(o + "
"); + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to update + out.println("

Assign Employee to Project

"); + out.println(""); + out.println(""); + out.println("" + + ""); + out.println("
Employee Id:(int)
Project Id:(int)
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter6/01-txScopedEmExample/undeploy.bat b/examples/Chapter6/01-txScopedEmExample/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter6/01-txScopedEmExample/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter6/02-extendedEmExample1/build.xml b/examples/Chapter6/02-extendedEmExample1/build.xml new file mode 100644 index 0000000..5df5f93 --- /dev/null +++ b/examples/Chapter6/02-extendedEmExample1/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/02-extendedEmExample1/deploy.bat b/examples/Chapter6/02-extendedEmExample1/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter6/02-extendedEmExample1/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter6/02-extendedEmExample1/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/02-extendedEmExample1/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..e9a7ddf --- /dev/null +++ b/examples/Chapter6/02-extendedEmExample1/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/extendedEmExample + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/02-extendedEmExample1/etc/sql/db.sql b/examples/Chapter6/02-extendedEmExample1/etc/sql/db.sql new file mode 100644 index 0000000..88a74b3 --- /dev/null +++ b/examples/Chapter6/02-extendedEmExample1/etc/sql/db.sql @@ -0,0 +1,23 @@ +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), STARTDATE DATE, SALARY BIGINT, + DEPARTMENT_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPARTMENT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID)); + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'CA13'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'CA19'); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (1, 'Joan', 59000, {d '2003-04-16'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (2, 'Sarah', 52000, {d '2002-04-26'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (3, 'John', 55000, {d '2001-01-01'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (4, 'Roberts', 53000, {d '2001-05-23'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (5, 'Peter', 50000, {d '2002-08-06'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (6, 'Frank', 51000, {d '2003-02-17'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (7, 'Scott', 60000, {d '2004-11-14'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (8, 'Sue', 62000, {d '2005-08-18'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (9, 'Stephanie', 54000, {d '2006-06-07'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (10, 'Jennifer', 55000, {d '1999-08-11'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (11, 'Marcus', 35000, {d '1995-07-22'}, NULL); \ No newline at end of file diff --git a/examples/Chapter6/02-extendedEmExample1/etc/web/WEB-INF/web.xml b/examples/Chapter6/02-extendedEmExample1/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter6/02-extendedEmExample1/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServiceServlet + examples.servlet.EmployeeServiceServlet + + + + EmployeeServiceServlet + /EmployeeServiceServlet + + \ No newline at end of file diff --git a/examples/Chapter6/02-extendedEmExample1/src/model/examples/model/Department.java b/examples/Chapter6/02-extendedEmExample1/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter6/02-extendedEmExample1/src/model/examples/model/Department.java @@ -0,0 +1,46 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="department") + private Collection employees; + + public Department() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter6/02-extendedEmExample1/src/model/examples/model/Employee.java b/examples/Chapter6/02-extendedEmExample1/src/model/examples/model/Employee.java new file mode 100644 index 0000000..b4ce131 --- /dev/null +++ b/examples/Chapter6/02-extendedEmExample1/src/model/examples/model/Employee.java @@ -0,0 +1,59 @@ +package examples.model; + +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + @Temporal(TemporalType.DATE) + private Date startDate; + + @ManyToOne + private Department department; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + + public long getSalary() { + return salary; + } + + public Date getStartDate() { + return startDate; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department dept) { + this.department = dept; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary() + + ", dept: " + ((getDepartment() == null) ? null : getDepartment().getName()); + } +} diff --git a/examples/Chapter6/02-extendedEmExample1/src/model/examples/stateless/DepartmentManager.java b/examples/Chapter6/02-extendedEmExample1/src/model/examples/stateless/DepartmentManager.java new file mode 100644 index 0000000..6ff6396 --- /dev/null +++ b/examples/Chapter6/02-extendedEmExample1/src/model/examples/stateless/DepartmentManager.java @@ -0,0 +1,12 @@ +package examples.stateless; + +import examples.model.Department; + + +public interface DepartmentManager { + public void init(int deptId); + public Department getDepartment(); + public void setName(String name); + public void addEmployee(int empId); + public void finished(); +} diff --git a/examples/Chapter6/02-extendedEmExample1/src/model/examples/stateless/DepartmentManagerBean.java b/examples/Chapter6/02-extendedEmExample1/src/model/examples/stateless/DepartmentManagerBean.java new file mode 100644 index 0000000..2ecaf1f --- /dev/null +++ b/examples/Chapter6/02-extendedEmExample1/src/model/examples/stateless/DepartmentManagerBean.java @@ -0,0 +1,41 @@ +package examples.stateless; + +import javax.ejb.Remove; +import javax.ejb.Stateful; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Department; +import examples.model.Employee; + +@Stateful +public class DepartmentManagerBean implements DepartmentManager { + @PersistenceContext(unitName="EmployeeService") + EntityManager em; + int deptId; + + public void init(int deptId) { + this.deptId = deptId; + } + + public Department getDepartment() { + return em.find(Department.class, deptId); + } + + public void setName(String name) { + Department dept = em.find(Department.class, deptId); + dept.setName(name); + } + + public void addEmployee(int empId) { + Department dept = em.find(Department.class, deptId); + Employee emp = em.find(Employee.class, empId); + dept.getEmployees().add(emp); + emp.setDepartment(dept); + } + + @Remove + public void finished() { + } +} + diff --git a/examples/Chapter6/02-extendedEmExample1/src/model/examples/stateless/EmployeeService.java b/examples/Chapter6/02-extendedEmExample1/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..cc0558b --- /dev/null +++ b/examples/Chapter6/02-extendedEmExample1/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Department; +import examples.model.Employee; + +public interface EmployeeService { + public Collection findAllEmployees(); + public Collection findAllDepartments(); +} diff --git a/examples/Chapter6/02-extendedEmExample1/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter6/02-extendedEmExample1/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..748e5a5 --- /dev/null +++ b/examples/Chapter6/02-extendedEmExample1/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,26 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + EntityManager em; + + public Collection findAllEmployees() { + return (Collection) em.createQuery( + "SELECT e FROM Employee e").getResultList(); + } + + public Collection findAllDepartments() { + return (Collection) em.createQuery( + "SELECT d FROM Department d").getResultList(); + } +} diff --git a/examples/Chapter6/02-extendedEmExample1/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter6/02-extendedEmExample1/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..8333076 --- /dev/null +++ b/examples/Chapter6/02-extendedEmExample1/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,141 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.naming.InitialContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateless.DepartmentManager; +import examples.stateless.EmployeeService; + +@EJB(name="ejb/DepartmentManager", + beanInterface=DepartmentManager.class, + beanName="DepartmentManagerBean") +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 6: Stateful Session bean and EntityManager Example (First Attempt)"; + + private final String DESCRIPTION = + "This example demonstrates how the department entity must be found " + + "before performing each operation"; + + + @EJB + private EmployeeService empService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + DepartmentManager deptManager = (DepartmentManager) request.getSession().getAttribute("DepartmentManager"); + if (deptManager == null) { + try { + deptManager = (DepartmentManager) + new InitialContext().lookup("java:comp/env/ejb/DepartmentManager"); + request.getSession().setAttribute("DepartmentManager", deptManager); + } catch (Exception e) { + throw new ServletException(e); + } + } + + // process request + String action = request.getParameter("action"); + if (action == null) { + printInitAction(out); + } else if (action.equals("ManageDept")) { + deptManager.init(parseInt(request.getParameter("deptId"))); + printManagementActions(out, deptManager); + } else if (action.equals("AddEmployee")) { + deptManager.addEmployee(parseInt(request.getParameter("empId"))); + printManagementActions(out, deptManager); + } else if (action.equals("SetName")) { + deptManager.setName(request.getParameter("name")); + printManagementActions(out, deptManager); + } else if (action.equals("Finished")) { + deptManager.finished(); + request.getSession().removeAttribute("DepartmentManager"); + printInitAction(out); + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printCollection(Collection c, PrintWriter out) { + for (Object o : c) { + out.print(o + "
"); + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + } + + private void printInitAction(PrintWriter out) { + out.println(""); + out.println("

Manage Department

"); + out.println(""); + out.println("" + + ""); + out.println("
Department Id:(int)
"); + out.println(""); + out.println("
"); + out.println("Departments:
"); + printCollection(empService.findAllDepartments(), out); + } + + private void printManagementActions(PrintWriter out, DepartmentManager deptManager) { + out.print("Managing " + deptManager.getDepartment() + " with " + + deptManager.getDepartment().getEmployees().size() + " employees.
"); + + out.println("
"); + out.println("

Add Employee to Department

"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
"); + out.println("
"); + out.println("

Set Department Name

"); + out.println(""); + out.println("" + + ""); + out.println("
Name:(String)
"); + out.println("
"); + out.println(""); + out.println("
"); + out.println("
"); + + out.println("Employees:
"); + printCollection(empService.findAllEmployees(), out); + } + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter6/02-extendedEmExample1/undeploy.bat b/examples/Chapter6/02-extendedEmExample1/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter6/02-extendedEmExample1/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter6/03-extendedEmExample2/build.xml b/examples/Chapter6/03-extendedEmExample2/build.xml new file mode 100644 index 0000000..497eb82 --- /dev/null +++ b/examples/Chapter6/03-extendedEmExample2/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/03-extendedEmExample2/deploy.bat b/examples/Chapter6/03-extendedEmExample2/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter6/03-extendedEmExample2/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter6/03-extendedEmExample2/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/03-extendedEmExample2/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..96ce74a --- /dev/null +++ b/examples/Chapter6/03-extendedEmExample2/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/extendedEmExample2 + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/03-extendedEmExample2/etc/sql/db.sql b/examples/Chapter6/03-extendedEmExample2/etc/sql/db.sql new file mode 100644 index 0000000..88a74b3 --- /dev/null +++ b/examples/Chapter6/03-extendedEmExample2/etc/sql/db.sql @@ -0,0 +1,23 @@ +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), STARTDATE DATE, SALARY BIGINT, + DEPARTMENT_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPARTMENT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID)); + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'CA13'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'CA19'); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (1, 'Joan', 59000, {d '2003-04-16'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (2, 'Sarah', 52000, {d '2002-04-26'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (3, 'John', 55000, {d '2001-01-01'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (4, 'Roberts', 53000, {d '2001-05-23'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (5, 'Peter', 50000, {d '2002-08-06'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (6, 'Frank', 51000, {d '2003-02-17'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (7, 'Scott', 60000, {d '2004-11-14'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (8, 'Sue', 62000, {d '2005-08-18'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (9, 'Stephanie', 54000, {d '2006-06-07'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (10, 'Jennifer', 55000, {d '1999-08-11'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (11, 'Marcus', 35000, {d '1995-07-22'}, NULL); \ No newline at end of file diff --git a/examples/Chapter6/03-extendedEmExample2/etc/web/WEB-INF/web.xml b/examples/Chapter6/03-extendedEmExample2/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter6/03-extendedEmExample2/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServiceServlet + examples.servlet.EmployeeServiceServlet + + + + EmployeeServiceServlet + /EmployeeServiceServlet + + \ No newline at end of file diff --git a/examples/Chapter6/03-extendedEmExample2/src/model/examples/model/Department.java b/examples/Chapter6/03-extendedEmExample2/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter6/03-extendedEmExample2/src/model/examples/model/Department.java @@ -0,0 +1,46 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="department") + private Collection employees; + + public Department() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter6/03-extendedEmExample2/src/model/examples/model/Employee.java b/examples/Chapter6/03-extendedEmExample2/src/model/examples/model/Employee.java new file mode 100644 index 0000000..b4ce131 --- /dev/null +++ b/examples/Chapter6/03-extendedEmExample2/src/model/examples/model/Employee.java @@ -0,0 +1,59 @@ +package examples.model; + +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + @Temporal(TemporalType.DATE) + private Date startDate; + + @ManyToOne + private Department department; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + + public long getSalary() { + return salary; + } + + public Date getStartDate() { + return startDate; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department dept) { + this.department = dept; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary() + + ", dept: " + ((getDepartment() == null) ? null : getDepartment().getName()); + } +} diff --git a/examples/Chapter6/03-extendedEmExample2/src/model/examples/stateless/DepartmentManager.java b/examples/Chapter6/03-extendedEmExample2/src/model/examples/stateless/DepartmentManager.java new file mode 100644 index 0000000..6ff6396 --- /dev/null +++ b/examples/Chapter6/03-extendedEmExample2/src/model/examples/stateless/DepartmentManager.java @@ -0,0 +1,12 @@ +package examples.stateless; + +import examples.model.Department; + + +public interface DepartmentManager { + public void init(int deptId); + public Department getDepartment(); + public void setName(String name); + public void addEmployee(int empId); + public void finished(); +} diff --git a/examples/Chapter6/03-extendedEmExample2/src/model/examples/stateless/DepartmentManagerBean.java b/examples/Chapter6/03-extendedEmExample2/src/model/examples/stateless/DepartmentManagerBean.java new file mode 100644 index 0000000..f5d31f9 --- /dev/null +++ b/examples/Chapter6/03-extendedEmExample2/src/model/examples/stateless/DepartmentManagerBean.java @@ -0,0 +1,39 @@ +package examples.stateless; + +import javax.ejb.Remove; +import javax.ejb.Stateful; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Department; +import examples.model.Employee; + +@Stateful +public class DepartmentManagerBean implements DepartmentManager { + @PersistenceContext(unitName="EmployeeService") + EntityManager em; + Department dept; + + public void init(int deptId) { + dept = em.find(Department.class, deptId); + } + + public Department getDepartment() { + return dept; + } + + public void setName(String name) { + dept.setName(name); + } + + public void addEmployee(int empId) { + Employee emp = em.find(Employee.class, empId); + dept.getEmployees().add(emp); + emp.setDepartment(dept); + } + + @Remove + public void finished() { + } +} + diff --git a/examples/Chapter6/03-extendedEmExample2/src/model/examples/stateless/EmployeeService.java b/examples/Chapter6/03-extendedEmExample2/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..cc0558b --- /dev/null +++ b/examples/Chapter6/03-extendedEmExample2/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Department; +import examples.model.Employee; + +public interface EmployeeService { + public Collection findAllEmployees(); + public Collection findAllDepartments(); +} diff --git a/examples/Chapter6/03-extendedEmExample2/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter6/03-extendedEmExample2/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..748e5a5 --- /dev/null +++ b/examples/Chapter6/03-extendedEmExample2/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,26 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + EntityManager em; + + public Collection findAllEmployees() { + return (Collection) em.createQuery( + "SELECT e FROM Employee e").getResultList(); + } + + public Collection findAllDepartments() { + return (Collection) em.createQuery( + "SELECT d FROM Department d").getResultList(); + } +} diff --git a/examples/Chapter6/03-extendedEmExample2/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter6/03-extendedEmExample2/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..f97c17c --- /dev/null +++ b/examples/Chapter6/03-extendedEmExample2/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,141 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.naming.InitialContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateless.DepartmentManager; +import examples.stateless.EmployeeService; + +@EJB(name="ejb/DepartmentManager", + beanInterface=DepartmentManager.class, + beanName="DepartmentManagerBean") +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 6: Stateful Session bean and EntityManager Example (Second Attempt)"; + + private final String DESCRIPTION = + "This example demonstrates how detached entities do not have any " + + "changes persisted to the database. Look at the console and you will not see any UPDATE statements."; + + + @EJB + private EmployeeService empService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + DepartmentManager deptManager = (DepartmentManager) request.getSession().getAttribute("DepartmentManager"); + if (deptManager == null) { + try { + deptManager = (DepartmentManager) + new InitialContext().lookup("java:comp/env/ejb/DepartmentManager"); + request.getSession().setAttribute("DepartmentManager", deptManager); + } catch (Exception e) { + throw new ServletException(e); + } + } + + // process request + String action = request.getParameter("action"); + if (action == null) { + printInitAction(out); + } else if (action.equals("ManageDept")) { + deptManager.init(parseInt(request.getParameter("deptId"))); + printManagementActions(out, deptManager); + } else if (action.equals("AddEmployee")) { + deptManager.addEmployee(parseInt(request.getParameter("empId"))); + printManagementActions(out, deptManager); + } else if (action.equals("SetName")) { + deptManager.setName(request.getParameter("name")); + printManagementActions(out, deptManager); + } else if (action.equals("Finished")) { + deptManager.finished(); + request.getSession().removeAttribute("DepartmentManager"); + printInitAction(out); + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printCollection(Collection c, PrintWriter out) { + for (Object o : c) { + out.print(o + "
"); + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + } + + private void printInitAction(PrintWriter out) { + out.println("
"); + out.println("

Manage Department

"); + out.println(""); + out.println("" + + ""); + out.println("
Department Id:(int)
"); + out.println("
"); + out.println("
"); + out.println("Departments:
"); + printCollection(empService.findAllDepartments(), out); + } + + private void printManagementActions(PrintWriter out, DepartmentManager deptManager) { + out.print("Managing " + deptManager.getDepartment() + " with " + + deptManager.getDepartment().getEmployees().size() + " employees.
"); + + out.println("
"); + out.println("

Add Employee to Department

"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
"); + out.println("
"); + out.println("

Set Department Name

"); + out.println(""); + out.println("" + + ""); + out.println("
Name:(String)
"); + out.println("
"); + out.println(""); + out.println("
"); + out.println("
"); + + out.println("Employees:
"); + printCollection(empService.findAllEmployees(), out); + } + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter6/03-extendedEmExample2/undeploy.bat b/examples/Chapter6/03-extendedEmExample2/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter6/03-extendedEmExample2/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter6/04-extendedEmExample3/build.xml b/examples/Chapter6/04-extendedEmExample3/build.xml new file mode 100644 index 0000000..001bdff --- /dev/null +++ b/examples/Chapter6/04-extendedEmExample3/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/04-extendedEmExample3/deploy.bat b/examples/Chapter6/04-extendedEmExample3/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter6/04-extendedEmExample3/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter6/04-extendedEmExample3/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/04-extendedEmExample3/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..b9f4559 --- /dev/null +++ b/examples/Chapter6/04-extendedEmExample3/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/extendedEmExample3 + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/04-extendedEmExample3/etc/sql/db.sql b/examples/Chapter6/04-extendedEmExample3/etc/sql/db.sql new file mode 100644 index 0000000..88a74b3 --- /dev/null +++ b/examples/Chapter6/04-extendedEmExample3/etc/sql/db.sql @@ -0,0 +1,23 @@ +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), STARTDATE DATE, SALARY BIGINT, + DEPARTMENT_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPARTMENT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID)); + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'CA13'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'CA19'); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (1, 'Joan', 59000, {d '2003-04-16'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (2, 'Sarah', 52000, {d '2002-04-26'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (3, 'John', 55000, {d '2001-01-01'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (4, 'Roberts', 53000, {d '2001-05-23'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (5, 'Peter', 50000, {d '2002-08-06'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (6, 'Frank', 51000, {d '2003-02-17'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (7, 'Scott', 60000, {d '2004-11-14'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (8, 'Sue', 62000, {d '2005-08-18'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (9, 'Stephanie', 54000, {d '2006-06-07'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (10, 'Jennifer', 55000, {d '1999-08-11'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (11, 'Marcus', 35000, {d '1995-07-22'}, NULL); \ No newline at end of file diff --git a/examples/Chapter6/04-extendedEmExample3/etc/web/WEB-INF/web.xml b/examples/Chapter6/04-extendedEmExample3/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter6/04-extendedEmExample3/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServiceServlet + examples.servlet.EmployeeServiceServlet + + + + EmployeeServiceServlet + /EmployeeServiceServlet + + \ No newline at end of file diff --git a/examples/Chapter6/04-extendedEmExample3/src/model/examples/model/Department.java b/examples/Chapter6/04-extendedEmExample3/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter6/04-extendedEmExample3/src/model/examples/model/Department.java @@ -0,0 +1,46 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="department") + private Collection employees; + + public Department() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter6/04-extendedEmExample3/src/model/examples/model/Employee.java b/examples/Chapter6/04-extendedEmExample3/src/model/examples/model/Employee.java new file mode 100644 index 0000000..b4ce131 --- /dev/null +++ b/examples/Chapter6/04-extendedEmExample3/src/model/examples/model/Employee.java @@ -0,0 +1,59 @@ +package examples.model; + +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + @Temporal(TemporalType.DATE) + private Date startDate; + + @ManyToOne + private Department department; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + + public long getSalary() { + return salary; + } + + public Date getStartDate() { + return startDate; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department dept) { + this.department = dept; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary() + + ", dept: " + ((getDepartment() == null) ? null : getDepartment().getName()); + } +} diff --git a/examples/Chapter6/04-extendedEmExample3/src/model/examples/stateless/DepartmentManager.java b/examples/Chapter6/04-extendedEmExample3/src/model/examples/stateless/DepartmentManager.java new file mode 100644 index 0000000..6ff6396 --- /dev/null +++ b/examples/Chapter6/04-extendedEmExample3/src/model/examples/stateless/DepartmentManager.java @@ -0,0 +1,12 @@ +package examples.stateless; + +import examples.model.Department; + + +public interface DepartmentManager { + public void init(int deptId); + public Department getDepartment(); + public void setName(String name); + public void addEmployee(int empId); + public void finished(); +} diff --git a/examples/Chapter6/04-extendedEmExample3/src/model/examples/stateless/DepartmentManagerBean.java b/examples/Chapter6/04-extendedEmExample3/src/model/examples/stateless/DepartmentManagerBean.java new file mode 100644 index 0000000..50021df --- /dev/null +++ b/examples/Chapter6/04-extendedEmExample3/src/model/examples/stateless/DepartmentManagerBean.java @@ -0,0 +1,42 @@ +package examples.stateless; + +import javax.ejb.Remove; +import javax.ejb.Stateful; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.PersistenceContextType; + +import examples.model.Department; +import examples.model.Employee; + +@Stateful +public class DepartmentManagerBean implements DepartmentManager { + @PersistenceContext(unitName="EmployeeService", + type=PersistenceContextType.EXTENDED) + EntityManager em; + Department dept; + + + public void init(int deptId) { + dept = em.find(Department.class, deptId); + } + + public Department getDepartment() { + return dept; + } + + public void setName(String name) { + dept.setName(name); + } + + public void addEmployee(int empId) { + Employee emp = em.find(Employee.class, empId); + dept.getEmployees().add(emp); + emp.setDepartment(dept); + } + + @Remove + public void finished() { + } +} + diff --git a/examples/Chapter6/04-extendedEmExample3/src/model/examples/stateless/EmployeeService.java b/examples/Chapter6/04-extendedEmExample3/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..cc0558b --- /dev/null +++ b/examples/Chapter6/04-extendedEmExample3/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Department; +import examples.model.Employee; + +public interface EmployeeService { + public Collection findAllEmployees(); + public Collection findAllDepartments(); +} diff --git a/examples/Chapter6/04-extendedEmExample3/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter6/04-extendedEmExample3/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..748e5a5 --- /dev/null +++ b/examples/Chapter6/04-extendedEmExample3/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,26 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + EntityManager em; + + public Collection findAllEmployees() { + return (Collection) em.createQuery( + "SELECT e FROM Employee e").getResultList(); + } + + public Collection findAllDepartments() { + return (Collection) em.createQuery( + "SELECT d FROM Department d").getResultList(); + } +} diff --git a/examples/Chapter6/04-extendedEmExample3/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter6/04-extendedEmExample3/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..85c8c6e --- /dev/null +++ b/examples/Chapter6/04-extendedEmExample3/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,141 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.naming.InitialContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateless.DepartmentManager; +import examples.stateless.EmployeeService; + +@EJB(name="ejb/DepartmentManager", + beanInterface=DepartmentManager.class, + beanName="DepartmentManagerBean") +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 6: Stateful Session bean and EntityManager Example (Third and Correct Attempt)"; + + private final String DESCRIPTION = + "This example demonstrates how the department Entity doesn't have to be found for each "+ + "operation and the the results are updated in the database."; + + + @EJB + private EmployeeService empService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + DepartmentManager deptManager = (DepartmentManager) request.getSession().getAttribute("DepartmentManager"); + if (deptManager == null) { + try { + deptManager = (DepartmentManager) + new InitialContext().lookup("java:comp/env/ejb/DepartmentManager"); + request.getSession().setAttribute("DepartmentManager", deptManager); + } catch (Exception e) { + throw new ServletException(e); + } + } + + // process request + String action = request.getParameter("action"); + if (action == null) { + printInitAction(out); + } else if (action.equals("ManageDept")) { + deptManager.init(parseInt(request.getParameter("deptId"))); + printManagementActions(out, deptManager); + } else if (action.equals("AddEmployee")) { + deptManager.addEmployee(parseInt(request.getParameter("empId"))); + printManagementActions(out, deptManager); + } else if (action.equals("SetName")) { + deptManager.setName(request.getParameter("name")); + printManagementActions(out, deptManager); + } else if (action.equals("Finished")) { + deptManager.finished(); + request.getSession().removeAttribute("DepartmentManager"); + printInitAction(out); + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printCollection(Collection c, PrintWriter out) { + for (Object o : c) { + out.print(o + "
"); + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + } + + private void printInitAction(PrintWriter out) { + out.println("
"); + out.println("

Manage Department

"); + out.println(""); + out.println("" + + ""); + out.println("
Department Id:(int)
"); + out.println("
"); + out.println("
"); + out.println("Departments:
"); + printCollection(empService.findAllDepartments(), out); + } + + private void printManagementActions(PrintWriter out, DepartmentManager deptManager) { + out.print("Managing " + deptManager.getDepartment() + " with " + + deptManager.getDepartment().getEmployees().size() + " employees.
"); + + out.println("
"); + out.println("

Add Employee to Department

"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
"); + out.println("
"); + out.println("

Set Department Name

"); + out.println(""); + out.println("" + + ""); + out.println("
Name:(String)
"); + out.println("
"); + out.println(""); + out.println("
"); + out.println("
"); + + out.println("Employees:
"); + printCollection(empService.findAllEmployees(), out); + } + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter6/04-extendedEmExample3/undeploy.bat b/examples/Chapter6/04-extendedEmExample3/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter6/04-extendedEmExample3/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter6/05-applicationManagedSE/build.xml b/examples/Chapter6/05-applicationManagedSE/build.xml new file mode 100644 index 0000000..4157e27 --- /dev/null +++ b/examples/Chapter6/05-applicationManagedSE/build.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/05-applicationManagedSE/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/05-applicationManagedSE/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..5deeb95 --- /dev/null +++ b/examples/Chapter6/05-applicationManagedSE/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,16 @@ + + + org.eclipse.persistence.jpa.PersistenceProvider + examples.model.Employee + NONE + + + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/05-applicationManagedSE/etc/sql/db.sql b/examples/Chapter6/05-applicationManagedSE/etc/sql/db.sql new file mode 100644 index 0000000..c934828 --- /dev/null +++ b/examples/Chapter6/05-applicationManagedSE/etc/sql/db.sql @@ -0,0 +1,15 @@ +DROP TABLE EMPLOYEE; + +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, STARTDATE DATE, PRIMARY KEY (ID)); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE) VALUES (1, 'Joan', 59000, {d '2003-04-16'}); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE) VALUES (2, 'Sarah', 52000, {d '2002-04-26'}); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE) VALUES (3, 'John', 55000, {d '2001-01-01'}); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE) VALUES (4, 'Roberts', 53000, {d '2001-05-23'}); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE) VALUES (5, 'Peter', 50000, {d '2002-08-06'}); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE) VALUES (6, 'Frank', 51000, {d '2003-02-17'}); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE) VALUES (7, 'Scott', 60000, {d '2004-11-14'}); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE) VALUES (8, 'Sue', 62000, {d '2005-08-18'}); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE) VALUES (9, 'Stephanie', 54000, {d '2006-06-07'}); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE) VALUES (10, 'Jennifer', 55000, {d '1999-08-11'}); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE) VALUES (11, 'Marcus', 35000, {d '1995-07-22'}); diff --git a/examples/Chapter6/05-applicationManagedSE/run.bat b/examples/Chapter6/05-applicationManagedSE/run.bat new file mode 100644 index 0000000..15bf23b --- /dev/null +++ b/examples/Chapter6/05-applicationManagedSE/run.bat @@ -0,0 +1,2 @@ +call ../../../config/ant +pause \ No newline at end of file diff --git a/examples/Chapter6/05-applicationManagedSE/src/client/examples/client/EmployeeClient.java b/examples/Chapter6/05-applicationManagedSE/src/client/examples/client/EmployeeClient.java new file mode 100644 index 0000000..496296f --- /dev/null +++ b/examples/Chapter6/05-applicationManagedSE/src/client/examples/client/EmployeeClient.java @@ -0,0 +1,29 @@ +package examples.client; + +import java.util.Collection; +import java.util.Iterator; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import examples.model.Employee; + +public class EmployeeClient { + + public static void main(String[] args) { + EntityManagerFactory emf = + Persistence.createEntityManagerFactory("EmployeeService"); + EntityManager em = emf.createEntityManager(); + + Collection emps = em.createQuery("SELECT e FROM Employee e") + .getResultList(); + for (Iterator i = emps.iterator(); i.hasNext();) { + Employee e = (Employee) i.next(); + System.out.println("Employee " + e.getId() + ", " + e.getName()); + } + + em.close(); + emf.close(); + } +} diff --git a/examples/Chapter6/05-applicationManagedSE/src/model/examples/model/Employee.java b/examples/Chapter6/05-applicationManagedSE/src/model/examples/model/Employee.java new file mode 100644 index 0000000..40615dd --- /dev/null +++ b/examples/Chapter6/05-applicationManagedSE/src/model/examples/model/Employee.java @@ -0,0 +1,45 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + + public Employee() {} + public Employee(int id) { + this.id = id; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + " salary: " + getSalary(); + } +} diff --git a/examples/Chapter6/05-applicationManagedSE/src/model/examples/model/EmployeeService.java b/examples/Chapter6/05-applicationManagedSE/src/model/examples/model/EmployeeService.java new file mode 100644 index 0000000..9274f42 --- /dev/null +++ b/examples/Chapter6/05-applicationManagedSE/src/model/examples/model/EmployeeService.java @@ -0,0 +1,47 @@ +package examples.model; + +import java.util.Collection; + +import javax.persistence.EntityManager; +import javax.persistence.Query; + + +public class EmployeeService { + protected EntityManager em; + + public EmployeeService(EntityManager em) { + this.em = em; + } + + public Employee createEmployee(int id, String name, long salary) { + Employee emp = new Employee(id); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + return emp; + } + + public void removeEmployee(int id) { + Employee emp = findEmployee(id); + if (emp != null) { + em.remove(emp); + } + } + + public Employee raiseEmployeeSalary(int id, long raise) { + Employee emp = em.find(Employee.class, id); + if (emp != null) { + emp.setSalary(emp.getSalary() + raise); + } + return emp; + } + + public Employee findEmployee(int id) { + return em.find(Employee.class, id); + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter6/06-applicationManagedEE/build.xml b/examples/Chapter6/06-applicationManagedEE/build.xml new file mode 100644 index 0000000..78299c7 --- /dev/null +++ b/examples/Chapter6/06-applicationManagedEE/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/06-applicationManagedEE/deploy.bat b/examples/Chapter6/06-applicationManagedEE/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter6/06-applicationManagedEE/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter6/06-applicationManagedEE/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/06-applicationManagedEE/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..e09312e --- /dev/null +++ b/examples/Chapter6/06-applicationManagedEE/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,13 @@ + + + jdbc/applicationManagedEE + examples.model.User + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/06-applicationManagedEE/etc/sql/db.sql b/examples/Chapter6/06-applicationManagedEE/etc/sql/db.sql new file mode 100644 index 0000000..1147049 --- /dev/null +++ b/examples/Chapter6/06-applicationManagedEE/etc/sql/db.sql @@ -0,0 +1,9 @@ +DROP TABLE USER_DB; + +CREATE TABLE USER_DB (NAME VARCHAR(255) NOT NULL, PASSWORD VARCHAR(255), PRIMARY KEY (NAME)); + +INSERT INTO USER_DB (NAME, PASSWORD) VALUES ('Joan', 'foo'); +INSERT INTO USER_DB (NAME, PASSWORD) VALUES ('Sarah', 'bar'); +INSERT INTO USER_DB (NAME, PASSWORD) VALUES ('John', 'password'); +INSERT INTO USER_DB (NAME, PASSWORD) VALUES ('Roberts', 'hello'); +INSERT INTO USER_DB (NAME, PASSWORD) VALUES ('Peter', '1234'); \ No newline at end of file diff --git a/examples/Chapter6/06-applicationManagedEE/etc/web/WEB-INF/web.xml b/examples/Chapter6/06-applicationManagedEE/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..9437b75 --- /dev/null +++ b/examples/Chapter6/06-applicationManagedEE/etc/web/WEB-INF/web.xml @@ -0,0 +1,20 @@ + + + + LoginServlet + examples.servlet.LoginServlet + + + + LoginServlet + /LoginServlet + + + + \ No newline at end of file diff --git a/examples/Chapter6/06-applicationManagedEE/src/model/examples/model/User.java b/examples/Chapter6/06-applicationManagedEE/src/model/examples/model/User.java new file mode 100644 index 0000000..ee47e87 --- /dev/null +++ b/examples/Chapter6/06-applicationManagedEE/src/model/examples/model/User.java @@ -0,0 +1,34 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name="USER_DB") +public class User { + @Id + private String name; + private String password; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getPassword() { + return password; + } + + public void setPassword(String name) { + this.password = name; + } + + public String toString() { + return "User " + getName() + + " pwd: " + getPassword(); + } +} diff --git a/examples/Chapter6/06-applicationManagedEE/src/servlet/examples/servlet/LoginServlet.java b/examples/Chapter6/06-applicationManagedEE/src/servlet/examples/servlet/LoginServlet.java new file mode 100644 index 0000000..c353b15 --- /dev/null +++ b/examples/Chapter6/06-applicationManagedEE/src/servlet/examples/servlet/LoginServlet.java @@ -0,0 +1,91 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.PersistenceUnit; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.User; + +public class LoginServlet extends HttpServlet { + + private final String TITLE = + "Chapter 6: Application Managed EntityManager in EE Example"; + + private final String DESCRIPTION = + "This example demonstrates the basic use of an application-managed " + + "EntityManager in an EE container."; + + + @PersistenceUnit(unitName="EmployeeService") + EntityManagerFactory emf; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + String userId = request.getParameter("user"); + + // check valid user + EntityManager em = emf.createEntityManager(); + try { + if (userId != null) { + User user = em.find(User.class, userId); + if (user == null) { + // return error page + out.println("User with Id: " + userId + " not found!
"); + } else { + out.println("Found " + user + "
"); + } + } + out.println("Users:
"); + printCollection(em.createQuery("SELECT u FROM User u").getResultList(), out); + } finally { + em.close(); + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private void printCollection(Collection c, PrintWriter out) { + for (Object o : c) { + out.print(o + "
"); + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to update + out.println("

Login User

"); + out.println(""); + out.println(""); + out.println(""); + out.println("
User Id:(String)
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter6/06-applicationManagedEE/undeploy.bat b/examples/Chapter6/06-applicationManagedEE/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter6/06-applicationManagedEE/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter6/07-txScopedPersistenceContext/build.xml b/examples/Chapter6/07-txScopedPersistenceContext/build.xml new file mode 100644 index 0000000..e0e6948 --- /dev/null +++ b/examples/Chapter6/07-txScopedPersistenceContext/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/07-txScopedPersistenceContext/deploy.bat b/examples/Chapter6/07-txScopedPersistenceContext/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter6/07-txScopedPersistenceContext/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter6/07-txScopedPersistenceContext/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/07-txScopedPersistenceContext/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..b42c47c --- /dev/null +++ b/examples/Chapter6/07-txScopedPersistenceContext/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/txScopedPersistenceContext + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/07-txScopedPersistenceContext/etc/sql/db.sql b/examples/Chapter6/07-txScopedPersistenceContext/etc/sql/db.sql new file mode 100644 index 0000000..ea842a6 --- /dev/null +++ b/examples/Chapter6/07-txScopedPersistenceContext/etc/sql/db.sql @@ -0,0 +1,6 @@ +DROP TABLE EMPLOYEE; +DROP TABLE LOGRECORD; + +CREATE TABLE LOGRECORD (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + EMPNO INTEGER, ACTION VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), STARTDATE DATE, SALARY BIGINT, PRIMARY KEY (ID)); diff --git a/examples/Chapter6/07-txScopedPersistenceContext/etc/web/WEB-INF/web.xml b/examples/Chapter6/07-txScopedPersistenceContext/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter6/07-txScopedPersistenceContext/etc/web/WEB-INF/web.xml @@ -0,0 +1,16 @@ + + + + EmployeeServiceServlet + examples.servlet.EmployeeServiceServlet + + + + EmployeeServiceServlet + /EmployeeServiceServlet + + + \ No newline at end of file diff --git a/examples/Chapter6/07-txScopedPersistenceContext/src/model/examples/model/Employee.java b/examples/Chapter6/07-txScopedPersistenceContext/src/model/examples/model/Employee.java new file mode 100644 index 0000000..337dab3 --- /dev/null +++ b/examples/Chapter6/07-txScopedPersistenceContext/src/model/examples/model/Employee.java @@ -0,0 +1,57 @@ +package examples.model; + +import java.text.DateFormat; +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + @Temporal(TemporalType.DATE) + private Date startDate; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary(); + } +} diff --git a/examples/Chapter6/07-txScopedPersistenceContext/src/model/examples/model/LogRecord.java b/examples/Chapter6/07-txScopedPersistenceContext/src/model/examples/model/LogRecord.java new file mode 100644 index 0000000..ad1970f --- /dev/null +++ b/examples/Chapter6/07-txScopedPersistenceContext/src/model/examples/model/LogRecord.java @@ -0,0 +1,49 @@ +package examples.model; + + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class LogRecord { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private int empNo; + private String action; + + public LogRecord() {} + public LogRecord(int empNo, String action) { + setEmpNo(empNo); + setAction(action); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getEmpNo() { + return empNo; + } + + public void setEmpNo(int empNo) { + this.empNo = empNo; + } + + public String getAction() { + return action; + } + + public void setAction(String name) { + this.action = name; + } + + public String toString() { + return "LogRecord empNo: " + getEmpNo() + ", action: " + getAction(); + } +} diff --git a/examples/Chapter6/07-txScopedPersistenceContext/src/model/examples/stateless/AuditService.java b/examples/Chapter6/07-txScopedPersistenceContext/src/model/examples/stateless/AuditService.java new file mode 100644 index 0000000..5b0fc2a --- /dev/null +++ b/examples/Chapter6/07-txScopedPersistenceContext/src/model/examples/stateless/AuditService.java @@ -0,0 +1,6 @@ +package examples.stateless; + +public interface AuditService { + public void logTransaction(int empNo, String action); + public void logTransaction2(int empNo, String action); +} diff --git a/examples/Chapter6/07-txScopedPersistenceContext/src/model/examples/stateless/AuditServiceBean.java b/examples/Chapter6/07-txScopedPersistenceContext/src/model/examples/stateless/AuditServiceBean.java new file mode 100644 index 0000000..575521d --- /dev/null +++ b/examples/Chapter6/07-txScopedPersistenceContext/src/model/examples/stateless/AuditServiceBean.java @@ -0,0 +1,31 @@ +package examples.stateless; + +import javax.ejb.Stateless; +import javax.ejb.TransactionAttribute; +import javax.ejb.TransactionAttributeType; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Employee; +import examples.model.LogRecord; + +@Stateless +public class AuditServiceBean implements AuditService { + @PersistenceContext(unitName="EmployeeService") + private EntityManager em; + + public void logTransaction(int empId, String action) { + // verify employee number is valid + if (em.find(Employee.class, empId) == null) { + throw new IllegalArgumentException("Unknown employee id"); + } + LogRecord lr = new LogRecord(empId, action); + em.persist(lr); + } + + @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) + public void logTransaction2(int empId, String action) { + logTransaction(empId, action); + } +} + diff --git a/examples/Chapter6/07-txScopedPersistenceContext/src/model/examples/stateless/EmployeeService.java b/examples/Chapter6/07-txScopedPersistenceContext/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..9b8ef67 --- /dev/null +++ b/examples/Chapter6/07-txScopedPersistenceContext/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public void createEmployee(Employee emp); + public void createEmployee2(Employee emp); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter6/07-txScopedPersistenceContext/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter6/07-txScopedPersistenceContext/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..2ba9cd8 --- /dev/null +++ b/examples/Chapter6/07-txScopedPersistenceContext/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,33 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.EJB; +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + private EntityManager em; + @EJB + AuditService audit; + + public void createEmployee(Employee emp) { + em.persist(emp); + audit.logTransaction(emp.getId(), "created employee"); + } + + public void createEmployee2(Employee emp) { + em.persist(emp); + audit.logTransaction2(emp.getId(), "created employee"); + } + + public Collection findAllEmployees() { + return (Collection) em.createQuery( + "SELECT e FROM Employee e").getResultList(); + } +} diff --git a/examples/Chapter6/07-txScopedPersistenceContext/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter6/07-txScopedPersistenceContext/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..66acc8c --- /dev/null +++ b/examples/Chapter6/07-txScopedPersistenceContext/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,111 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.stateless.EmployeeService; + +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 6: Tx-scoped Persistence Context Example"; + + private final String DESCRIPTION = + "This example shows the basic use of a tx-scoped persistence " + + "context. The second create button shows what happens when the " + + "'logTransaction' operation is marked REQUIRES_NEW"; + + + @EJB EmployeeService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("Create")) { + Employee emp = new Employee(); + emp.setId(parseInt(request.getParameter("createId"))); + emp.setName(request.getParameter("name")); + emp.setSalary(parseLong(request.getParameter("salary"))); + service.createEmployee(emp); + out.println("Created " + emp); + } else if (action.equals("Create2")) { + Employee emp = new Employee(); + emp.setId(parseInt(request.getParameter("createId"))); + emp.setName(request.getParameter("name")); + emp.setSalary(parseLong(request.getParameter("salary"))); + try { + service.createEmployee2(emp); + out.println("Created " + emp); + } catch (Exception e) { + out.println(e.getCause()); + } + } + + out.println("Employees:
"); + for (Employee emp : service.findAllEmployees()) { + out.print(emp + "
"); + } + printHtmlFooter(out); + + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println(""); + // form to create + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println("" + + "" + + ""); + out.println("
Id:(int)
Name:(String)
Salary:(long)
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter6/07-txScopedPersistenceContext/undeploy.bat b/examples/Chapter6/07-txScopedPersistenceContext/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter6/07-txScopedPersistenceContext/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter6/08-extendedPersistenceContext/build.xml b/examples/Chapter6/08-extendedPersistenceContext/build.xml new file mode 100644 index 0000000..5027660 --- /dev/null +++ b/examples/Chapter6/08-extendedPersistenceContext/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/08-extendedPersistenceContext/deploy.bat b/examples/Chapter6/08-extendedPersistenceContext/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter6/08-extendedPersistenceContext/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter6/08-extendedPersistenceContext/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/08-extendedPersistenceContext/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..2b9ca13 --- /dev/null +++ b/examples/Chapter6/08-extendedPersistenceContext/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/extendedPersistenceContext + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/08-extendedPersistenceContext/etc/sql/db.sql b/examples/Chapter6/08-extendedPersistenceContext/etc/sql/db.sql new file mode 100644 index 0000000..93114a2 --- /dev/null +++ b/examples/Chapter6/08-extendedPersistenceContext/etc/sql/db.sql @@ -0,0 +1,26 @@ +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; +DROP TABLE LOGRECORD; + +CREATE TABLE LOGRECORD (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + EMPNO INTEGER, ACTION VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), STARTDATE DATE, SALARY BIGINT, + DEPARTMENT_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPARTMENT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID)); + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'CA13'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'CA19'); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (1, 'Joan', 59000, {d '2003-04-16'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (2, 'Sarah', 52000, {d '2002-04-26'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (3, 'John', 55000, {d '2001-01-01'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (4, 'Roberts', 53000, {d '2001-05-23'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (5, 'Peter', 50000, {d '2002-08-06'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (6, 'Frank', 51000, {d '2003-02-17'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (7, 'Scott', 60000, {d '2004-11-14'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (8, 'Sue', 62000, {d '2005-08-18'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (9, 'Stephanie', 54000, {d '2006-06-07'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (10, 'Jennifer', 55000, {d '1999-08-11'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (11, 'Marcus', 35000, {d '1995-07-22'}, NULL); \ No newline at end of file diff --git a/examples/Chapter6/08-extendedPersistenceContext/etc/web/WEB-INF/web.xml b/examples/Chapter6/08-extendedPersistenceContext/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter6/08-extendedPersistenceContext/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServiceServlet + examples.servlet.EmployeeServiceServlet + + + + EmployeeServiceServlet + /EmployeeServiceServlet + + \ No newline at end of file diff --git a/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/model/Department.java b/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/model/Department.java @@ -0,0 +1,46 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="department") + private Collection employees; + + public Department() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/model/Employee.java b/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/model/Employee.java new file mode 100644 index 0000000..b4ce131 --- /dev/null +++ b/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/model/Employee.java @@ -0,0 +1,59 @@ +package examples.model; + +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + @Temporal(TemporalType.DATE) + private Date startDate; + + @ManyToOne + private Department department; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + + public long getSalary() { + return salary; + } + + public Date getStartDate() { + return startDate; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department dept) { + this.department = dept; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary() + + ", dept: " + ((getDepartment() == null) ? null : getDepartment().getName()); + } +} diff --git a/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/model/LogRecord.java b/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/model/LogRecord.java new file mode 100644 index 0000000..ad1970f --- /dev/null +++ b/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/model/LogRecord.java @@ -0,0 +1,49 @@ +package examples.model; + + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class LogRecord { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private int empNo; + private String action; + + public LogRecord() {} + public LogRecord(int empNo, String action) { + setEmpNo(empNo); + setAction(action); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getEmpNo() { + return empNo; + } + + public void setEmpNo(int empNo) { + this.empNo = empNo; + } + + public String getAction() { + return action; + } + + public void setAction(String name) { + this.action = name; + } + + public String toString() { + return "LogRecord empNo: " + getEmpNo() + ", action: " + getAction(); + } +} diff --git a/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/stateless/AuditService.java b/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/stateless/AuditService.java new file mode 100644 index 0000000..c2ad1c0 --- /dev/null +++ b/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/stateless/AuditService.java @@ -0,0 +1,5 @@ +package examples.stateless; + +public interface AuditService { + public void logTransaction(int empNo, String action); +} diff --git a/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/stateless/AuditServiceBean.java b/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/stateless/AuditServiceBean.java new file mode 100644 index 0000000..2fbabe1 --- /dev/null +++ b/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/stateless/AuditServiceBean.java @@ -0,0 +1,24 @@ +package examples.stateless; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Employee; +import examples.model.LogRecord; + +@Stateless +public class AuditServiceBean implements AuditService { + @PersistenceContext(unitName="EmployeeService") + private EntityManager em; + + public void logTransaction(int empId, String action) { + // verify employee number is valid + if (em.find(Employee.class, empId) == null) { + throw new IllegalArgumentException("Unknown employee id"); + } + LogRecord lr = new LogRecord(empId, action); + em.persist(lr); + } +} + diff --git a/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/stateless/DepartmentManager.java b/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/stateless/DepartmentManager.java new file mode 100644 index 0000000..6ff6396 --- /dev/null +++ b/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/stateless/DepartmentManager.java @@ -0,0 +1,12 @@ +package examples.stateless; + +import examples.model.Department; + + +public interface DepartmentManager { + public void init(int deptId); + public Department getDepartment(); + public void setName(String name); + public void addEmployee(int empId); + public void finished(); +} diff --git a/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/stateless/DepartmentManagerBean.java b/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/stateless/DepartmentManagerBean.java new file mode 100644 index 0000000..cecaa3c --- /dev/null +++ b/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/stateless/DepartmentManagerBean.java @@ -0,0 +1,48 @@ +package examples.stateless; + +import javax.ejb.EJB; +import javax.ejb.Remove; +import javax.ejb.Stateful; +import javax.ejb.TransactionAttribute; +import javax.ejb.TransactionAttributeType; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.PersistenceContextType; + +import examples.model.Department; +import examples.model.Employee; + +@Stateful +@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) +public class DepartmentManagerBean implements DepartmentManager { + @PersistenceContext(unitName="EmployeeService", + type=PersistenceContextType.EXTENDED) + EntityManager em; + Department dept; + @EJB AuditService audit; + + public void init(int deptId) { + dept = em.find(Department.class, deptId); + } + + public Department getDepartment() { + return dept; + } + + public void setName(String name) { + dept.setName(name); + } + + public void addEmployee(int empId) { + Employee emp = em.find(Employee.class, empId); + dept.getEmployees().add(emp); + emp.setDepartment(dept); + audit.logTransaction(emp.getId(), + "added to department " + dept.getName()); + } + + @Remove + public void finished() { + } +} + diff --git a/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/stateless/EmployeeService.java b/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..cc0558b --- /dev/null +++ b/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Department; +import examples.model.Employee; + +public interface EmployeeService { + public Collection findAllEmployees(); + public Collection findAllDepartments(); +} diff --git a/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..748e5a5 --- /dev/null +++ b/examples/Chapter6/08-extendedPersistenceContext/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,26 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + EntityManager em; + + public Collection findAllEmployees() { + return (Collection) em.createQuery( + "SELECT e FROM Employee e").getResultList(); + } + + public Collection findAllDepartments() { + return (Collection) em.createQuery( + "SELECT d FROM Department d").getResultList(); + } +} diff --git a/examples/Chapter6/08-extendedPersistenceContext/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter6/08-extendedPersistenceContext/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..6c77a9f --- /dev/null +++ b/examples/Chapter6/08-extendedPersistenceContext/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,140 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.naming.InitialContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateless.DepartmentManager; +import examples.stateless.EmployeeService; + +@EJB(name="ejb/DepartmentManager", + beanInterface=DepartmentManager.class, + beanName="DepartmentManagerBean") +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 6: Extended Persistence Context Propagation Example"; + + private final String DESCRIPTION = + "This example shows the basic use of an extended persistence " + + "context and its propagation."; + + + @EJB + private EmployeeService empService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + DepartmentManager deptManager = (DepartmentManager) request.getSession().getAttribute("DepartmentManager"); + if (deptManager == null) { + try { + deptManager = (DepartmentManager) + new InitialContext().lookup("java:comp/env/ejb/DepartmentManager"); + request.getSession().setAttribute("DepartmentManager", deptManager); + } catch (Exception e) { + throw new ServletException(e); + } + } + + // process request + String action = request.getParameter("action"); + if (action == null) { + printInitAction(out); + } else if (action.equals("ManageDept")) { + deptManager.init(parseInt(request.getParameter("deptId"))); + printManagementActions(out, deptManager); + } else if (action.equals("AddEmployee")) { + deptManager.addEmployee(parseInt(request.getParameter("empId"))); + printManagementActions(out, deptManager); + } else if (action.equals("SetName")) { + deptManager.setName(request.getParameter("name")); + printManagementActions(out, deptManager); + } else if (action.equals("Finished")) { + deptManager.finished(); + request.getSession().removeAttribute("DepartmentManager"); + printInitAction(out); + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printCollection(Collection c, PrintWriter out) { + for (Object o : c) { + out.print(o + "
"); + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + } + + private void printInitAction(PrintWriter out) { + out.println(""); + out.println("

Manage Department

"); + out.println(""); + out.println("" + + ""); + out.println("
Department Id:(int)
"); + out.println(""); + out.println("
"); + out.println("Departments:
"); + printCollection(empService.findAllDepartments(), out); + } + + private void printManagementActions(PrintWriter out, DepartmentManager deptManager) { + out.print("Managing " + deptManager.getDepartment() + "
"); + + out.println("
"); + out.println("

Add Employee to Department

"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
"); + out.println("
"); + out.println("

Add Set Department Name

"); + out.println(""); + out.println("" + + ""); + out.println("
Name:(String)
"); + out.println("
"); + out.println(""); + out.println("
"); + out.println("
"); + + out.println("Employees:
"); + printCollection(empService.findAllEmployees(), out); + } + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter6/08-extendedPersistenceContext/undeploy.bat b/examples/Chapter6/08-extendedPersistenceContext/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter6/08-extendedPersistenceContext/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter6/09-persistenceContextCollision/build.xml b/examples/Chapter6/09-persistenceContextCollision/build.xml new file mode 100644 index 0000000..43b6811 --- /dev/null +++ b/examples/Chapter6/09-persistenceContextCollision/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/09-persistenceContextCollision/deploy.bat b/examples/Chapter6/09-persistenceContextCollision/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter6/09-persistenceContextCollision/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter6/09-persistenceContextCollision/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/09-persistenceContextCollision/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..6c6365c --- /dev/null +++ b/examples/Chapter6/09-persistenceContextCollision/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/persistenceContextCollision + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/09-persistenceContextCollision/etc/sql/db.sql b/examples/Chapter6/09-persistenceContextCollision/etc/sql/db.sql new file mode 100644 index 0000000..93114a2 --- /dev/null +++ b/examples/Chapter6/09-persistenceContextCollision/etc/sql/db.sql @@ -0,0 +1,26 @@ +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; +DROP TABLE LOGRECORD; + +CREATE TABLE LOGRECORD (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + EMPNO INTEGER, ACTION VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), STARTDATE DATE, SALARY BIGINT, + DEPARTMENT_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPARTMENT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID)); + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'CA13'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'CA19'); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (1, 'Joan', 59000, {d '2003-04-16'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (2, 'Sarah', 52000, {d '2002-04-26'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (3, 'John', 55000, {d '2001-01-01'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (4, 'Roberts', 53000, {d '2001-05-23'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (5, 'Peter', 50000, {d '2002-08-06'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (6, 'Frank', 51000, {d '2003-02-17'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (7, 'Scott', 60000, {d '2004-11-14'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (8, 'Sue', 62000, {d '2005-08-18'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (9, 'Stephanie', 54000, {d '2006-06-07'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (10, 'Jennifer', 55000, {d '1999-08-11'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (11, 'Marcus', 35000, {d '1995-07-22'}, NULL); \ No newline at end of file diff --git a/examples/Chapter6/09-persistenceContextCollision/etc/web/WEB-INF/web.xml b/examples/Chapter6/09-persistenceContextCollision/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter6/09-persistenceContextCollision/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServiceServlet + examples.servlet.EmployeeServiceServlet + + + + EmployeeServiceServlet + /EmployeeServiceServlet + + \ No newline at end of file diff --git a/examples/Chapter6/09-persistenceContextCollision/src/model/examples/model/Department.java b/examples/Chapter6/09-persistenceContextCollision/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter6/09-persistenceContextCollision/src/model/examples/model/Department.java @@ -0,0 +1,46 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="department") + private Collection employees; + + public Department() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter6/09-persistenceContextCollision/src/model/examples/model/Employee.java b/examples/Chapter6/09-persistenceContextCollision/src/model/examples/model/Employee.java new file mode 100644 index 0000000..b4ce131 --- /dev/null +++ b/examples/Chapter6/09-persistenceContextCollision/src/model/examples/model/Employee.java @@ -0,0 +1,59 @@ +package examples.model; + +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + @Temporal(TemporalType.DATE) + private Date startDate; + + @ManyToOne + private Department department; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + + public long getSalary() { + return salary; + } + + public Date getStartDate() { + return startDate; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department dept) { + this.department = dept; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary() + + ", dept: " + ((getDepartment() == null) ? null : getDepartment().getName()); + } +} diff --git a/examples/Chapter6/09-persistenceContextCollision/src/model/examples/model/LogRecord.java b/examples/Chapter6/09-persistenceContextCollision/src/model/examples/model/LogRecord.java new file mode 100644 index 0000000..ad1970f --- /dev/null +++ b/examples/Chapter6/09-persistenceContextCollision/src/model/examples/model/LogRecord.java @@ -0,0 +1,49 @@ +package examples.model; + + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class LogRecord { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private int empNo; + private String action; + + public LogRecord() {} + public LogRecord(int empNo, String action) { + setEmpNo(empNo); + setAction(action); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getEmpNo() { + return empNo; + } + + public void setEmpNo(int empNo) { + this.empNo = empNo; + } + + public String getAction() { + return action; + } + + public void setAction(String name) { + this.action = name; + } + + public String toString() { + return "LogRecord empNo: " + getEmpNo() + ", action: " + getAction(); + } +} diff --git a/examples/Chapter6/09-persistenceContextCollision/src/model/examples/stateless/AuditService.java b/examples/Chapter6/09-persistenceContextCollision/src/model/examples/stateless/AuditService.java new file mode 100644 index 0000000..c2ad1c0 --- /dev/null +++ b/examples/Chapter6/09-persistenceContextCollision/src/model/examples/stateless/AuditService.java @@ -0,0 +1,5 @@ +package examples.stateless; + +public interface AuditService { + public void logTransaction(int empNo, String action); +} diff --git a/examples/Chapter6/09-persistenceContextCollision/src/model/examples/stateless/AuditServiceBean.java b/examples/Chapter6/09-persistenceContextCollision/src/model/examples/stateless/AuditServiceBean.java new file mode 100644 index 0000000..9169339 --- /dev/null +++ b/examples/Chapter6/09-persistenceContextCollision/src/model/examples/stateless/AuditServiceBean.java @@ -0,0 +1,31 @@ +package examples.stateless; + +import javax.ejb.Stateless; +import javax.ejb.TransactionAttribute; +import javax.ejb.TransactionAttributeType; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Employee; +import examples.model.LogRecord; + +@Stateless +public class AuditServiceBean implements AuditService { + @PersistenceContext(unitName="EmployeeService") + private EntityManager em; + + public void logTransaction(int empId, String action) { + // verify employee number is valid + if (em.find(Employee.class, empId) == null) { + throw new IllegalArgumentException("Unknown employee id"); + } + LogRecord lr = new LogRecord(empId, action); + em.persist(lr); + } + + @TransactionAttribute(TransactionAttributeType.REQUIRED) + public void logTransaction2(int empId, String action) { + logTransaction(empId, action); + } +} + diff --git a/examples/Chapter6/09-persistenceContextCollision/src/model/examples/stateless/DepartmentManager.java b/examples/Chapter6/09-persistenceContextCollision/src/model/examples/stateless/DepartmentManager.java new file mode 100644 index 0000000..185ee47 --- /dev/null +++ b/examples/Chapter6/09-persistenceContextCollision/src/model/examples/stateless/DepartmentManager.java @@ -0,0 +1,14 @@ +package examples.stateless; + +import examples.model.Department; + + +public interface DepartmentManager { + public void init(int deptId); + public Department getDepartment(); + public String getName(); + public void setName(String name); + public void addEmployee(int empId); + public void addEmployee2(int empId); + public void finished(); +} diff --git a/examples/Chapter6/09-persistenceContextCollision/src/model/examples/stateless/DepartmentManagerBean.java b/examples/Chapter6/09-persistenceContextCollision/src/model/examples/stateless/DepartmentManagerBean.java new file mode 100644 index 0000000..dbc16df --- /dev/null +++ b/examples/Chapter6/09-persistenceContextCollision/src/model/examples/stateless/DepartmentManagerBean.java @@ -0,0 +1,61 @@ +package examples.stateless; + +import javax.ejb.EJB; +import javax.ejb.Remove; +import javax.ejb.Stateful; +import javax.ejb.TransactionAttribute; +import javax.ejb.TransactionAttributeType; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.PersistenceContextType; + +import examples.model.Department; +import examples.model.Employee; + +@Stateful +@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) +public class DepartmentManagerBean implements DepartmentManager { + @PersistenceContext(unitName="EmployeeService", + type=PersistenceContextType.EXTENDED) + EntityManager em; + Department dept; + @EJB AuditService audit; + + public void init(int deptId) { + dept = em.find(Department.class, deptId); + } + + public Department getDepartment() { + return dept; + } + + @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) + public String getName() { + return dept.getName(); + } + + public void setName(String name) { + dept.setName(name); + } + + public void addEmployee(int empId) { + Employee emp = em.find(Employee.class, empId); + dept.getEmployees().add(emp); + emp.setDepartment(dept); + audit.logTransaction(emp.getId(), + "added to department " + dept.getName()); + } + + @TransactionAttribute(TransactionAttributeType.REQUIRED) + public void addEmployee2(int empId) { + Employee emp = em.find(Employee.class, empId); + dept.getEmployees().add(emp); + emp.setDepartment(dept); + audit.logTransaction(emp.getId(), + "added to department " + dept.getName()); + } + @Remove + public void finished() { + } +} + diff --git a/examples/Chapter6/09-persistenceContextCollision/src/model/examples/stateless/EmployeeService.java b/examples/Chapter6/09-persistenceContextCollision/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..cc0558b --- /dev/null +++ b/examples/Chapter6/09-persistenceContextCollision/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Department; +import examples.model.Employee; + +public interface EmployeeService { + public Collection findAllEmployees(); + public Collection findAllDepartments(); +} diff --git a/examples/Chapter6/09-persistenceContextCollision/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter6/09-persistenceContextCollision/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..748e5a5 --- /dev/null +++ b/examples/Chapter6/09-persistenceContextCollision/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,26 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + EntityManager em; + + public Collection findAllEmployees() { + return (Collection) em.createQuery( + "SELECT e FROM Employee e").getResultList(); + } + + public Collection findAllDepartments() { + return (Collection) em.createQuery( + "SELECT d FROM Department d").getResultList(); + } +} diff --git a/examples/Chapter6/09-persistenceContextCollision/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter6/09-persistenceContextCollision/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..760ecdf --- /dev/null +++ b/examples/Chapter6/09-persistenceContextCollision/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,158 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.annotation.Resource; +import javax.ejb.EJB; +import javax.naming.InitialContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.transaction.UserTransaction; + +import examples.stateless.DepartmentManager; +import examples.stateless.EmployeeService; + +@EJB(name="ejb/DepartmentManager", + beanInterface=DepartmentManager.class, + beanName="DepartmentManagerBean") +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 6: Persistence Context Collision Example"; + + private final String DESCRIPTION = + "This example shows the basic use of an extended persistence " + + "context and how to avoid collisions. The second create button " + + "shows what happens when the 'addEmployee' operation is marked " + + "REQUIRED and there's already a tx in place."; + + + @EJB + private EmployeeService empService; + @Resource UserTransaction tx; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + DepartmentManager deptManager = (DepartmentManager) request.getSession().getAttribute("DepartmentManager"); + if (deptManager == null) { + try { + deptManager = (DepartmentManager) + new InitialContext().lookup("java:comp/env/ejb/DepartmentManager"); + request.getSession().setAttribute("DepartmentManager", deptManager); + } catch (Exception e) { + throw new ServletException(e); + } + } + + // process request + String action = request.getParameter("action"); + if (action == null) { + printInitAction(out); + } else if (action.equals("ManageDept")) { + deptManager.init(parseInt(request.getParameter("deptId"))); + printManagementActions(out, deptManager); + } else if (action.equals("AddEmployee")) { + deptManager.addEmployee(parseInt(request.getParameter("empId"))); + printManagementActions(out, deptManager); + } else if (action.equals("AddEmployee2")) { + try { + tx.begin(); + deptManager.addEmployee2(parseInt(request.getParameter("empId"))); + printManagementActions(out, deptManager); + tx.rollback(); + } catch (Exception e) { + out.print(e); + request.getSession().removeAttribute("DepartmentManager"); + printInitAction(out); + } finally { + } + } else if (action.equals("SetName")) { + deptManager.setName(request.getParameter("name")); + printManagementActions(out, deptManager); + } else if (action.equals("Finished")) { + deptManager.finished(); + request.getSession().removeAttribute("DepartmentManager"); + printInitAction(out); + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printCollection(Collection c, PrintWriter out) { + for (Object o : c) { + out.print(o + "
"); + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + } + + private void printInitAction(PrintWriter out) { + out.println("
"); + out.println("

Manage Department

"); + out.println(""); + out.println("" + + ""); + out.println("
Department Id:(int)
"); + out.println("
"); + out.println("
"); + out.println("Departments:
"); + printCollection(empService.findAllDepartments(), out); + } + + private void printManagementActions(PrintWriter out, DepartmentManager deptManager) { + out.print("Managing " + deptManager.getDepartment() + "
"); + + out.println("
"); + out.println("

Add Employee to Department

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
"); + out.println("
"); + out.println("

Add Set Department Name

"); + out.println(""); + out.println("" + + ""); + out.println("
Name:(String)
"); + out.println("
"); + out.println(""); + out.println("
"); + out.println("
"); + + out.println("Employees:
"); + printCollection(empService.findAllEmployees(), out); + } + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter6/09-persistenceContextCollision/undeploy.bat b/examples/Chapter6/09-persistenceContextCollision/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter6/09-persistenceContextCollision/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter6/10-persistenceContextInheritance/build.xml b/examples/Chapter6/10-persistenceContextInheritance/build.xml new file mode 100644 index 0000000..7ab91af --- /dev/null +++ b/examples/Chapter6/10-persistenceContextInheritance/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/10-persistenceContextInheritance/deploy.bat b/examples/Chapter6/10-persistenceContextInheritance/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter6/10-persistenceContextInheritance/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter6/10-persistenceContextInheritance/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/10-persistenceContextInheritance/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..4c8a117 --- /dev/null +++ b/examples/Chapter6/10-persistenceContextInheritance/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/persistenceContextInheritance + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/10-persistenceContextInheritance/etc/sql/db.sql b/examples/Chapter6/10-persistenceContextInheritance/etc/sql/db.sql new file mode 100644 index 0000000..93114a2 --- /dev/null +++ b/examples/Chapter6/10-persistenceContextInheritance/etc/sql/db.sql @@ -0,0 +1,26 @@ +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; +DROP TABLE LOGRECORD; + +CREATE TABLE LOGRECORD (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + EMPNO INTEGER, ACTION VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), STARTDATE DATE, SALARY BIGINT, + DEPARTMENT_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPARTMENT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID)); + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'CA13'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'CA19'); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (1, 'Joan', 59000, {d '2003-04-16'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (2, 'Sarah', 52000, {d '2002-04-26'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (3, 'John', 55000, {d '2001-01-01'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (4, 'Roberts', 53000, {d '2001-05-23'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (5, 'Peter', 50000, {d '2002-08-06'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (6, 'Frank', 51000, {d '2003-02-17'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (7, 'Scott', 60000, {d '2004-11-14'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (8, 'Sue', 62000, {d '2005-08-18'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (9, 'Stephanie', 54000, {d '2006-06-07'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (10, 'Jennifer', 55000, {d '1999-08-11'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (11, 'Marcus', 35000, {d '1995-07-22'}, NULL); \ No newline at end of file diff --git a/examples/Chapter6/10-persistenceContextInheritance/etc/web/WEB-INF/web.xml b/examples/Chapter6/10-persistenceContextInheritance/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter6/10-persistenceContextInheritance/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServiceServlet + examples.servlet.EmployeeServiceServlet + + + + EmployeeServiceServlet + /EmployeeServiceServlet + + \ No newline at end of file diff --git a/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/model/Department.java b/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/model/Department.java @@ -0,0 +1,46 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="department") + private Collection employees; + + public Department() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/model/Employee.java b/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/model/Employee.java new file mode 100644 index 0000000..b4ce131 --- /dev/null +++ b/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/model/Employee.java @@ -0,0 +1,59 @@ +package examples.model; + +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + @Temporal(TemporalType.DATE) + private Date startDate; + + @ManyToOne + private Department department; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + + public long getSalary() { + return salary; + } + + public Date getStartDate() { + return startDate; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department dept) { + this.department = dept; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary() + + ", dept: " + ((getDepartment() == null) ? null : getDepartment().getName()); + } +} diff --git a/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/model/LogRecord.java b/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/model/LogRecord.java new file mode 100644 index 0000000..ad1970f --- /dev/null +++ b/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/model/LogRecord.java @@ -0,0 +1,49 @@ +package examples.model; + + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class LogRecord { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private int empNo; + private String action; + + public LogRecord() {} + public LogRecord(int empNo, String action) { + setEmpNo(empNo); + setAction(action); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getEmpNo() { + return empNo; + } + + public void setEmpNo(int empNo) { + this.empNo = empNo; + } + + public String getAction() { + return action; + } + + public void setAction(String name) { + this.action = name; + } + + public String toString() { + return "LogRecord empNo: " + getEmpNo() + ", action: " + getAction(); + } +} diff --git a/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/stateless/AuditService.java b/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/stateless/AuditService.java new file mode 100644 index 0000000..c2ad1c0 --- /dev/null +++ b/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/stateless/AuditService.java @@ -0,0 +1,5 @@ +package examples.stateless; + +public interface AuditService { + public void logTransaction(int empNo, String action); +} diff --git a/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/stateless/AuditServiceBean.java b/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/stateless/AuditServiceBean.java new file mode 100644 index 0000000..2fbabe1 --- /dev/null +++ b/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/stateless/AuditServiceBean.java @@ -0,0 +1,24 @@ +package examples.stateless; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Employee; +import examples.model.LogRecord; + +@Stateless +public class AuditServiceBean implements AuditService { + @PersistenceContext(unitName="EmployeeService") + private EntityManager em; + + public void logTransaction(int empId, String action) { + // verify employee number is valid + if (em.find(Employee.class, empId) == null) { + throw new IllegalArgumentException("Unknown employee id"); + } + LogRecord lr = new LogRecord(empId, action); + em.persist(lr); + } +} + diff --git a/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/stateless/DepartmentManager.java b/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/stateless/DepartmentManager.java new file mode 100644 index 0000000..6ff6396 --- /dev/null +++ b/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/stateless/DepartmentManager.java @@ -0,0 +1,12 @@ +package examples.stateless; + +import examples.model.Department; + + +public interface DepartmentManager { + public void init(int deptId); + public Department getDepartment(); + public void setName(String name); + public void addEmployee(int empId); + public void finished(); +} diff --git a/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/stateless/DepartmentManagerBean.java b/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/stateless/DepartmentManagerBean.java new file mode 100644 index 0000000..4db6e6f --- /dev/null +++ b/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/stateless/DepartmentManagerBean.java @@ -0,0 +1,50 @@ +package examples.stateless; + +import javax.ejb.EJB; +import javax.ejb.Remove; +import javax.ejb.Stateful; +import javax.ejb.TransactionAttribute; +import javax.ejb.TransactionAttributeType; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.PersistenceContextType; + +import examples.model.Department; +import examples.model.Employee; + +@Stateful +@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) +public class DepartmentManagerBean implements DepartmentManager { + @PersistenceContext(unitName="EmployeeService", + type=PersistenceContextType.EXTENDED) + EntityManager em; + Department dept; + @EJB AuditService audit; + @EJB EmployeeManager manager; + + public void init(int deptId) { + dept = em.find(Department.class, deptId); + manager.init(); + } + + public Department getDepartment() { + return dept; + } + + public void setName(String name) { + dept.setName(name); + } + + public void addEmployee(int empId) { + Employee emp = em.find(Employee.class, empId); + dept.getEmployees().add(emp); + emp.setDepartment(dept); + audit.logTransaction(emp.getId(), + "added to department " + dept.getName()); + } + + @Remove + public void finished() { + } +} + diff --git a/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/stateless/EmployeeManager.java b/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/stateless/EmployeeManager.java new file mode 100644 index 0000000..34a1b21 --- /dev/null +++ b/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/stateless/EmployeeManager.java @@ -0,0 +1,6 @@ +package examples.stateless; + +public interface EmployeeManager { + public void init(); + public void finished(); +} diff --git a/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/stateless/EmployeeManagerBean.java b/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/stateless/EmployeeManagerBean.java new file mode 100644 index 0000000..428a147 --- /dev/null +++ b/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/stateless/EmployeeManagerBean.java @@ -0,0 +1,25 @@ +package examples.stateless; + +import javax.ejb.Remove; +import javax.ejb.Stateful; +import javax.ejb.TransactionAttribute; +import javax.ejb.TransactionAttributeType; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.PersistenceContextType; + +@Stateful +@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) +public class EmployeeManagerBean implements EmployeeManager { + @PersistenceContext(unitName="EmployeeService", + type=PersistenceContextType.EXTENDED) + EntityManager em; + + public void init() { + } + + @Remove + public void finished() { + } +} + diff --git a/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/stateless/EmployeeService.java b/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..cc0558b --- /dev/null +++ b/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Department; +import examples.model.Employee; + +public interface EmployeeService { + public Collection findAllEmployees(); + public Collection findAllDepartments(); +} diff --git a/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..748e5a5 --- /dev/null +++ b/examples/Chapter6/10-persistenceContextInheritance/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,26 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + EntityManager em; + + public Collection findAllEmployees() { + return (Collection) em.createQuery( + "SELECT e FROM Employee e").getResultList(); + } + + public Collection findAllDepartments() { + return (Collection) em.createQuery( + "SELECT d FROM Department d").getResultList(); + } +} diff --git a/examples/Chapter6/10-persistenceContextInheritance/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter6/10-persistenceContextInheritance/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..a2c0e36 --- /dev/null +++ b/examples/Chapter6/10-persistenceContextInheritance/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,141 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.naming.InitialContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateless.DepartmentManager; +import examples.stateless.EmployeeService; + +@EJB(name="ejb/DepartmentManager", + beanInterface=DepartmentManager.class, + beanName="DepartmentManagerBean") +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 6: Extended Persistence Context Inheritance Example"; + + private final String DESCRIPTION = + "This example shows the basic use of an extended persistence " + + "context and its inheritance in SFSBs."; + + + @EJB + private EmployeeService empService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + DepartmentManager deptManager = (DepartmentManager) request.getSession().getAttribute("DepartmentManager"); + if (deptManager == null) { + try { + deptManager = (DepartmentManager) + new InitialContext().lookup("java:comp/env/ejb/DepartmentManager"); + System.out.println("deptManager: " + deptManager); + request.getSession().setAttribute("DepartmentManager", deptManager); + } catch (Exception e) { + throw new ServletException(e); + } + } + + // process request + String action = request.getParameter("action"); + if (action == null) { + printInitAction(out); + } else if (action.equals("ManageDept")) { + deptManager.init(parseInt(request.getParameter("deptId"))); + printManagementActions(out, deptManager); + } else if (action.equals("AddEmployee")) { + deptManager.addEmployee(parseInt(request.getParameter("empId"))); + printManagementActions(out, deptManager); + } else if (action.equals("SetName")) { + deptManager.setName(request.getParameter("name")); + printManagementActions(out, deptManager); + } else if (action.equals("Finished")) { + deptManager.finished(); + request.getSession().removeAttribute("DepartmentManager"); + printInitAction(out); + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printCollection(Collection c, PrintWriter out) { + for (Object o : c) { + out.print(o + "
"); + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + } + + private void printInitAction(PrintWriter out) { + out.println("
"); + out.println("

Manage Department

"); + out.println(""); + out.println("" + + ""); + out.println("
Department Id:(int)
"); + out.println("
"); + out.println("
"); + out.println("Departments:
"); + printCollection(empService.findAllDepartments(), out); + } + + private void printManagementActions(PrintWriter out, DepartmentManager deptManager) { + out.print("Managing " + deptManager.getDepartment() + "
"); + + out.println("
"); + out.println("

Add Employee to Department

"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
"); + out.println("
"); + out.println("

Add Set Department Name

"); + out.println(""); + out.println("" + + ""); + out.println("
Name:(String)
"); + out.println("
"); + out.println(""); + out.println("
"); + out.println("
"); + + out.println("Employees:
"); + printCollection(empService.findAllEmployees(), out); + } + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter6/10-persistenceContextInheritance/undeploy.bat b/examples/Chapter6/10-persistenceContextInheritance/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter6/10-persistenceContextInheritance/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter6/11-applicationManagedJTA/build.xml b/examples/Chapter6/11-applicationManagedJTA/build.xml new file mode 100644 index 0000000..6179b05 --- /dev/null +++ b/examples/Chapter6/11-applicationManagedJTA/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/11-applicationManagedJTA/deploy.bat b/examples/Chapter6/11-applicationManagedJTA/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter6/11-applicationManagedJTA/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter6/11-applicationManagedJTA/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/11-applicationManagedJTA/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..52cdb12 --- /dev/null +++ b/examples/Chapter6/11-applicationManagedJTA/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/applicationManagedJTA + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/11-applicationManagedJTA/etc/sql/db.sql b/examples/Chapter6/11-applicationManagedJTA/etc/sql/db.sql new file mode 100644 index 0000000..88a74b3 --- /dev/null +++ b/examples/Chapter6/11-applicationManagedJTA/etc/sql/db.sql @@ -0,0 +1,23 @@ +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), STARTDATE DATE, SALARY BIGINT, + DEPARTMENT_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPARTMENT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID)); + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'CA13'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'CA19'); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (1, 'Joan', 59000, {d '2003-04-16'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (2, 'Sarah', 52000, {d '2002-04-26'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (3, 'John', 55000, {d '2001-01-01'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (4, 'Roberts', 53000, {d '2001-05-23'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (5, 'Peter', 50000, {d '2002-08-06'}, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (6, 'Frank', 51000, {d '2003-02-17'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (7, 'Scott', 60000, {d '2004-11-14'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (8, 'Sue', 62000, {d '2005-08-18'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (9, 'Stephanie', 54000, {d '2006-06-07'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (10, 'Jennifer', 55000, {d '1999-08-11'}, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID) VALUES (11, 'Marcus', 35000, {d '1995-07-22'}, NULL); \ No newline at end of file diff --git a/examples/Chapter6/11-applicationManagedJTA/etc/web/WEB-INF/web.xml b/examples/Chapter6/11-applicationManagedJTA/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter6/11-applicationManagedJTA/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServiceServlet + examples.servlet.EmployeeServiceServlet + + + + EmployeeServiceServlet + /EmployeeServiceServlet + + \ No newline at end of file diff --git a/examples/Chapter6/11-applicationManagedJTA/src/model/examples/model/Department.java b/examples/Chapter6/11-applicationManagedJTA/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter6/11-applicationManagedJTA/src/model/examples/model/Department.java @@ -0,0 +1,46 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="department") + private Collection employees; + + public Department() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter6/11-applicationManagedJTA/src/model/examples/model/Employee.java b/examples/Chapter6/11-applicationManagedJTA/src/model/examples/model/Employee.java new file mode 100644 index 0000000..b4ce131 --- /dev/null +++ b/examples/Chapter6/11-applicationManagedJTA/src/model/examples/model/Employee.java @@ -0,0 +1,59 @@ +package examples.model; + +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + @Temporal(TemporalType.DATE) + private Date startDate; + + @ManyToOne + private Department department; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + + public long getSalary() { + return salary; + } + + public Date getStartDate() { + return startDate; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department dept) { + this.department = dept; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary() + + ", dept: " + ((getDepartment() == null) ? null : getDepartment().getName()); + } +} diff --git a/examples/Chapter6/11-applicationManagedJTA/src/model/examples/stateless/DepartmentManager.java b/examples/Chapter6/11-applicationManagedJTA/src/model/examples/stateless/DepartmentManager.java new file mode 100644 index 0000000..6ff6396 --- /dev/null +++ b/examples/Chapter6/11-applicationManagedJTA/src/model/examples/stateless/DepartmentManager.java @@ -0,0 +1,12 @@ +package examples.stateless; + +import examples.model.Department; + + +public interface DepartmentManager { + public void init(int deptId); + public Department getDepartment(); + public void setName(String name); + public void addEmployee(int empId); + public void finished(); +} diff --git a/examples/Chapter6/11-applicationManagedJTA/src/model/examples/stateless/DepartmentManagerBean.java b/examples/Chapter6/11-applicationManagedJTA/src/model/examples/stateless/DepartmentManagerBean.java new file mode 100644 index 0000000..af6fa7e --- /dev/null +++ b/examples/Chapter6/11-applicationManagedJTA/src/model/examples/stateless/DepartmentManagerBean.java @@ -0,0 +1,49 @@ +package examples.stateless; + +import javax.ejb.Remove; +import javax.ejb.Stateful; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.PersistenceUnit; + +import examples.model.Department; +import examples.model.Employee; + +@Stateful +public class DepartmentManagerBean implements DepartmentManager { + @PersistenceUnit(unitName="EmployeeService") + private EntityManagerFactory emf; + private EntityManager em; + private Department dept; + + public void init(int deptId) { + em = emf.createEntityManager(); + dept = em.find(Department.class, deptId); + } + + public Department getDepartment() { + return dept; + } + + public void setName(String name) { + em.joinTransaction(); + dept.setName(name); + } + + public String getName() { + return dept.getName(); + } + + public void addEmployee(int empId) { + em.joinTransaction(); + Employee emp = em.find(Employee.class, empId); + dept.getEmployees().add(emp); + emp.setDepartment(dept); + } + + @Remove + public void finished() { + em.close(); + } +} + diff --git a/examples/Chapter6/11-applicationManagedJTA/src/model/examples/stateless/EmployeeService.java b/examples/Chapter6/11-applicationManagedJTA/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..cc0558b --- /dev/null +++ b/examples/Chapter6/11-applicationManagedJTA/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Department; +import examples.model.Employee; + +public interface EmployeeService { + public Collection findAllEmployees(); + public Collection findAllDepartments(); +} diff --git a/examples/Chapter6/11-applicationManagedJTA/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter6/11-applicationManagedJTA/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..748e5a5 --- /dev/null +++ b/examples/Chapter6/11-applicationManagedJTA/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,26 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + EntityManager em; + + public Collection findAllEmployees() { + return (Collection) em.createQuery( + "SELECT e FROM Employee e").getResultList(); + } + + public Collection findAllDepartments() { + return (Collection) em.createQuery( + "SELECT d FROM Department d").getResultList(); + } +} diff --git a/examples/Chapter6/11-applicationManagedJTA/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter6/11-applicationManagedJTA/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..d653eeb --- /dev/null +++ b/examples/Chapter6/11-applicationManagedJTA/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,140 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.naming.InitialContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateless.DepartmentManager; +import examples.stateless.EmployeeService; + +@EJB(name="ejb/DepartmentManager", + beanInterface=DepartmentManager.class, + beanName="DepartmentManagerBean") +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 6: Application Managed Persistence Context with JTA Example"; + + private final String DESCRIPTION = + "This example shows the basic use of an application managed " + + "persistence context with JTA."; + + + @EJB + private EmployeeService empService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + DepartmentManager deptManager = (DepartmentManager) request.getSession().getAttribute("DepartmentManager"); + if (deptManager == null) { + try { + deptManager = (DepartmentManager) + new InitialContext().lookup("java:comp/env/ejb/DepartmentManager"); + request.getSession().setAttribute("DepartmentManager", deptManager); + } catch (Exception e) { + throw new ServletException(e); + } + } + + // process request + String action = request.getParameter("action"); + if (action == null) { + printInitAction(out); + } else if (action.equals("ManageDept")) { + deptManager.init(parseInt(request.getParameter("deptId"))); + printManagementActions(out, deptManager); + } else if (action.equals("AddEmployee")) { + deptManager.addEmployee(parseInt(request.getParameter("empId"))); + printManagementActions(out, deptManager); + } else if (action.equals("SetName")) { + deptManager.setName(request.getParameter("name")); + printManagementActions(out, deptManager); + } else if (action.equals("Finished")) { + deptManager.finished(); + request.getSession().removeAttribute("DepartmentManager"); + printInitAction(out); + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printCollection(Collection c, PrintWriter out) { + for (Object o : c) { + out.print(o + "
"); + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + } + + private void printInitAction(PrintWriter out) { + out.println("
"); + out.println("

Manage Department

"); + out.println(""); + out.println("" + + ""); + out.println("
Department Id:(int)
"); + out.println("
"); + out.println("
"); + out.println("Departments:
"); + printCollection(empService.findAllDepartments(), out); + } + + private void printManagementActions(PrintWriter out, DepartmentManager deptManager) { + out.print("Managing " + deptManager.getDepartment() + "
"); + + out.println("
"); + out.println("

Add Employee to Department

"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
"); + out.println("
"); + out.println("

Add Set Department Name

"); + out.println(""); + out.println("" + + ""); + out.println("
Name:(String)
"); + out.println("
"); + out.println(""); + out.println("
"); + out.println("
"); + + out.println("Employees:
"); + printCollection(empService.findAllEmployees(), out); + } + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter6/11-applicationManagedJTA/undeploy.bat b/examples/Chapter6/11-applicationManagedJTA/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter6/11-applicationManagedJTA/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter6/12-sharingApplicationManagedJTA/build.xml b/examples/Chapter6/12-sharingApplicationManagedJTA/build.xml new file mode 100644 index 0000000..e69f8b8 --- /dev/null +++ b/examples/Chapter6/12-sharingApplicationManagedJTA/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/12-sharingApplicationManagedJTA/deploy.bat b/examples/Chapter6/12-sharingApplicationManagedJTA/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter6/12-sharingApplicationManagedJTA/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter6/12-sharingApplicationManagedJTA/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/12-sharingApplicationManagedJTA/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..8e3c562 --- /dev/null +++ b/examples/Chapter6/12-sharingApplicationManagedJTA/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/sharingApplicationManagedJTA + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/12-sharingApplicationManagedJTA/etc/sql/db.sql b/examples/Chapter6/12-sharingApplicationManagedJTA/etc/sql/db.sql new file mode 100644 index 0000000..b2b562d --- /dev/null +++ b/examples/Chapter6/12-sharingApplicationManagedJTA/etc/sql/db.sql @@ -0,0 +1,7 @@ +DROP TABLE EMPLOYEE; + +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), STARTDATE DATE, SALARY BIGINT, PRIMARY KEY (ID)); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY) VALUES (1, 'Joan', 59000); +INSERT INTO EMPLOYEE (ID, NAME, SALARY) VALUES (2, 'Sarah', 52000); +INSERT INTO EMPLOYEE (ID, NAME, SALARY) VALUES (3, 'John', 55000); \ No newline at end of file diff --git a/examples/Chapter6/12-sharingApplicationManagedJTA/etc/web/WEB-INF/web.xml b/examples/Chapter6/12-sharingApplicationManagedJTA/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5d96981 --- /dev/null +++ b/examples/Chapter6/12-sharingApplicationManagedJTA/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter6/12-sharingApplicationManagedJTA/src/model/examples/model/Employee.java b/examples/Chapter6/12-sharingApplicationManagedJTA/src/model/examples/model/Employee.java new file mode 100644 index 0000000..40615dd --- /dev/null +++ b/examples/Chapter6/12-sharingApplicationManagedJTA/src/model/examples/model/Employee.java @@ -0,0 +1,45 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + + public Employee() {} + public Employee(int id) { + this.id = id; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + " salary: " + getSalary(); + } +} diff --git a/examples/Chapter6/12-sharingApplicationManagedJTA/src/model/examples/model/EmployeeService.java b/examples/Chapter6/12-sharingApplicationManagedJTA/src/model/examples/model/EmployeeService.java new file mode 100644 index 0000000..9274f42 --- /dev/null +++ b/examples/Chapter6/12-sharingApplicationManagedJTA/src/model/examples/model/EmployeeService.java @@ -0,0 +1,47 @@ +package examples.model; + +import java.util.Collection; + +import javax.persistence.EntityManager; +import javax.persistence.Query; + + +public class EmployeeService { + protected EntityManager em; + + public EmployeeService(EntityManager em) { + this.em = em; + } + + public Employee createEmployee(int id, String name, long salary) { + Employee emp = new Employee(id); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + return emp; + } + + public void removeEmployee(int id) { + Employee emp = findEmployee(id); + if (emp != null) { + em.remove(emp); + } + } + + public Employee raiseEmployeeSalary(int id, long raise) { + Employee emp = em.find(Employee.class, id); + if (emp != null) { + emp.setSalary(emp.getSalary() + raise); + } + return emp; + } + + public Employee findEmployee(int id) { + return em.find(Employee.class, id); + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter6/12-sharingApplicationManagedJTA/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter6/12-sharingApplicationManagedJTA/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..d25d8ad --- /dev/null +++ b/examples/Chapter6/12-sharingApplicationManagedJTA/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,169 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.annotation.Resource; +import javax.transaction.UserTransaction; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.PersistenceUnit; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.model.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 6: Sharing Application Managed EntityManagers Example"; + + private final String DESCRIPTION = + "This example shows a brief example of how to share an applicaton " + + "managed entity manager between components."; + + + @PersistenceUnit(unitName="EmployeeService") + EntityManagerFactory emf; + @Resource UserTransaction tx; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + printHtmlFooter(out); + return; + } + + EntityManager em = null; + try { + tx.begin(); + em = emf.createEntityManager(); + EmployeeService service = new EmployeeService(em); + // process request + if (action.equals("Create")) { + Employee emp = service.createEmployee( + parseInt(request.getParameter("createId")), + request.getParameter("name"), + parseLong(request.getParameter("salary"))); + out.println("Created " + emp); + } else if (action.equals("Remove")) { + String id = request.getParameter("removeId"); + service.removeEmployee(parseInt(id)); + out.println("Removed Employee with id: " + id); + } else if (action.equals("Update")) { + String id = request.getParameter("raiseId"); + Employee emp = service.raiseEmployeeSalary( + parseInt(id), + parseLong(request.getParameter("raise"))); + out.println("Updated " + emp); + } else if (action.equals("Find")) { + Employee emp = service.findEmployee( + parseInt(request.getParameter("findId"))); + out.println("Found " + emp); + } else if (action.equals("FindAll")) { + Collection emps = service.findAllEmployees(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.print(emp + "
"); + } + } + } + } catch (Exception e) { + throw new ServletException(e); + } finally { + em.close(); + try { + tx.commit(); + } catch (Exception e) { + throw new ServletException(e); + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form to create + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println("" + + ""); + out.println("
Id:(int)
Name:(String)
Salary:(long)
"); + out.println("
"); + // form to remove + out.println("

Remove an Employee

"); + out.println(""); + out.println("" + + ""); + out.println("
Id:(int)
"); + out.println("
"); + // form to update + out.println("

Update an Employee

"); + out.println(""); + out.println(""); + out.println("" + + ""); + out.println("
Id:(int)
Raise:(long)
"); + out.println("
"); + // form to find + out.println("

Find an Employee

"); + out.println(""); + out.println("" + + ""); + out.println("
Id:(int)
"); + out.println("
"); + // form to find all + out.println("

Find all Employees

"); + out.println(""); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter6/12-sharingApplicationManagedJTA/undeploy.bat b/examples/Chapter6/12-sharingApplicationManagedJTA/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter6/12-sharingApplicationManagedJTA/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter6/13-resourceLocalTxSE/build.xml b/examples/Chapter6/13-resourceLocalTxSE/build.xml new file mode 100644 index 0000000..44d7d40 --- /dev/null +++ b/examples/Chapter6/13-resourceLocalTxSE/build.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/13-resourceLocalTxSE/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/13-resourceLocalTxSE/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..1011f97 --- /dev/null +++ b/examples/Chapter6/13-resourceLocalTxSE/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,14 @@ + + + examples.model.User + NONE + + + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/13-resourceLocalTxSE/etc/sql/db.sql b/examples/Chapter6/13-resourceLocalTxSE/etc/sql/db.sql new file mode 100644 index 0000000..e44a732 --- /dev/null +++ b/examples/Chapter6/13-resourceLocalTxSE/etc/sql/db.sql @@ -0,0 +1,15 @@ +DROP TABLE USER_DB; + +CREATE TABLE USER_DB (NAME VARCHAR(255) NOT NULL, PASSWORD VARCHAR(255), LASTCHANGE DATE, PRIMARY KEY (NAME)); + +INSERT INTO USER_DB (NAME, PASSWORD, LASTCHANGE) VALUES ('Joan', 'foo', {d '2003-04-16'}); +INSERT INTO USER_DB (NAME, PASSWORD, LASTCHANGE) VALUES ('Sarah', 'bar', {d '2002-04-26'}); +INSERT INTO USER_DB (NAME, PASSWORD, LASTCHANGE) VALUES ('John', 'password', {d '2001-01-01'}); +INSERT INTO USER_DB (NAME, PASSWORD, LASTCHANGE) VALUES ('Roberts', 'hello', {d '2001-05-23'}); +INSERT INTO USER_DB (NAME, PASSWORD, LASTCHANGE) VALUES ('Peter', '1234', {d '2002-08-06'}); +INSERT INTO USER_DB (NAME, PASSWORD, LASTCHANGE) VALUES ('Frank', 'myPassword', {d '2003-02-17'}); +INSERT INTO USER_DB (NAME, PASSWORD, LASTCHANGE) VALUES ('Scott', 'persistence', {d '2004-11-14'}); +INSERT INTO USER_DB (NAME, PASSWORD, LASTCHANGE) VALUES ('Sue', '5678', {d '2005-08-18'}); +INSERT INTO USER_DB (NAME, PASSWORD, LASTCHANGE) VALUES ('Stephanie', 'ejb', {d '2006-06-07'}); +INSERT INTO USER_DB (NAME, PASSWORD, LASTCHANGE) VALUES ('Jennifer', 'pwd', {d '1999-08-11'}); +INSERT INTO USER_DB (NAME, PASSWORD, LASTCHANGE) VALUES ('Marcus', 'foobar', {d '1995-07-22'}); \ No newline at end of file diff --git a/examples/Chapter6/13-resourceLocalTxSE/run.bat b/examples/Chapter6/13-resourceLocalTxSE/run.bat new file mode 100644 index 0000000..15bf23b --- /dev/null +++ b/examples/Chapter6/13-resourceLocalTxSE/run.bat @@ -0,0 +1,2 @@ +call ../../../config/ant +pause \ No newline at end of file diff --git a/examples/Chapter6/13-resourceLocalTxSE/src/client/examples/client/ExpirePasswords.java b/examples/Chapter6/13-resourceLocalTxSE/src/client/examples/client/ExpirePasswords.java new file mode 100644 index 0000000..dd52f33 --- /dev/null +++ b/examples/Chapter6/13-resourceLocalTxSE/src/client/examples/client/ExpirePasswords.java @@ -0,0 +1,44 @@ +package examples.client; + +import java.util.Calendar; +import java.util.Collection; +import java.util.Iterator; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import examples.model.User; + +public class ExpirePasswords { + + public static void main(String[] args) { + int maxAge = Integer.parseInt(args[0]); + String defaultPassword = args[1]; + + EntityManagerFactory emf = + Persistence.createEntityManagerFactory("admin"); + try { + EntityManager em = emf.createEntityManager(); + + Calendar cal = Calendar.getInstance(); + cal.add(Calendar.DAY_OF_YEAR, -maxAge); + + em.getTransaction().begin(); + Collection expired = + em.createQuery("SELECT u FROM User u WHERE u.lastChange > ?1") + .setParameter(1, cal) + .getResultList(); + for (Iterator i = expired.iterator(); i.hasNext();) { + User u = (User) i.next(); + System.out.println("Expiring password for " + u.getName()); + u.setPassword(defaultPassword); + } + em.getTransaction().commit(); + em.close(); + } finally { + emf.close(); + } + } + +} diff --git a/examples/Chapter6/13-resourceLocalTxSE/src/model/examples/model/User.java b/examples/Chapter6/13-resourceLocalTxSE/src/model/examples/model/User.java new file mode 100644 index 0000000..e56d669 --- /dev/null +++ b/examples/Chapter6/13-resourceLocalTxSE/src/model/examples/model/User.java @@ -0,0 +1,49 @@ +package examples.model; + +import java.text.DateFormat; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@Table(name="USER_DB") +public class User { + @Id + private String name; + private String password; + @Temporal(TemporalType.DATE) + private java.util.Calendar lastChange; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getPassword() { + return password; + } + + public void setPassword(String name) { + this.password = name; + } + + public java.util.Calendar getLastChange() { + return lastChange; + } + + public void setLastChange(java.util.Calendar lastChange) { + this.lastChange = lastChange; + } + + public String toString() { + return "User " + getName() + + " pwd: " + getPassword() + + " lastChange: " + DateFormat.getDateInstance().format(getLastChange()); + } +} diff --git a/examples/Chapter6/14-resourceLocalTxEE/build.xml b/examples/Chapter6/14-resourceLocalTxEE/build.xml new file mode 100644 index 0000000..e545190 --- /dev/null +++ b/examples/Chapter6/14-resourceLocalTxEE/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/14-resourceLocalTxEE/deploy.bat b/examples/Chapter6/14-resourceLocalTxEE/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter6/14-resourceLocalTxEE/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter6/14-resourceLocalTxEE/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/14-resourceLocalTxEE/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..ed886d7 --- /dev/null +++ b/examples/Chapter6/14-resourceLocalTxEE/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/resourceLocalTxEE + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/14-resourceLocalTxEE/etc/sql/db.sql b/examples/Chapter6/14-resourceLocalTxEE/etc/sql/db.sql new file mode 100644 index 0000000..e6b183e --- /dev/null +++ b/examples/Chapter6/14-resourceLocalTxEE/etc/sql/db.sql @@ -0,0 +1,4 @@ +DROP TABLE LOGRECORD; + +CREATE TABLE LOGRECORD (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + EMPNO INTEGER, ACTION VARCHAR(255), PRIMARY KEY (ID)); \ No newline at end of file diff --git a/examples/Chapter6/14-resourceLocalTxEE/etc/web/WEB-INF/web.xml b/examples/Chapter6/14-resourceLocalTxEE/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..882291d --- /dev/null +++ b/examples/Chapter6/14-resourceLocalTxEE/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + LoggingServlet + examples.servlet.LoggingServlet + + + + LoggingServlet + /LoggingServlet + + \ No newline at end of file diff --git a/examples/Chapter6/14-resourceLocalTxEE/src/model/examples/model/LogRecord.java b/examples/Chapter6/14-resourceLocalTxEE/src/model/examples/model/LogRecord.java new file mode 100644 index 0000000..ad1970f --- /dev/null +++ b/examples/Chapter6/14-resourceLocalTxEE/src/model/examples/model/LogRecord.java @@ -0,0 +1,49 @@ +package examples.model; + + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class LogRecord { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) + private int id; + private int empNo; + private String action; + + public LogRecord() {} + public LogRecord(int empNo, String action) { + setEmpNo(empNo); + setAction(action); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getEmpNo() { + return empNo; + } + + public void setEmpNo(int empNo) { + this.empNo = empNo; + } + + public String getAction() { + return action; + } + + public void setAction(String name) { + this.action = name; + } + + public String toString() { + return "LogRecord empNo: " + getEmpNo() + ", action: " + getAction(); + } +} diff --git a/examples/Chapter6/14-resourceLocalTxEE/src/model/examples/stateless/LogService.java b/examples/Chapter6/14-resourceLocalTxEE/src/model/examples/stateless/LogService.java new file mode 100644 index 0000000..a137cf0 --- /dev/null +++ b/examples/Chapter6/14-resourceLocalTxEE/src/model/examples/stateless/LogService.java @@ -0,0 +1,5 @@ +package examples.stateless; + +public interface LogService { + public void logAccess(int userId, String action); +} diff --git a/examples/Chapter6/14-resourceLocalTxEE/src/model/examples/stateless/LogServiceBean.java b/examples/Chapter6/14-resourceLocalTxEE/src/model/examples/stateless/LogServiceBean.java new file mode 100644 index 0000000..8365249 --- /dev/null +++ b/examples/Chapter6/14-resourceLocalTxEE/src/model/examples/stateless/LogServiceBean.java @@ -0,0 +1,28 @@ +package examples.stateless; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.PersistenceUnit; + +import examples.model.LogRecord; + +@Stateless +public class LogServiceBean implements LogService { + @PersistenceUnit(unitName="logging") + EntityManagerFactory emf; + + public void logAccess(int userId, String action) { + EntityManager em = emf.createEntityManager(); + try { + LogRecord lr = new LogRecord(userId, action); + em.getTransaction().begin(); + em.persist(lr); + em.getTransaction().commit(); + } finally { + em.close(); + } + } +} + + diff --git a/examples/Chapter6/14-resourceLocalTxEE/src/servlet/examples/servlet/LoggingServlet.java b/examples/Chapter6/14-resourceLocalTxEE/src/servlet/examples/servlet/LoggingServlet.java new file mode 100644 index 0000000..bb6d49d --- /dev/null +++ b/examples/Chapter6/14-resourceLocalTxEE/src/servlet/examples/servlet/LoggingServlet.java @@ -0,0 +1,80 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateless.LogService; + +public class LoggingServlet extends HttpServlet { + + private final String TITLE = + "Chapter 6: Resource-Local Transaction in EE Example"; + + private final String DESCRIPTION = + "This example shows the basic use of an application managed " + + "EntityManager with ResourceLocal transactions in EE."; + + + @EJB + private LogService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action != null) { + int id = parseInt(request.getParameter("id")); + String access = request.getParameter("access"); + service.logAccess(id, access); + out.print("Logged id: " + id + " access: " + access + "
"); + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + + out.println(""); + out.println("

Log Access

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Id:(int)
Action:(String)
"); + out.println("
"); + } + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter6/14-resourceLocalTxEE/undeploy.bat b/examples/Chapter6/14-resourceLocalTxEE/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter6/14-resourceLocalTxEE/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter6/15-persistingWithRelationships/build.xml b/examples/Chapter6/15-persistingWithRelationships/build.xml new file mode 100644 index 0000000..cb5482b --- /dev/null +++ b/examples/Chapter6/15-persistingWithRelationships/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/15-persistingWithRelationships/deploy.bat b/examples/Chapter6/15-persistingWithRelationships/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter6/15-persistingWithRelationships/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter6/15-persistingWithRelationships/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/15-persistingWithRelationships/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..acede69 --- /dev/null +++ b/examples/Chapter6/15-persistingWithRelationships/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/persistingWithRelationships + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/15-persistingWithRelationships/etc/sql/db.sql b/examples/Chapter6/15-persistingWithRelationships/etc/sql/db.sql new file mode 100644 index 0000000..f9b9756 --- /dev/null +++ b/examples/Chapter6/15-persistingWithRelationships/etc/sql/db.sql @@ -0,0 +1,11 @@ +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), + DEPARTMENT_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPARTMENT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID)); + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'CA13'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'CA19'); \ No newline at end of file diff --git a/examples/Chapter6/15-persistingWithRelationships/etc/web/WEB-INF/web.xml b/examples/Chapter6/15-persistingWithRelationships/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter6/15-persistingWithRelationships/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServiceServlet + examples.servlet.EmployeeServiceServlet + + + + EmployeeServiceServlet + /EmployeeServiceServlet + + \ No newline at end of file diff --git a/examples/Chapter6/15-persistingWithRelationships/src/model/examples/model/Department.java b/examples/Chapter6/15-persistingWithRelationships/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter6/15-persistingWithRelationships/src/model/examples/model/Department.java @@ -0,0 +1,46 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="department") + private Collection employees; + + public Department() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter6/15-persistingWithRelationships/src/model/examples/model/Employee.java b/examples/Chapter6/15-persistingWithRelationships/src/model/examples/model/Employee.java new file mode 100644 index 0000000..3b074a5 --- /dev/null +++ b/examples/Chapter6/15-persistingWithRelationships/src/model/examples/model/Employee.java @@ -0,0 +1,46 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@Entity +public class Employee { + @Id + private int id; + private String name; + + @ManyToOne + private Department department; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department dept) { + this.department = dept; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", dept: " + ((getDepartment() == null) ? null : getDepartment().getName()); + } +} diff --git a/examples/Chapter6/15-persistingWithRelationships/src/model/examples/stateless/EmployeeService.java b/examples/Chapter6/15-persistingWithRelationships/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..208d7df --- /dev/null +++ b/examples/Chapter6/15-persistingWithRelationships/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,12 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Department; +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(int empId, String empName, int deptId); + public Collection findAllEmployees(); + public Collection findAllDepartments(); +} diff --git a/examples/Chapter6/15-persistingWithRelationships/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter6/15-persistingWithRelationships/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..afbf2ef --- /dev/null +++ b/examples/Chapter6/15-persistingWithRelationships/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,37 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + EntityManager em; + + public Employee createEmployee(int empId, String empName, int deptId) { + Department dept = em.find(Department.class, deptId); + Employee emp = new Employee(); + emp.setId(empId); + emp.setName(empName); + emp.setDepartment(dept); + dept.getEmployees().add(emp); + em.persist(emp); + return emp; + } + + public Collection findAllEmployees() { + return (Collection) em.createQuery( + "SELECT e FROM Employee e").getResultList(); + } + + public Collection findAllDepartments() { + return (Collection) em.createQuery( + "SELECT d FROM Department d").getResultList(); + } +} diff --git a/examples/Chapter6/15-persistingWithRelationships/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter6/15-persistingWithRelationships/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..f8f42ba --- /dev/null +++ b/examples/Chapter6/15-persistingWithRelationships/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,94 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateless.EmployeeService; + +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 6: Persisting Entities with Relationships Example"; + + private final String DESCRIPTION = + "This example shows how to persist an entity with relationships."; + + + @EJB + private EmployeeService empService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action != null) { + if (action.equals("Create")) { + empService.createEmployee( + parseInt(request.getParameter("empId")), + request.getParameter("name"), + parseInt(request.getParameter("deptId"))); + } + } + + out.println("Employees:
"); + printCollection(empService.findAllEmployees(), out); + + out.println("
Departments:
"); + printCollection(empService.findAllDepartments(), out); + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printCollection(Collection c, PrintWriter out) { + for (Object o : c) { + out.print(o + "
"); + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + + out.println(""); + out.println("

Create Employee and add to Department

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
Employee Name:(String)
Department Id:(int)
"); + out.println("
"); + } + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter6/15-persistingWithRelationships/undeploy.bat b/examples/Chapter6/15-persistingWithRelationships/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter6/15-persistingWithRelationships/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/build.xml b/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/build.xml new file mode 100644 index 0000000..05c8b32 --- /dev/null +++ b/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/deploy.bat b/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..291dd63 --- /dev/null +++ b/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/persistingWithRelationshipsUsingGetReference + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/etc/sql/db.sql b/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/etc/sql/db.sql new file mode 100644 index 0000000..f9b9756 --- /dev/null +++ b/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/etc/sql/db.sql @@ -0,0 +1,11 @@ +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), + DEPARTMENT_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPARTMENT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID)); + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'CA13'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'CA19'); \ No newline at end of file diff --git a/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/etc/web/WEB-INF/web.xml b/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServiceServlet + examples.servlet.EmployeeServiceServlet + + + + EmployeeServiceServlet + /EmployeeServiceServlet + + \ No newline at end of file diff --git a/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/src/model/examples/model/Department.java b/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/src/model/examples/model/Department.java @@ -0,0 +1,46 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="department") + private Collection employees; + + public Department() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/src/model/examples/model/Employee.java b/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/src/model/examples/model/Employee.java new file mode 100644 index 0000000..3b074a5 --- /dev/null +++ b/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/src/model/examples/model/Employee.java @@ -0,0 +1,46 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@Entity +public class Employee { + @Id + private int id; + private String name; + + @ManyToOne + private Department department; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department dept) { + this.department = dept; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", dept: " + ((getDepartment() == null) ? null : getDepartment().getName()); + } +} diff --git a/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/src/model/examples/stateless/EmployeeService.java b/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..208d7df --- /dev/null +++ b/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,12 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Department; +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployee(int empId, String empName, int deptId); + public Collection findAllEmployees(); + public Collection findAllDepartments(); +} diff --git a/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..3b84d06 --- /dev/null +++ b/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,37 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + EntityManager em; + + public Employee createEmployee(int empId, String empName, int deptId) { + Department dept = em.getReference(Department.class, deptId); + Employee emp = new Employee(); + emp.setId(empId); + emp.setName(empName); + emp.setDepartment(dept); + dept.getEmployees().add(emp); + em.persist(emp); + return emp; + } + + public Collection findAllEmployees() { + return (Collection) em.createQuery( + "SELECT e FROM Employee e").getResultList(); + } + + public Collection findAllDepartments() { + return (Collection) em.createQuery( + "SELECT d FROM Department d").getResultList(); + } +} diff --git a/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..31207e9 --- /dev/null +++ b/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,94 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateless.EmployeeService; + +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 6: Persisting Entities with Relationships (using getReference) Example"; + + private final String DESCRIPTION = + "This example shows how to persist an entity with relationships."; + + + @EJB + private EmployeeService empService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action != null) { + if (action.equals("Create")) { + empService.createEmployee( + parseInt(request.getParameter("empId")), + request.getParameter("name"), + parseInt(request.getParameter("deptId"))); + } + } + + out.println("Employees:
"); + printCollection(empService.findAllEmployees(), out); + + out.println("
Departments:
"); + printCollection(empService.findAllDepartments(), out); + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printCollection(Collection c, PrintWriter out) { + for (Object o : c) { + out.print(o + "
"); + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + + out.println(""); + out.println("

Create Employee and add to Department

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
Employee Name:(String)
Department Id:(int)
"); + out.println("
"); + } + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/undeploy.bat b/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter6/16-persistingWithRelationshipsUsingGetReference/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter6/17-removingWithRelationships/build.xml b/examples/Chapter6/17-removingWithRelationships/build.xml new file mode 100644 index 0000000..14ba084 --- /dev/null +++ b/examples/Chapter6/17-removingWithRelationships/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/17-removingWithRelationships/deploy.bat b/examples/Chapter6/17-removingWithRelationships/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter6/17-removingWithRelationships/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter6/17-removingWithRelationships/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/17-removingWithRelationships/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..e65ddd3 --- /dev/null +++ b/examples/Chapter6/17-removingWithRelationships/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/removingWithRelationships + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/17-removingWithRelationships/etc/sql/db.sql b/examples/Chapter6/17-removingWithRelationships/etc/sql/db.sql new file mode 100644 index 0000000..ca6c7a8 --- /dev/null +++ b/examples/Chapter6/17-removingWithRelationships/etc/sql/db.sql @@ -0,0 +1,18 @@ +DROP TABLE EMPLOYEE; +DROP TABLE PARKING_SPACE; + +CREATE TABLE PARKING_SPACE (ID INTEGER NOT NULL, LOT INTEGER, LOCATION VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), PSPACE_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT PSPACE_FK FOREIGN KEY (PSPACE_ID) REFERENCES PARKING_SPACE(ID)); + +INSERT INTO PARKING_SPACE (ID, LOT, LOCATION) VALUES (1, 1, 'East Lot'); +INSERT INTO PARKING_SPACE (ID, LOT, LOCATION) VALUES (2, 2, 'West Lot'); +INSERT INTO PARKING_SPACE (ID, LOT, LOCATION) VALUES (3, 3, 'North Lot'); +INSERT INTO PARKING_SPACE (ID, LOT, LOCATION) VALUES (4, 4, 'South Lot'); +INSERT INTO PARKING_SPACE (ID, LOT, LOCATION) VALUES (5, 5, 'West Lot'); + +INSERT INTO EMPLOYEE (ID, NAME, PSPACE_ID) VALUES (1, 'Joan', 1); +INSERT INTO EMPLOYEE (ID, NAME, PSPACE_ID) VALUES (2, 'Sarah', 2); +INSERT INTO EMPLOYEE (ID, NAME, PSPACE_ID) VALUES (3, 'John', 3); +INSERT INTO EMPLOYEE (ID, NAME, PSPACE_ID) VALUES (4, 'Roberts', 4); +INSERT INTO EMPLOYEE (ID, NAME, PSPACE_ID) VALUES (5, 'Peter', 5); diff --git a/examples/Chapter6/17-removingWithRelationships/etc/web/WEB-INF/web.xml b/examples/Chapter6/17-removingWithRelationships/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter6/17-removingWithRelationships/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServiceServlet + examples.servlet.EmployeeServiceServlet + + + + EmployeeServiceServlet + /EmployeeServiceServlet + + \ No newline at end of file diff --git a/examples/Chapter6/17-removingWithRelationships/src/model/examples/model/Employee.java b/examples/Chapter6/17-removingWithRelationships/src/model/examples/model/Employee.java new file mode 100644 index 0000000..70dda67 --- /dev/null +++ b/examples/Chapter6/17-removingWithRelationships/src/model/examples/model/Employee.java @@ -0,0 +1,46 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToOne; + +@Entity +public class Employee { + @Id + private int id; + private String name; + + @OneToOne + @JoinColumn(name="PSPACE_ID") + private ParkingSpace parkingSpace; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public ParkingSpace getParkingSpace() { + return parkingSpace; + } + + public void setParkingSpace(ParkingSpace parkingSpace) { + this.parkingSpace = parkingSpace; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " with " + getParkingSpace(); + } +} diff --git a/examples/Chapter6/17-removingWithRelationships/src/model/examples/model/ParkingSpace.java b/examples/Chapter6/17-removingWithRelationships/src/model/examples/model/ParkingSpace.java new file mode 100644 index 0000000..77813c6 --- /dev/null +++ b/examples/Chapter6/17-removingWithRelationships/src/model/examples/model/ParkingSpace.java @@ -0,0 +1,54 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +@Entity +@Table(name="PARKING_SPACE") +public class ParkingSpace { + @Id + private int id; + private int lot; + private String location; + @OneToOne(mappedBy="parkingSpace") + private Employee employee; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getLot() { + return lot; + } + + public void setLot(int lot) { + this.lot = lot; + } + + public String getLocation() { + return location; + } + + public void setLocation(String deptName) { + this.location = deptName; + } + + public Employee getEmployee() { + return employee; + } + + public void setEmployee(Employee employee) { + this.employee = employee; + } + + public String toString() { + return "ParkingSpace id: " + getId() + " lot: " + getLot() + + ", location: " + getLocation(); + } +} diff --git a/examples/Chapter6/17-removingWithRelationships/src/model/examples/stateless/EmployeeService.java b/examples/Chapter6/17-removingWithRelationships/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..5e0c3ea --- /dev/null +++ b/examples/Chapter6/17-removingWithRelationships/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public void removeParkingSpace(int empId); + public void removeParkingSpaceWithFailure(int empId); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter6/17-removingWithRelationships/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter6/17-removingWithRelationships/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..79b9963 --- /dev/null +++ b/examples/Chapter6/17-removingWithRelationships/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,36 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Employee; +import examples.model.ParkingSpace; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + EntityManager em; + + public void removeParkingSpace(int empId) { + Employee emp = em.find(Employee.class, empId); + ParkingSpace ps = emp.getParkingSpace(); + ps.setEmployee(null); + emp.setParkingSpace(null); + em.remove(ps); + } + + public void removeParkingSpaceWithFailure(int empId) { + // forgetting to null out the relationship will cause a + // db constraint failure + Employee emp = em.find(Employee.class, empId); + em.remove(emp.getParkingSpace()); + } + + public Collection findAllEmployees() { + return (Collection) em.createQuery( + "SELECT e FROM Employee e").getResultList(); + } +} diff --git a/examples/Chapter6/17-removingWithRelationships/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter6/17-removingWithRelationships/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..2fbaada --- /dev/null +++ b/examples/Chapter6/17-removingWithRelationships/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,102 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateless.EmployeeService; + +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 6: Removing Entities with Relationships Example"; + + private final String DESCRIPTION = + "This example shows how to remove an entity with relationships."; + + + @EJB + private EmployeeService empService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action != null) { + if (action.equals("Remove")) { + empService.removeParkingSpace( + parseInt(request.getParameter("empId"))); + } else if (action.equals("RemoveWithFailure")) { + try { + empService.removeParkingSpaceWithFailure( + parseInt(request.getParameter("empId2"))); + } catch (Exception e) { + out.print("Remove caused exception: " + e); + out.print("
See log for details

"); + } + } + } + + out.println("Employees:
"); + printCollection(empService.findAllEmployees(), out); + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printCollection(Collection c, PrintWriter out) { + for (Object o : c) { + out.print(o + "
"); + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + + out.println(""); + out.println("

Remove Employee Parking Space

"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
"); + out.println("
"); + out.println(""); + out.println("

Remove Employee Parking Space (causes DB constraint failure)

"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
"); + out.println("
"); + } + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter6/17-removingWithRelationships/undeploy.bat b/examples/Chapter6/17-removingWithRelationships/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter6/17-removingWithRelationships/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter6/18-persistingWithRelationshipsCascade/build.xml b/examples/Chapter6/18-persistingWithRelationshipsCascade/build.xml new file mode 100644 index 0000000..a7ba4ef --- /dev/null +++ b/examples/Chapter6/18-persistingWithRelationshipsCascade/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/18-persistingWithRelationshipsCascade/deploy.bat b/examples/Chapter6/18-persistingWithRelationshipsCascade/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter6/18-persistingWithRelationshipsCascade/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter6/18-persistingWithRelationshipsCascade/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/18-persistingWithRelationshipsCascade/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..3260e85 --- /dev/null +++ b/examples/Chapter6/18-persistingWithRelationshipsCascade/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/persistingWithRelationshipsCascade + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/18-persistingWithRelationshipsCascade/etc/sql/db.sql b/examples/Chapter6/18-persistingWithRelationshipsCascade/etc/sql/db.sql new file mode 100644 index 0000000..346085a --- /dev/null +++ b/examples/Chapter6/18-persistingWithRelationshipsCascade/etc/sql/db.sql @@ -0,0 +1,6 @@ +DROP TABLE EMPLOYEE; +DROP TABLE ADDRESS; + +CREATE TABLE ADDRESS (ID INTEGER NOT NULL, CITY VARCHAR(255), STATE VARCHAR(255), STREET VARCHAR(255), ZIP VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), ADDRESS_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT ADDRESS_FK FOREIGN KEY (ADDRESS_ID) REFERENCES ADDRESS(ID)); diff --git a/examples/Chapter6/18-persistingWithRelationshipsCascade/etc/web/WEB-INF/web.xml b/examples/Chapter6/18-persistingWithRelationshipsCascade/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter6/18-persistingWithRelationshipsCascade/etc/web/WEB-INF/web.xml @@ -0,0 +1,16 @@ + + + + EmployeeServiceServlet + examples.servlet.EmployeeServiceServlet + + + + EmployeeServiceServlet + /EmployeeServiceServlet + + + \ No newline at end of file diff --git a/examples/Chapter6/18-persistingWithRelationshipsCascade/src/model/examples/model/Address.java b/examples/Chapter6/18-persistingWithRelationshipsCascade/src/model/examples/model/Address.java new file mode 100644 index 0000000..e18406b --- /dev/null +++ b/examples/Chapter6/18-persistingWithRelationshipsCascade/src/model/examples/model/Address.java @@ -0,0 +1,62 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Address { + @Id + private int id; + private String street; + private String city; + private String state; + private String zip; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getStreet() { + return street; + } + + public void setStreet(String address) { + this.street = address; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getZip() { + return zip; + } + + public void setZip(String zip) { + this.zip = zip; + } + public String toString() { + return "Address id: " + getId() + + ", street: " + getStreet() + + ", city: " + getCity() + + ", state: " + getState() + + ", zip: " + getZip(); + } + +} diff --git a/examples/Chapter6/18-persistingWithRelationshipsCascade/src/model/examples/model/Employee.java b/examples/Chapter6/18-persistingWithRelationshipsCascade/src/model/examples/model/Employee.java new file mode 100644 index 0000000..8c1c112 --- /dev/null +++ b/examples/Chapter6/18-persistingWithRelationshipsCascade/src/model/examples/model/Employee.java @@ -0,0 +1,45 @@ +package examples.model; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@Entity +public class Employee { + @Id + private int id; + private String name; + + @ManyToOne(cascade=CascadeType.PERSIST) + Address address; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " with " + getAddress(); + } +} diff --git a/examples/Chapter6/18-persistingWithRelationshipsCascade/src/model/examples/stateless/EmployeeService.java b/examples/Chapter6/18-persistingWithRelationshipsCascade/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..52d57fc --- /dev/null +++ b/examples/Chapter6/18-persistingWithRelationshipsCascade/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee createEmployeeAndAddress(int id, String name, + int addrId, String street, String city, String state); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter6/18-persistingWithRelationshipsCascade/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter6/18-persistingWithRelationshipsCascade/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..822d3c7 --- /dev/null +++ b/examples/Chapter6/18-persistingWithRelationshipsCascade/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,38 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Address; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployeeAndAddress(int id, String name, + int addrId, String street, String city, String state) { + Employee emp = new Employee(); + emp.setId(id); + emp.setName(name); + Address addr = new Address(); + addr.setId(addrId); + addr.setStreet(street); + addr.setCity(city); + addr.setState(state); + emp.setAddress(addr); + em.persist(emp); + + return emp; + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter6/18-persistingWithRelationshipsCascade/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter6/18-persistingWithRelationshipsCascade/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..24383d1 --- /dev/null +++ b/examples/Chapter6/18-persistingWithRelationshipsCascade/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,95 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.stateless.EmployeeService; + +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 6: Persisting Entities with Relationships using Cascade Example"; + + private final String DESCRIPTION = + "This example demonstates how to persist a simple relationship.
" + + "It allows you to create/find employees and address."; + + + // inject a reference to the EmployeeService slsb + @EJB EmployeeService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("Create")) { + service.createEmployeeAndAddress( + parseInt(request.getParameter("empId")), + request.getParameter("name"), + parseInt(request.getParameter("addrId")), + request.getParameter("street"), + request.getParameter("city"), + request.getParameter("state")); + } + + out.println("Employees and Addresses:
"); + for (Employee emp : service.findAllEmployees()) { + out.print(emp + "
"); + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println(""); + // form to create and Employee and Address + out.println("

Create an Employee and Address

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("" + + ""); + out.println("
Employee Id:(int)
Employee Name:(String)
Address Id:(int)
Address Street:(String)
Address City:(String)
Address State:(String)
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter6/18-persistingWithRelationshipsCascade/undeploy.bat b/examples/Chapter6/18-persistingWithRelationshipsCascade/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter6/18-persistingWithRelationshipsCascade/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter6/19-removingWithRelationshipsCascade/build.xml b/examples/Chapter6/19-removingWithRelationshipsCascade/build.xml new file mode 100644 index 0000000..d11c54a --- /dev/null +++ b/examples/Chapter6/19-removingWithRelationshipsCascade/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/19-removingWithRelationshipsCascade/deploy.bat b/examples/Chapter6/19-removingWithRelationshipsCascade/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter6/19-removingWithRelationshipsCascade/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter6/19-removingWithRelationshipsCascade/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/19-removingWithRelationshipsCascade/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..47b55ca --- /dev/null +++ b/examples/Chapter6/19-removingWithRelationshipsCascade/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/removingWithRelationshipsCascade + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/19-removingWithRelationshipsCascade/etc/sql/db.sql b/examples/Chapter6/19-removingWithRelationshipsCascade/etc/sql/db.sql new file mode 100644 index 0000000..48d4c71 --- /dev/null +++ b/examples/Chapter6/19-removingWithRelationshipsCascade/etc/sql/db.sql @@ -0,0 +1,31 @@ +DROP TABLE EMPLOYEE; +DROP TABLE PARKING_SPACE; +DROP TABLE PHONE; + +CREATE TABLE PARKING_SPACE (ID INTEGER NOT NULL, LOT INTEGER, LOCATION VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), PSPACE_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT PSPACE_FK FOREIGN KEY (PSPACE_ID) REFERENCES PARKING_SPACE(ID)); +CREATE TABLE PHONE (ID INTEGER NOT NULL, NUMBER VARCHAR(255), TYPE VARCHAR(255), EMPLOYEE_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT EMPLOYEE_FK FOREIGN KEY (EMPLOYEE_ID) REFERENCES EMPLOYEE(ID)); + +INSERT INTO PARKING_SPACE (ID, LOT, LOCATION) VALUES (1, 1, 'East Lot'); +INSERT INTO PARKING_SPACE (ID, LOT, LOCATION) VALUES (2, 2, 'West Lot'); +INSERT INTO PARKING_SPACE (ID, LOT, LOCATION) VALUES (3, 3, 'North Lot'); +INSERT INTO PARKING_SPACE (ID, LOT, LOCATION) VALUES (4, 4, 'South Lot'); +INSERT INTO PARKING_SPACE (ID, LOT, LOCATION) VALUES (5, 5, 'West Lot'); + +INSERT INTO EMPLOYEE (ID, NAME, PSPACE_ID) VALUES (1, 'Joan', 1); +INSERT INTO EMPLOYEE (ID, NAME, PSPACE_ID) VALUES (2, 'Sarah', 2); +INSERT INTO EMPLOYEE (ID, NAME, PSPACE_ID) VALUES (3, 'John', 3); +INSERT INTO EMPLOYEE (ID, NAME, PSPACE_ID) VALUES (4, 'Roberts', 4); +INSERT INTO EMPLOYEE (ID, NAME, PSPACE_ID) VALUES (5, 'Peter', 5); + +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (1, '212-555-1234', 'office', 1); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (2, '212-555-1234', 'home', 1); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (3, '315-555-1234', 'office', 2); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (4, '516-555-1234', 'office', 3); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (5, '516-555-1234', 'cell', 3); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (6, '650-555-1234', 'office', 4); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (7, '650-555-1234', 'home', 4); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (8, '650-555-1234', 'office', 5); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (9, '650-555-1234', 'cell', 5); diff --git a/examples/Chapter6/19-removingWithRelationshipsCascade/etc/web/WEB-INF/web.xml b/examples/Chapter6/19-removingWithRelationshipsCascade/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter6/19-removingWithRelationshipsCascade/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServiceServlet + examples.servlet.EmployeeServiceServlet + + + + EmployeeServiceServlet + /EmployeeServiceServlet + + \ No newline at end of file diff --git a/examples/Chapter6/19-removingWithRelationshipsCascade/src/model/examples/model/Employee.java b/examples/Chapter6/19-removingWithRelationshipsCascade/src/model/examples/model/Employee.java new file mode 100644 index 0000000..fcf42e1 --- /dev/null +++ b/examples/Chapter6/19-removingWithRelationshipsCascade/src/model/examples/model/Employee.java @@ -0,0 +1,59 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToMany; +import javax.persistence.OneToOne; + +@Entity +public class Employee { + @Id + private int id; + private String name; + + @OneToOne(cascade={CascadeType.PERSIST, CascadeType.REMOVE}) + @JoinColumn(name="PSPACE_ID") + ParkingSpace parkingSpace; + + @OneToMany(cascade={CascadeType.PERSIST, CascadeType.REMOVE}, + mappedBy="employee") + Collection phones; + + public Employee() { + phones = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public ParkingSpace getParkingSpace() { + return parkingSpace; + } + + public void setParkingSpace(ParkingSpace parkingSpace) { + this.parkingSpace = parkingSpace; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " with " + getParkingSpace(); + } +} diff --git a/examples/Chapter6/19-removingWithRelationshipsCascade/src/model/examples/model/ParkingSpace.java b/examples/Chapter6/19-removingWithRelationshipsCascade/src/model/examples/model/ParkingSpace.java new file mode 100644 index 0000000..77813c6 --- /dev/null +++ b/examples/Chapter6/19-removingWithRelationshipsCascade/src/model/examples/model/ParkingSpace.java @@ -0,0 +1,54 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +@Entity +@Table(name="PARKING_SPACE") +public class ParkingSpace { + @Id + private int id; + private int lot; + private String location; + @OneToOne(mappedBy="parkingSpace") + private Employee employee; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getLot() { + return lot; + } + + public void setLot(int lot) { + this.lot = lot; + } + + public String getLocation() { + return location; + } + + public void setLocation(String deptName) { + this.location = deptName; + } + + public Employee getEmployee() { + return employee; + } + + public void setEmployee(Employee employee) { + this.employee = employee; + } + + public String toString() { + return "ParkingSpace id: " + getId() + " lot: " + getLot() + + ", location: " + getLocation(); + } +} diff --git a/examples/Chapter6/19-removingWithRelationshipsCascade/src/model/examples/model/Phone.java b/examples/Chapter6/19-removingWithRelationshipsCascade/src/model/examples/model/Phone.java new file mode 100644 index 0000000..afa5419 --- /dev/null +++ b/examples/Chapter6/19-removingWithRelationshipsCascade/src/model/examples/model/Phone.java @@ -0,0 +1,52 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToOne; + +@Entity +public class Phone { + @Id + private long id; + private String number; + private String type; + @OneToOne Employee employee; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getNumber() { + return number; + } + + public void setNumber(String phoneNo) { + this.number = phoneNo; + } + + public String getType() { + return type; + } + + public void setType(String phoneType) { + this.type = phoneType; + } + + public Employee getEmployee() { + return employee; + } + + public void setEmployee(Employee employee) { + this.employee = employee; + } + + public String toString() { + return "Phone id: " + getId() + + ", no: " + getNumber() + + ", type: " + getType(); + } +} diff --git a/examples/Chapter6/19-removingWithRelationshipsCascade/src/model/examples/stateless/EmployeeService.java b/examples/Chapter6/19-removingWithRelationshipsCascade/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..2b74bfc --- /dev/null +++ b/examples/Chapter6/19-removingWithRelationshipsCascade/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,12 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; +import examples.model.Phone; + +public interface EmployeeService { + public void removeEmployee(int empId); + public Collection findAllPhones(); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter6/19-removingWithRelationshipsCascade/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter6/19-removingWithRelationshipsCascade/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..1d39dd2 --- /dev/null +++ b/examples/Chapter6/19-removingWithRelationshipsCascade/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,32 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Employee; +import examples.model.Phone; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + EntityManager em; + + public void removeEmployee(int empId) { + Employee emp = em.find(Employee.class, empId); + em.remove(emp); + + } + + public Collection findAllEmployees() { + return (Collection) em.createQuery( + "SELECT e FROM Employee e").getResultList(); + } + + public Collection findAllPhones() { + return (Collection) em.createQuery( + "SELECT p FROM Phone p").getResultList(); + } +} diff --git a/examples/Chapter6/19-removingWithRelationshipsCascade/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter6/19-removingWithRelationshipsCascade/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..e58b765 --- /dev/null +++ b/examples/Chapter6/19-removingWithRelationshipsCascade/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,90 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateless.EmployeeService; + +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 6: Removing Entities with Relationships using Cascade Example"; + + private final String DESCRIPTION = + "This example shows how to remove an entity with relationships."; + + + @EJB + private EmployeeService empService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action != null) { + if (action.equals("Remove")) { + empService.removeEmployee( + parseInt(request.getParameter("empId"))); + } + } + + out.println("Employees:
"); + printCollection(empService.findAllEmployees(), out); + + out.println("
Phones:
"); + printCollection(empService.findAllPhones(), out); + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printCollection(Collection c, PrintWriter out) { + for (Object o : c) { + out.print(o + "
"); + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + + out.println(""); + out.println("

Remove Employee and related Entities

"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
"); + out.println("
"); + } + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter6/19-removingWithRelationshipsCascade/undeploy.bat b/examples/Chapter6/19-removingWithRelationshipsCascade/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter6/19-removingWithRelationshipsCascade/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter6/20-mergingDetachedEntities/build.xml b/examples/Chapter6/20-mergingDetachedEntities/build.xml new file mode 100644 index 0000000..e80927b --- /dev/null +++ b/examples/Chapter6/20-mergingDetachedEntities/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/20-mergingDetachedEntities/deploy.bat b/examples/Chapter6/20-mergingDetachedEntities/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter6/20-mergingDetachedEntities/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter6/20-mergingDetachedEntities/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/20-mergingDetachedEntities/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..1309c0d --- /dev/null +++ b/examples/Chapter6/20-mergingDetachedEntities/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/mergingDetachedEntities + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/20-mergingDetachedEntities/etc/sql/db.sql b/examples/Chapter6/20-mergingDetachedEntities/etc/sql/db.sql new file mode 100644 index 0000000..cf5762b --- /dev/null +++ b/examples/Chapter6/20-mergingDetachedEntities/etc/sql/db.sql @@ -0,0 +1,9 @@ +DROP TABLE EMPLOYEE; + +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), LASTACCESSTIME TIMESTAMP, PRIMARY KEY (ID)); + +INSERT INTO EMPLOYEE (ID, NAME) VALUES (1, 'Joan'); +INSERT INTO EMPLOYEE (ID, NAME) VALUES (2, 'Sarah'); +INSERT INTO EMPLOYEE (ID, NAME) VALUES (3, 'John'); +INSERT INTO EMPLOYEE (ID, NAME) VALUES (4, 'Roberts'); +INSERT INTO EMPLOYEE (ID, NAME) VALUES (5, 'Peter'); \ No newline at end of file diff --git a/examples/Chapter6/20-mergingDetachedEntities/etc/web/WEB-INF/web.xml b/examples/Chapter6/20-mergingDetachedEntities/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter6/20-mergingDetachedEntities/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServiceServlet + examples.servlet.EmployeeServiceServlet + + + + EmployeeServiceServlet + /EmployeeServiceServlet + + \ No newline at end of file diff --git a/examples/Chapter6/20-mergingDetachedEntities/src/model/examples/model/Employee.java b/examples/Chapter6/20-mergingDetachedEntities/src/model/examples/model/Employee.java new file mode 100644 index 0000000..ee504f9 --- /dev/null +++ b/examples/Chapter6/20-mergingDetachedEntities/src/model/examples/model/Employee.java @@ -0,0 +1,49 @@ +package examples.model; + +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +public class Employee { + @Id + private int id; + private String name; + + @Temporal(TemporalType.TIMESTAMP) + private Date lastAccessTime; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Date getLastAccessTime() { + return lastAccessTime; + } + + public void setLastAccessTime(Date lastAccessTime) { + this.lastAccessTime = lastAccessTime; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + " lastAccessTime: " + getLastAccessTime(); + } +} diff --git a/examples/Chapter6/20-mergingDetachedEntities/src/model/examples/stateless/EmployeeService.java b/examples/Chapter6/20-mergingDetachedEntities/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..9b9bbee --- /dev/null +++ b/examples/Chapter6/20-mergingDetachedEntities/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public void updateEmployee(Employee emp); + public void updateEmployeeIncorrect(Employee emp); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter6/20-mergingDetachedEntities/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter6/20-mergingDetachedEntities/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..ccd2528 --- /dev/null +++ b/examples/Chapter6/20-mergingDetachedEntities/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,37 @@ +package examples.stateless; + +import java.util.Collection; +import java.util.Date; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + EntityManager em; + + public void updateEmployee(Employee emp) { + if (em.find(Employee.class, emp.getId()) == null) { + throw new IllegalArgumentException("Unknown employee id: " + emp.getId()); + } + Employee managedEmp = em.merge(emp); + managedEmp.setLastAccessTime(new Date()); + } + + public void updateEmployeeIncorrect(Employee emp) { + if (em.find(Employee.class, emp.getId()) == null) { + throw new IllegalArgumentException("Unknown employee id: " + emp.getId()); + } + em.merge(emp); + emp.setLastAccessTime(new Date()); + } + + public Collection findAllEmployees() { + return (Collection) em.createQuery( + "SELECT e FROM Employee e").getResultList(); + } +} diff --git a/examples/Chapter6/20-mergingDetachedEntities/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter6/20-mergingDetachedEntities/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..4184a45 --- /dev/null +++ b/examples/Chapter6/20-mergingDetachedEntities/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,103 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.stateless.EmployeeService; + +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 6: Merging Detached Entities Example"; + + private final String DESCRIPTION = + "This example shows the correct and incorrect way to merge a " + + "detached entity."; + + + @EJB + private EmployeeService empService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action != null) { + if (action.equals("Update")) { + int id = parseInt(request.getParameter("empId")); + String name = request.getParameter("name"); + Employee emp = new Employee(); + emp.setId(id); + emp.setName(name); + empService.updateEmployee(emp); + } else if (action.equals("UpdateIncorrect")) { + int id = parseInt(request.getParameter("empId")); + String name = request.getParameter("name"); + Employee emp = new Employee(); + emp.setId(id); + emp.setName(name); + empService.updateEmployeeIncorrect(emp); + } + } + + out.println("Employees:
"); + printCollection(empService.findAllEmployees(), out); + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printCollection(Collection c, PrintWriter out) { + for (Object o : c) { + out.print(o + "
"); + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + + out.println(""); + out.println("

Update Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
New Name:(String)
"); + out.println(""); + out.println("
"); + } + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter6/20-mergingDetachedEntities/undeploy.bat b/examples/Chapter6/20-mergingDetachedEntities/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter6/20-mergingDetachedEntities/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/build.xml b/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/build.xml new file mode 100644 index 0000000..ccdbc09 --- /dev/null +++ b/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/deploy.bat b/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..578a60a --- /dev/null +++ b/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/detachmentWithTriggeredLazyLoading + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/etc/sql/db.sql b/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/etc/sql/db.sql new file mode 100644 index 0000000..5e4ea5b --- /dev/null +++ b/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/etc/sql/db.sql @@ -0,0 +1,23 @@ +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, + DEPARTMENT_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPARTMENT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID)); + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'CA13'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'CA19'); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (1, 'Joan', 59000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (2, 'Sarah', 52000, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (3, 'John', 55000, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (4, 'Roberts', 53000, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (5, 'Peter', 50000, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (6, 'Frank', 51000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (7, 'Scott', 60000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (8, 'Sue', 62000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (9, 'Stephanie', 54000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (10, 'Jennifer', 55000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (11, 'Marcus', 35000, NULL); \ No newline at end of file diff --git a/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/etc/web/WEB-INF/web.xml b/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5d96981 --- /dev/null +++ b/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/etc/web/listEmployees.jsp b/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/etc/web/listEmployees.jsp new file mode 100644 index 0000000..7da7758 --- /dev/null +++ b/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/etc/web/listEmployees.jsp @@ -0,0 +1,25 @@ + +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> + + + All Employees + + + + + + + + + + + + + + + + + +
NameDepartment
+ + diff --git a/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/src/model/examples/model/Department.java b/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/src/model/examples/model/Department.java @@ -0,0 +1,46 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="department") + private Collection employees; + + public Department() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/src/model/examples/model/Employee.java b/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/src/model/examples/model/Employee.java new file mode 100644 index 0000000..c6a74ed --- /dev/null +++ b/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/src/model/examples/model/Employee.java @@ -0,0 +1,49 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import javax.persistence.FetchType; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + + @ManyToOne(fetch=FetchType.LAZY) + private Department department; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + + public long getSalary() { + return salary; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department dept) { + this.department = dept; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary(); + } +} diff --git a/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/src/model/examples/stateless/EmployeeService.java b/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..3c54249 --- /dev/null +++ b/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,7 @@ +package examples.stateless; + +import java.util.List; + +public interface EmployeeService { + public List findAll(); +} \ No newline at end of file diff --git a/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..d9ad9ca --- /dev/null +++ b/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,26 @@ +package examples.stateless; + +import java.util.List; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + private EntityManager em; + + public List findAll() { + List emps = em.createQuery("SELECT e FROM Employee e") + .getResultList(); + for (Employee emp : emps) { + if (emp.getDepartment() != null) { + emp.getDepartment().getName(); + } + } + return emps; + } +} diff --git a/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..623b994 --- /dev/null +++ b/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,28 @@ +package examples.servlet; + +import java.io.IOException; +import java.util.List; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + @EJB + private EmployeeService bean; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + List emps = bean.findAll(); + request.setAttribute("employees", emps); + getServletContext().getRequestDispatcher("/listEmployees.jsp") + .forward(request, response); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } +} diff --git a/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/undeploy.bat b/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter6/21-detachmentWithTriggeredLazyLoading/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter6/22-detachmentWithEagerLoading/build.xml b/examples/Chapter6/22-detachmentWithEagerLoading/build.xml new file mode 100644 index 0000000..aa6a0a7 --- /dev/null +++ b/examples/Chapter6/22-detachmentWithEagerLoading/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/22-detachmentWithEagerLoading/deploy.bat b/examples/Chapter6/22-detachmentWithEagerLoading/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter6/22-detachmentWithEagerLoading/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter6/22-detachmentWithEagerLoading/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/22-detachmentWithEagerLoading/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..47ade70 --- /dev/null +++ b/examples/Chapter6/22-detachmentWithEagerLoading/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/detachmentWithEagerLoading + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/22-detachmentWithEagerLoading/etc/sql/db.sql b/examples/Chapter6/22-detachmentWithEagerLoading/etc/sql/db.sql new file mode 100644 index 0000000..5e4ea5b --- /dev/null +++ b/examples/Chapter6/22-detachmentWithEagerLoading/etc/sql/db.sql @@ -0,0 +1,23 @@ +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, + DEPARTMENT_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPARTMENT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID)); + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'CA13'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'CA19'); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (1, 'Joan', 59000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (2, 'Sarah', 52000, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (3, 'John', 55000, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (4, 'Roberts', 53000, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (5, 'Peter', 50000, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (6, 'Frank', 51000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (7, 'Scott', 60000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (8, 'Sue', 62000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (9, 'Stephanie', 54000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (10, 'Jennifer', 55000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (11, 'Marcus', 35000, NULL); \ No newline at end of file diff --git a/examples/Chapter6/22-detachmentWithEagerLoading/etc/web/WEB-INF/web.xml b/examples/Chapter6/22-detachmentWithEagerLoading/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5d96981 --- /dev/null +++ b/examples/Chapter6/22-detachmentWithEagerLoading/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter6/22-detachmentWithEagerLoading/etc/web/listEmployees.jsp b/examples/Chapter6/22-detachmentWithEagerLoading/etc/web/listEmployees.jsp new file mode 100644 index 0000000..7da7758 --- /dev/null +++ b/examples/Chapter6/22-detachmentWithEagerLoading/etc/web/listEmployees.jsp @@ -0,0 +1,25 @@ + +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> + + + All Employees + + + + + + + + + + + + + + + + + +
NameDepartment
+ + diff --git a/examples/Chapter6/22-detachmentWithEagerLoading/src/model/examples/model/Department.java b/examples/Chapter6/22-detachmentWithEagerLoading/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter6/22-detachmentWithEagerLoading/src/model/examples/model/Department.java @@ -0,0 +1,46 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="department") + private Collection employees; + + public Department() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter6/22-detachmentWithEagerLoading/src/model/examples/model/Employee.java b/examples/Chapter6/22-detachmentWithEagerLoading/src/model/examples/model/Employee.java new file mode 100644 index 0000000..8b1778b --- /dev/null +++ b/examples/Chapter6/22-detachmentWithEagerLoading/src/model/examples/model/Employee.java @@ -0,0 +1,49 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + + @ManyToOne(fetch=FetchType.EAGER) + private Department department; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + + public long getSalary() { + return salary; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department dept) { + this.department = dept; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary(); + } +} diff --git a/examples/Chapter6/22-detachmentWithEagerLoading/src/model/examples/stateless/EmployeeService.java b/examples/Chapter6/22-detachmentWithEagerLoading/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..3c54249 --- /dev/null +++ b/examples/Chapter6/22-detachmentWithEagerLoading/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,7 @@ +package examples.stateless; + +import java.util.List; + +public interface EmployeeService { + public List findAll(); +} \ No newline at end of file diff --git a/examples/Chapter6/22-detachmentWithEagerLoading/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter6/22-detachmentWithEagerLoading/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..3c0c0a6 --- /dev/null +++ b/examples/Chapter6/22-detachmentWithEagerLoading/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,18 @@ +package examples.stateless; + +import java.util.List; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + private EntityManager em; + + public List findAll() { + return em.createQuery("SELECT e FROM Employee e") + .getResultList(); + } +} diff --git a/examples/Chapter6/22-detachmentWithEagerLoading/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter6/22-detachmentWithEagerLoading/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..623b994 --- /dev/null +++ b/examples/Chapter6/22-detachmentWithEagerLoading/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,28 @@ +package examples.servlet; + +import java.io.IOException; +import java.util.List; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + @EJB + private EmployeeService bean; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + List emps = bean.findAll(); + request.setAttribute("employees", emps); + getServletContext().getRequestDispatcher("/listEmployees.jsp") + .forward(request, response); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } +} diff --git a/examples/Chapter6/22-detachmentWithEagerLoading/undeploy.bat b/examples/Chapter6/22-detachmentWithEagerLoading/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter6/22-detachmentWithEagerLoading/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter6/23-noDetachmentSingleTx/build.xml b/examples/Chapter6/23-noDetachmentSingleTx/build.xml new file mode 100644 index 0000000..9c3c6d2 --- /dev/null +++ b/examples/Chapter6/23-noDetachmentSingleTx/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/23-noDetachmentSingleTx/deploy.bat b/examples/Chapter6/23-noDetachmentSingleTx/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter6/23-noDetachmentSingleTx/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter6/23-noDetachmentSingleTx/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/23-noDetachmentSingleTx/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..ca1eebb --- /dev/null +++ b/examples/Chapter6/23-noDetachmentSingleTx/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/noDetachmentSingleTx + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/23-noDetachmentSingleTx/etc/sql/db.sql b/examples/Chapter6/23-noDetachmentSingleTx/etc/sql/db.sql new file mode 100644 index 0000000..5e4ea5b --- /dev/null +++ b/examples/Chapter6/23-noDetachmentSingleTx/etc/sql/db.sql @@ -0,0 +1,23 @@ +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, + DEPARTMENT_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPARTMENT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID)); + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'CA13'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'CA19'); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (1, 'Joan', 59000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (2, 'Sarah', 52000, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (3, 'John', 55000, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (4, 'Roberts', 53000, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (5, 'Peter', 50000, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (6, 'Frank', 51000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (7, 'Scott', 60000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (8, 'Sue', 62000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (9, 'Stephanie', 54000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (10, 'Jennifer', 55000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (11, 'Marcus', 35000, NULL); \ No newline at end of file diff --git a/examples/Chapter6/23-noDetachmentSingleTx/etc/web/WEB-INF/web.xml b/examples/Chapter6/23-noDetachmentSingleTx/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5d96981 --- /dev/null +++ b/examples/Chapter6/23-noDetachmentSingleTx/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter6/23-noDetachmentSingleTx/etc/web/listEmployees.jsp b/examples/Chapter6/23-noDetachmentSingleTx/etc/web/listEmployees.jsp new file mode 100644 index 0000000..7da7758 --- /dev/null +++ b/examples/Chapter6/23-noDetachmentSingleTx/etc/web/listEmployees.jsp @@ -0,0 +1,25 @@ + +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> + + + All Employees + + + + + + + + + + + + + + + + + +
NameDepartment
+ + diff --git a/examples/Chapter6/23-noDetachmentSingleTx/src/model/examples/model/Department.java b/examples/Chapter6/23-noDetachmentSingleTx/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter6/23-noDetachmentSingleTx/src/model/examples/model/Department.java @@ -0,0 +1,46 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="department") + private Collection employees; + + public Department() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter6/23-noDetachmentSingleTx/src/model/examples/model/Employee.java b/examples/Chapter6/23-noDetachmentSingleTx/src/model/examples/model/Employee.java new file mode 100644 index 0000000..6bcf568 --- /dev/null +++ b/examples/Chapter6/23-noDetachmentSingleTx/src/model/examples/model/Employee.java @@ -0,0 +1,48 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + + @ManyToOne + private Department department; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + + public long getSalary() { + return salary; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department dept) { + this.department = dept; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary(); + } +} diff --git a/examples/Chapter6/23-noDetachmentSingleTx/src/model/examples/stateless/EmployeeService.java b/examples/Chapter6/23-noDetachmentSingleTx/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..3c54249 --- /dev/null +++ b/examples/Chapter6/23-noDetachmentSingleTx/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,7 @@ +package examples.stateless; + +import java.util.List; + +public interface EmployeeService { + public List findAll(); +} \ No newline at end of file diff --git a/examples/Chapter6/23-noDetachmentSingleTx/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter6/23-noDetachmentSingleTx/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..3c0c0a6 --- /dev/null +++ b/examples/Chapter6/23-noDetachmentSingleTx/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,18 @@ +package examples.stateless; + +import java.util.List; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + private EntityManager em; + + public List findAll() { + return em.createQuery("SELECT e FROM Employee e") + .getResultList(); + } +} diff --git a/examples/Chapter6/23-noDetachmentSingleTx/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter6/23-noDetachmentSingleTx/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..fec7664 --- /dev/null +++ b/examples/Chapter6/23-noDetachmentSingleTx/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,41 @@ +package examples.servlet; + +import java.io.IOException; +import java.util.List; + +import javax.annotation.Resource; +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.transaction.UserTransaction; + +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + @Resource UserTransaction tx; + @EJB EmployeeService bean; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + try { + tx.begin(); + List emps = bean.findAll(); + request.setAttribute("employees", emps); + getServletContext().getRequestDispatcher("/listEmployees.jsp") + .forward(request, response); + } catch (Exception e) { + throw new ServletException(e); + } finally { + try { + tx.commit(); + } catch (Exception e) { + throw new ServletException(e); + } + } + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } +} diff --git a/examples/Chapter6/23-noDetachmentSingleTx/undeploy.bat b/examples/Chapter6/23-noDetachmentSingleTx/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter6/23-noDetachmentSingleTx/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter6/24-noDetachmentAppManagedEm/build.xml b/examples/Chapter6/24-noDetachmentAppManagedEm/build.xml new file mode 100644 index 0000000..ca0c0a6 --- /dev/null +++ b/examples/Chapter6/24-noDetachmentAppManagedEm/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/24-noDetachmentAppManagedEm/deploy.bat b/examples/Chapter6/24-noDetachmentAppManagedEm/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter6/24-noDetachmentAppManagedEm/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter6/24-noDetachmentAppManagedEm/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/24-noDetachmentAppManagedEm/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..932185a --- /dev/null +++ b/examples/Chapter6/24-noDetachmentAppManagedEm/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/noDetachmentAppManagedEm + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/24-noDetachmentAppManagedEm/etc/sql/db.sql b/examples/Chapter6/24-noDetachmentAppManagedEm/etc/sql/db.sql new file mode 100644 index 0000000..5e4ea5b --- /dev/null +++ b/examples/Chapter6/24-noDetachmentAppManagedEm/etc/sql/db.sql @@ -0,0 +1,23 @@ +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, + DEPARTMENT_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPARTMENT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID)); + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'CA13'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'CA19'); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (1, 'Joan', 59000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (2, 'Sarah', 52000, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (3, 'John', 55000, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (4, 'Roberts', 53000, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (5, 'Peter', 50000, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (6, 'Frank', 51000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (7, 'Scott', 60000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (8, 'Sue', 62000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (9, 'Stephanie', 54000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (10, 'Jennifer', 55000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (11, 'Marcus', 35000, NULL); \ No newline at end of file diff --git a/examples/Chapter6/24-noDetachmentAppManagedEm/etc/web/WEB-INF/web.xml b/examples/Chapter6/24-noDetachmentAppManagedEm/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5d96981 --- /dev/null +++ b/examples/Chapter6/24-noDetachmentAppManagedEm/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter6/24-noDetachmentAppManagedEm/etc/web/listEmployees.jsp b/examples/Chapter6/24-noDetachmentAppManagedEm/etc/web/listEmployees.jsp new file mode 100644 index 0000000..7da7758 --- /dev/null +++ b/examples/Chapter6/24-noDetachmentAppManagedEm/etc/web/listEmployees.jsp @@ -0,0 +1,25 @@ + +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> + + + All Employees + + + + + + + + + + + + + + + + + +
NameDepartment
+ + diff --git a/examples/Chapter6/24-noDetachmentAppManagedEm/src/model/examples/model/Department.java b/examples/Chapter6/24-noDetachmentAppManagedEm/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter6/24-noDetachmentAppManagedEm/src/model/examples/model/Department.java @@ -0,0 +1,46 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="department") + private Collection employees; + + public Department() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter6/24-noDetachmentAppManagedEm/src/model/examples/model/Employee.java b/examples/Chapter6/24-noDetachmentAppManagedEm/src/model/examples/model/Employee.java new file mode 100644 index 0000000..6bcf568 --- /dev/null +++ b/examples/Chapter6/24-noDetachmentAppManagedEm/src/model/examples/model/Employee.java @@ -0,0 +1,48 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + + @ManyToOne + private Department department; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + + public long getSalary() { + return salary; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department dept) { + this.department = dept; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary(); + } +} diff --git a/examples/Chapter6/24-noDetachmentAppManagedEm/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter6/24-noDetachmentAppManagedEm/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..b86073b --- /dev/null +++ b/examples/Chapter6/24-noDetachmentAppManagedEm/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,35 @@ +package examples.servlet; + +import java.io.IOException; +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.PersistenceUnit; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public class EmployeeServlet extends HttpServlet { + @PersistenceUnit(unitName="EmployeeService") + EntityManagerFactory emf; + + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + EntityManager em = emf.createEntityManager(); + try { + List emps = em.createQuery("SELECT e FROM Employee e") + .getResultList(); + request.setAttribute("employees", emps); + getServletContext().getRequestDispatcher("/listEmployees.jsp") + .forward(request, response); + } finally { + em.close(); + } + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } +} diff --git a/examples/Chapter6/24-noDetachmentAppManagedEm/undeploy.bat b/examples/Chapter6/24-noDetachmentAppManagedEm/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter6/24-noDetachmentAppManagedEm/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/build.xml b/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/build.xml new file mode 100644 index 0000000..13bf76d --- /dev/null +++ b/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/deploy.bat b/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..83e8428 --- /dev/null +++ b/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/noDetachmentSFSBAndExtendedEm + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/etc/sql/db.sql b/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/etc/sql/db.sql new file mode 100644 index 0000000..5e4ea5b --- /dev/null +++ b/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/etc/sql/db.sql @@ -0,0 +1,23 @@ +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, + DEPARTMENT_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPARTMENT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID)); + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'CA13'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'CA19'); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (1, 'Joan', 59000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (2, 'Sarah', 52000, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (3, 'John', 55000, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (4, 'Roberts', 53000, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (5, 'Peter', 50000, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (6, 'Frank', 51000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (7, 'Scott', 60000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (8, 'Sue', 62000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (9, 'Stephanie', 54000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (10, 'Jennifer', 55000, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID) VALUES (11, 'Marcus', 35000, NULL); \ No newline at end of file diff --git a/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/etc/web/WEB-INF/web.xml b/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5d96981 --- /dev/null +++ b/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + \ No newline at end of file diff --git a/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/etc/web/listEmployees.jsp b/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/etc/web/listEmployees.jsp new file mode 100644 index 0000000..d345f64 --- /dev/null +++ b/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/etc/web/listEmployees.jsp @@ -0,0 +1,25 @@ + +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> + + + 6-25: All Employees + + + + + + + + + + + + + + + + + +
NameDepartment
+ + diff --git a/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/src/model/examples/model/Department.java b/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/src/model/examples/model/Department.java @@ -0,0 +1,46 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="department") + private Collection employees; + + public Department() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/src/model/examples/model/Employee.java b/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/src/model/examples/model/Employee.java new file mode 100644 index 0000000..6bcf568 --- /dev/null +++ b/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/src/model/examples/model/Employee.java @@ -0,0 +1,48 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + + @ManyToOne + private Department department; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + + public long getSalary() { + return salary; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department dept) { + this.department = dept; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary(); + } +} diff --git a/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/src/model/examples/stateful/EmployeeQuery.java b/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/src/model/examples/stateful/EmployeeQuery.java new file mode 100644 index 0000000..52565ae --- /dev/null +++ b/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/src/model/examples/stateful/EmployeeQuery.java @@ -0,0 +1,8 @@ +package examples.stateful; + +import java.util.List; + +public interface EmployeeQuery { + public List findAll(); + public void finished(); +} \ No newline at end of file diff --git a/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/src/model/examples/stateful/EmployeeQueryBean.java b/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/src/model/examples/stateful/EmployeeQueryBean.java new file mode 100644 index 0000000..25e0447 --- /dev/null +++ b/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/src/model/examples/stateful/EmployeeQueryBean.java @@ -0,0 +1,29 @@ +package examples.stateful; + +import java.util.List; + +import javax.ejb.Remove; +import javax.ejb.Stateful; +import javax.ejb.TransactionAttribute; +import javax.ejb.TransactionAttributeType; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.PersistenceContextType; + +@Stateful +@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) +public class EmployeeQueryBean implements EmployeeQuery { + @PersistenceContext(type=PersistenceContextType.EXTENDED, + unitName="EmployeeService") + EntityManager em; + + public List findAll() { + return em.createQuery("SELECT e FROM Employee e") + .getResultList(); + } + + @Remove + public void finished() { + } +} + diff --git a/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..de5bbb1 --- /dev/null +++ b/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,48 @@ +package examples.servlet; + +import java.io.IOException; +import java.util.List; + +import javax.ejb.EJB; +import javax.naming.InitialContext; +import javax.persistence.EntityManagerFactory; +import javax.persistence.PersistenceUnit; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateful.EmployeeQuery; + +@EJB(name="queryBean", beanInterface=EmployeeQuery.class) +public class EmployeeServlet extends HttpServlet { + // @PersistenceUnit(unitName="EmployeeService") + // EntityManagerFactory emf; + + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + EmployeeQuery bean = createQueryBean(); + try { + List emps = bean.findAll(); + request.setAttribute("employees", emps); + getServletContext().getRequestDispatcher("/listEmployees.jsp") + .forward(request, response); + } finally { + bean.finished(); + } + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private EmployeeQuery createQueryBean() throws ServletException { + // look up queryBean + try { + return (EmployeeQuery) + new InitialContext().lookup("java:comp/env/queryBean"); + } catch (Exception e) { + throw new ServletException(e); + } + } +} diff --git a/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/undeploy.bat b/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter6/25-noDetachmentSFSBAndExtendedEm/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter6/26-editSessionExample/build.xml b/examples/Chapter6/26-editSessionExample/build.xml new file mode 100644 index 0000000..1817a77 --- /dev/null +++ b/examples/Chapter6/26-editSessionExample/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/26-editSessionExample/deploy.bat b/examples/Chapter6/26-editSessionExample/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter6/26-editSessionExample/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter6/26-editSessionExample/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/26-editSessionExample/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..5e7d968 --- /dev/null +++ b/examples/Chapter6/26-editSessionExample/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/editSessionExample + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/26-editSessionExample/etc/sql/db.sql b/examples/Chapter6/26-editSessionExample/etc/sql/db.sql new file mode 100644 index 0000000..b62efcd --- /dev/null +++ b/examples/Chapter6/26-editSessionExample/etc/sql/db.sql @@ -0,0 +1,15 @@ +DROP TABLE EMPLOYEE; + +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, PRIMARY KEY (ID)); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY) VALUES (1, 'Joan', 59000); +INSERT INTO EMPLOYEE (ID, NAME, SALARY) VALUES (2, 'Sarah', 52000); +INSERT INTO EMPLOYEE (ID, NAME, SALARY) VALUES (3, 'John', 55000); +INSERT INTO EMPLOYEE (ID, NAME, SALARY) VALUES (4, 'Roberts', 53000); +INSERT INTO EMPLOYEE (ID, NAME, SALARY) VALUES (5, 'Peter', 50000); +INSERT INTO EMPLOYEE (ID, NAME, SALARY) VALUES (6, 'Frank', 51000); +INSERT INTO EMPLOYEE (ID, NAME, SALARY) VALUES (7, 'Scott', 60000); +INSERT INTO EMPLOYEE (ID, NAME, SALARY) VALUES (8, 'Sue', 62000); +INSERT INTO EMPLOYEE (ID, NAME, SALARY) VALUES (9, 'Stephanie', 54000); +INSERT INTO EMPLOYEE (ID, NAME, SALARY) VALUES (10, 'Jennifer', 55000); +INSERT INTO EMPLOYEE (ID, NAME, SALARY) VALUES (11, 'Marcus', 35000); \ No newline at end of file diff --git a/examples/Chapter6/26-editSessionExample/etc/web/WEB-INF/web.xml b/examples/Chapter6/26-editSessionExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..c25518c --- /dev/null +++ b/examples/Chapter6/26-editSessionExample/etc/web/WEB-INF/web.xml @@ -0,0 +1,31 @@ + + + + EmployeeServiceServlet + examples.servlet.EmployeeServiceServlet + + + EmployeeEditServlet + examples.servlet.EmployeeEditServlet + + + EmployeeUpdateServlet + examples.servlet.EmployeeUpdateServlet + + + + EmployeeServiceServlet + /EmployeeServiceServlet + + + EmployeeEditServlet + /EmployeeEditServlet + + + EmployeeUpdateServlet + /EmployeeUpdateServlet + + \ No newline at end of file diff --git a/examples/Chapter6/26-editSessionExample/etc/web/editEmployee.jsp b/examples/Chapter6/26-editSessionExample/etc/web/editEmployee.jsp new file mode 100644 index 0000000..02d7dc0 --- /dev/null +++ b/examples/Chapter6/26-editSessionExample/etc/web/editEmployee.jsp @@ -0,0 +1,21 @@ + +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> + + + Edit Employee + + + +

Editing Employee with id: ${employee.id}

+ + + + + + +
Name: (String)
Salary: (long)
+ + + + + diff --git a/examples/Chapter6/26-editSessionExample/etc/web/listEmployees.jsp b/examples/Chapter6/26-editSessionExample/etc/web/listEmployees.jsp new file mode 100644 index 0000000..e6b6a64 --- /dev/null +++ b/examples/Chapter6/26-editSessionExample/etc/web/listEmployees.jsp @@ -0,0 +1,35 @@ + +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> + + + All Employees + + +

Chapter 5: Employee Edit Session Example

+ This example shows how to use a SFSB and an extended EntityManager to + avoid detaching/merging entities. + +
+ + + + + + + + + + + + + + + + + + +
IdNameSalary
+ +
+ + diff --git a/examples/Chapter6/26-editSessionExample/src/model/examples/model/Employee.java b/examples/Chapter6/26-editSessionExample/src/model/examples/model/Employee.java new file mode 100644 index 0000000..0601a4c --- /dev/null +++ b/examples/Chapter6/26-editSessionExample/src/model/examples/model/Employee.java @@ -0,0 +1,43 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + " salary: " + getSalary(); + } +} diff --git a/examples/Chapter6/26-editSessionExample/src/model/examples/stateful/EmployeeEdit.java b/examples/Chapter6/26-editSessionExample/src/model/examples/stateful/EmployeeEdit.java new file mode 100644 index 0000000..07ac9ca --- /dev/null +++ b/examples/Chapter6/26-editSessionExample/src/model/examples/stateful/EmployeeEdit.java @@ -0,0 +1,10 @@ +package examples.stateful; + +import examples.model.Employee; + +public interface EmployeeEdit { + public void begin(int id); + public Employee getEmployee(); + public void save(); + public void cancel(); +} diff --git a/examples/Chapter6/26-editSessionExample/src/model/examples/stateful/EmployeeEditBean.java b/examples/Chapter6/26-editSessionExample/src/model/examples/stateful/EmployeeEditBean.java new file mode 100644 index 0000000..c75532c --- /dev/null +++ b/examples/Chapter6/26-editSessionExample/src/model/examples/stateful/EmployeeEditBean.java @@ -0,0 +1,38 @@ +package examples.stateful; + +import javax.ejb.Remove; +import javax.ejb.Stateful; +import javax.ejb.TransactionAttribute; +import javax.ejb.TransactionAttributeType; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.PersistenceContextType; + +import examples.model.Employee; + +@Stateful +@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) +public class EmployeeEditBean implements EmployeeEdit { + @PersistenceContext(type=PersistenceContextType.EXTENDED, + unitName="EmployeeService") + EntityManager em; + Employee emp; + + public void begin(int id) { + emp = em.find(Employee.class, id); + if (emp == null) { + throw new IllegalArgumentException("Unknown employee id: " + id); + } + } + + public Employee getEmployee() { + return emp; + } + + @Remove + @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) + public void save() {} + + @Remove + public void cancel() {} +} \ No newline at end of file diff --git a/examples/Chapter6/26-editSessionExample/src/model/examples/stateless/EmployeeService.java b/examples/Chapter6/26-editSessionExample/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..3c54249 --- /dev/null +++ b/examples/Chapter6/26-editSessionExample/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,7 @@ +package examples.stateless; + +import java.util.List; + +public interface EmployeeService { + public List findAll(); +} \ No newline at end of file diff --git a/examples/Chapter6/26-editSessionExample/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter6/26-editSessionExample/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..3c0c0a6 --- /dev/null +++ b/examples/Chapter6/26-editSessionExample/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,18 @@ +package examples.stateless; + +import java.util.List; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + private EntityManager em; + + public List findAll() { + return em.createQuery("SELECT e FROM Employee e") + .getResultList(); + } +} diff --git a/examples/Chapter6/26-editSessionExample/src/servlet/examples/servlet/EmployeeEditServlet.java b/examples/Chapter6/26-editSessionExample/src/servlet/examples/servlet/EmployeeEditServlet.java new file mode 100644 index 0000000..307368c --- /dev/null +++ b/examples/Chapter6/26-editSessionExample/src/servlet/examples/servlet/EmployeeEditServlet.java @@ -0,0 +1,48 @@ +package examples.servlet; + +import java.io.IOException; + +import javax.naming.InitialContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import examples.stateful.EmployeeEdit; + +public class EmployeeEditServlet extends HttpServlet { + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + int id = parseInt(request.getParameter("id")); + EmployeeEdit bean = getBean(); + bean.begin(id); + HttpSession session = request.getSession(); + session.setAttribute("employee.edit", bean); + request.setAttribute("employee", bean.getEmployee()); + getServletContext().getRequestDispatcher("/editEmployee.jsp") + .forward(request, response); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + public EmployeeEdit getBean() throws ServletException { + // lookup EmployeeEdit bean + try { + return (EmployeeEdit) + new InitialContext().lookup("java:comp/env/EmployeeEdit"); + } catch (Exception e) { + throw new ServletException(e); + } + } +} diff --git a/examples/Chapter6/26-editSessionExample/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter6/26-editSessionExample/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..34a7c43 --- /dev/null +++ b/examples/Chapter6/26-editSessionExample/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,28 @@ +package examples.servlet; + +import java.io.IOException; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateless.EmployeeService; + +public class EmployeeServiceServlet extends HttpServlet { + + @EJB + private EmployeeService empService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + request.setAttribute("employees", empService.findAll()); + getServletContext().getRequestDispatcher("/listEmployees.jsp") + .forward(request, response); + + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } +} \ No newline at end of file diff --git a/examples/Chapter6/26-editSessionExample/src/servlet/examples/servlet/EmployeeUpdateServlet.java b/examples/Chapter6/26-editSessionExample/src/servlet/examples/servlet/EmployeeUpdateServlet.java new file mode 100644 index 0000000..3281cf0 --- /dev/null +++ b/examples/Chapter6/26-editSessionExample/src/servlet/examples/servlet/EmployeeUpdateServlet.java @@ -0,0 +1,54 @@ +package examples.servlet; + +import java.io.IOException; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import examples.model.Employee; +import examples.stateful.EmployeeEdit; +import examples.stateless.EmployeeService; + +@EJB(name="EmployeeEdit", beanInterface=EmployeeEdit.class) +public class EmployeeUpdateServlet extends HttpServlet { + @EJB EmployeeService empService; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + HttpSession session = request.getSession(); + EmployeeEdit bean = (EmployeeEdit) session.getAttribute("employee.edit"); + + String action = request.getParameter("action"); + if (action.equals("Save")) { + String name = request.getParameter("name"); + long salary = parseLong(request.getParameter("salary")); + Employee emp = bean.getEmployee(); + emp.setName(name); + emp.setSalary(salary); + bean.save(); + } else if (action.equals("Cancel")) { + bean.cancel(); + } + + session.removeAttribute("employee.edit"); + + request.setAttribute("employees", empService.findAll()); + getServletContext().getRequestDispatcher("/listEmployees.jsp") + .forward(request, response); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } +} diff --git a/examples/Chapter6/26-editSessionExample/undeploy.bat b/examples/Chapter6/26-editSessionExample/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter6/26-editSessionExample/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter7/01-dynamicQueryExample/build.xml b/examples/Chapter7/01-dynamicQueryExample/build.xml new file mode 100644 index 0000000..f285175 --- /dev/null +++ b/examples/Chapter7/01-dynamicQueryExample/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter7/01-dynamicQueryExample/deploy.bat b/examples/Chapter7/01-dynamicQueryExample/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter7/01-dynamicQueryExample/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter7/01-dynamicQueryExample/etc/persistence/META-INF/persistence.xml b/examples/Chapter7/01-dynamicQueryExample/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..7ecba69 --- /dev/null +++ b/examples/Chapter7/01-dynamicQueryExample/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/dynamicQueryExample + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter7/01-dynamicQueryExample/etc/sql/db.sql b/examples/Chapter7/01-dynamicQueryExample/etc/sql/db.sql new file mode 100644 index 0000000..1d29472 --- /dev/null +++ b/examples/Chapter7/01-dynamicQueryExample/etc/sql/db.sql @@ -0,0 +1,57 @@ +DROP TABLE EMPLOYEE_PROJECT; +DROP TABLE PROJECT; +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE PROJECT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), STARTDATE DATE, SALARY BIGINT, + DEPARTMENT_ID INTEGER, MANAGER_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPARTMENT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID), + CONSTRAINT MANAGER_FK FOREIGN KEY (MANAGER_ID) REFERENCES EMPLOYEE (ID)); +CREATE TABLE EMPLOYEE_PROJECT (PROJECTS_ID INTEGER NOT NULL, EMPLOYEES_ID INTEGER NOT NULL, + CONSTRAINT PROJECTS_FK FOREIGN KEY (PROJECTS_ID) REFERENCES PROJECT (ID), + CONSTRAINT EMPLOYEES_FK FOREIGN KEY (EMPLOYEES_ID) REFERENCES EMPLOYEE (ID), + PRIMARY KEY (PROJECTS_ID, EMPLOYEES_ID)); + + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'CA13'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'CA19'); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (1, 'Joan', 59000, {d '2003-04-16'}, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (2, 'Sarah', 52000, {d '2002-04-26'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (3, 'John', 55000, {d '2001-01-01'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (4, 'Roberts', 53000, {d '2001-05-23'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (5, 'Peter', 50000, {d '2002-08-06'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (6, 'Frank', 51000, {d '2003-02-17'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (7, 'Scott', 60000, {d '2004-11-14'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (8, 'Sue', 62000, {d '2005-08-18'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (9, 'Stephanie', 54000, {d '2006-06-07'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (10, 'Jennifer', 55000, {d '1999-08-11'}, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (11, 'Marcus', 35000, {d '1995-07-22'}, NULL, NULL); + +INSERT INTO PROJECT (ID, NAME) VALUES (1, 'Design Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (2, 'Implement Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (3, 'Test Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (4, 'Release3'); + +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (1, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (4, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (7, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 3); \ No newline at end of file diff --git a/examples/Chapter7/01-dynamicQueryExample/etc/web/WEB-INF/web.xml b/examples/Chapter7/01-dynamicQueryExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..9f60be8 --- /dev/null +++ b/examples/Chapter7/01-dynamicQueryExample/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + QueryServiceServlet + examples.servlet.QueryServiceServlet + + + + QueryServiceServlet + /QueryServiceServlet + + \ No newline at end of file diff --git a/examples/Chapter7/01-dynamicQueryExample/src/model/examples/model/Department.java b/examples/Chapter7/01-dynamicQueryExample/src/model/examples/model/Department.java new file mode 100644 index 0000000..5704081 --- /dev/null +++ b/examples/Chapter7/01-dynamicQueryExample/src/model/examples/model/Department.java @@ -0,0 +1,38 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="department") + private Collection employees; + + public Department() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter7/01-dynamicQueryExample/src/model/examples/model/Employee.java b/examples/Chapter7/01-dynamicQueryExample/src/model/examples/model/Employee.java new file mode 100644 index 0000000..4bc3ecc --- /dev/null +++ b/examples/Chapter7/01-dynamicQueryExample/src/model/examples/model/Employee.java @@ -0,0 +1,79 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToMany; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + @Temporal(TemporalType.DATE) + private Date startDate; + + @ManyToOne + private Employee manager; + + @OneToMany(mappedBy="manager") + private Collection directs; + + @ManyToOne + private Department department; + + @ManyToMany + private Collection projects; + + public Employee() { + projects = new ArrayList(); + directs = new ArrayList(); + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public long getSalary() { + return salary; + } + + public Date getStartDate() { + return startDate; + } + + public Department getDepartment() { + return department; + } + + public Collection getDirects() { + return directs; + } + + public Employee getManager() { + return manager; + } + + public Collection getProjects() { + return projects; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary() + + ", dept: " + ((getDepartment() == null) ? null : getDepartment().getName()); + } +} diff --git a/examples/Chapter7/01-dynamicQueryExample/src/model/examples/model/Project.java b/examples/Chapter7/01-dynamicQueryExample/src/model/examples/model/Project.java new file mode 100644 index 0000000..8226327 --- /dev/null +++ b/examples/Chapter7/01-dynamicQueryExample/src/model/examples/model/Project.java @@ -0,0 +1,37 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToMany; + +@Entity +public class Project { + @Id + protected int id; + protected String name; + @ManyToMany(mappedBy="projects") + private Collection employees; + + public Project() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Project id: " + getId() + ", name: " + getName(); + } +} diff --git a/examples/Chapter7/01-dynamicQueryExample/src/model/examples/stateless/QueryService.java b/examples/Chapter7/01-dynamicQueryExample/src/model/examples/stateless/QueryService.java new file mode 100644 index 0000000..c8e8f00 --- /dev/null +++ b/examples/Chapter7/01-dynamicQueryExample/src/model/examples/stateless/QueryService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface QueryService { + public Collection findAllEmployees(); + public long queryEmpSalary(String deptName, String empName); + public long queryEmpSalaryUsingParams(String deptName, String empName); +} diff --git a/examples/Chapter7/01-dynamicQueryExample/src/model/examples/stateless/QueryServiceBean.java b/examples/Chapter7/01-dynamicQueryExample/src/model/examples/stateless/QueryServiceBean.java new file mode 100644 index 0000000..b0bf3d6 --- /dev/null +++ b/examples/Chapter7/01-dynamicQueryExample/src/model/examples/stateless/QueryServiceBean.java @@ -0,0 +1,51 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.NoResultException; +import javax.persistence.PersistenceContext; + +import examples.model.Employee; + +@Stateless +public class QueryServiceBean implements QueryService { + private static final String QUERY = + "SELECT e.salary " + + "FROM Employee e " + + "WHERE e.department.name = :deptName AND " + + " e.name = :empName "; + + @PersistenceContext(unitName="DynamicQueries") + EntityManager em; + + public long queryEmpSalary(String deptName, String empName) { + String query = "SELECT e.salary " + + "FROM Employee e " + + "WHERE e.department.name = '" + deptName + "' AND " + + " e.name = '" + empName + "'"; + try { + return (Long) em.createQuery(query).getSingleResult(); + } catch (NoResultException e) { + return 0; + } + } + + public long queryEmpSalaryUsingParams(String deptName, String empName) { + try { + return (Long) em.createQuery(QUERY) + .setParameter("deptName", deptName) + .setParameter("empName", empName) + .getSingleResult(); + } catch (NoResultException e) { + return 0; + } + } + + + public Collection findAllEmployees() { + return (Collection) em.createQuery( + "SELECT e FROM Employee e").getResultList(); + } +} diff --git a/examples/Chapter7/01-dynamicQueryExample/src/servlet/examples/servlet/QueryServiceServlet.java b/examples/Chapter7/01-dynamicQueryExample/src/servlet/examples/servlet/QueryServiceServlet.java new file mode 100644 index 0000000..7d0920e --- /dev/null +++ b/examples/Chapter7/01-dynamicQueryExample/src/servlet/examples/servlet/QueryServiceServlet.java @@ -0,0 +1,92 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.stateless.QueryService; + +public class QueryServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 7: Dynamic Query Example"; + + private final String DESCRIPTION = + "This example demonstrates the use of a dynamic query.
" + + "The example allows you to query the salary for a given employee " + + "in the given department. Make sure that you enter values in both fields. " + + "You can try the two options shown in the book, " + + "with or without parameters. Try a malicious query without parameters by " + + "using the String described in the book (_UNKNOWN' OR e.name = 'Roberts) " + + "for the employee name and a department that doesn't exist."; + + + @EJB + private QueryService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action != null) { + if (action.equals("Find")) { + long salary = service.queryEmpSalary( + request.getParameter("deptName"), + request.getParameter("empName")); + out.println("Found Salary: " + salary); + out.println("
"); + } else if (action.equals("FindUsingParams")) { + long salary = service.queryEmpSalaryUsingParams( + request.getParameter("deptName"), + request.getParameter("empName")); + out.println("Found Salary: " + salary); + out.println("
"); + } + } + out.println("All Employees:
"); + for (Employee emp : service.findAllEmployees()) { + out.print(emp + "
"); + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form find + out.println("

Find Employee Salary

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
Department Name:(String)
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter7/01-dynamicQueryExample/undeploy.bat b/examples/Chapter7/01-dynamicQueryExample/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter7/01-dynamicQueryExample/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter7/02-namedQueryExample/build.xml b/examples/Chapter7/02-namedQueryExample/build.xml new file mode 100644 index 0000000..30943c9 --- /dev/null +++ b/examples/Chapter7/02-namedQueryExample/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter7/02-namedQueryExample/deploy.bat b/examples/Chapter7/02-namedQueryExample/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter7/02-namedQueryExample/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter7/02-namedQueryExample/etc/persistence/META-INF/persistence.xml b/examples/Chapter7/02-namedQueryExample/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..bcb597e --- /dev/null +++ b/examples/Chapter7/02-namedQueryExample/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/namedQueryExample + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter7/02-namedQueryExample/etc/sql/db.sql b/examples/Chapter7/02-namedQueryExample/etc/sql/db.sql new file mode 100644 index 0000000..1d29472 --- /dev/null +++ b/examples/Chapter7/02-namedQueryExample/etc/sql/db.sql @@ -0,0 +1,57 @@ +DROP TABLE EMPLOYEE_PROJECT; +DROP TABLE PROJECT; +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE PROJECT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), STARTDATE DATE, SALARY BIGINT, + DEPARTMENT_ID INTEGER, MANAGER_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPARTMENT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID), + CONSTRAINT MANAGER_FK FOREIGN KEY (MANAGER_ID) REFERENCES EMPLOYEE (ID)); +CREATE TABLE EMPLOYEE_PROJECT (PROJECTS_ID INTEGER NOT NULL, EMPLOYEES_ID INTEGER NOT NULL, + CONSTRAINT PROJECTS_FK FOREIGN KEY (PROJECTS_ID) REFERENCES PROJECT (ID), + CONSTRAINT EMPLOYEES_FK FOREIGN KEY (EMPLOYEES_ID) REFERENCES EMPLOYEE (ID), + PRIMARY KEY (PROJECTS_ID, EMPLOYEES_ID)); + + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'CA13'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'CA19'); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (1, 'Joan', 59000, {d '2003-04-16'}, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (2, 'Sarah', 52000, {d '2002-04-26'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (3, 'John', 55000, {d '2001-01-01'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (4, 'Roberts', 53000, {d '2001-05-23'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (5, 'Peter', 50000, {d '2002-08-06'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (6, 'Frank', 51000, {d '2003-02-17'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (7, 'Scott', 60000, {d '2004-11-14'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (8, 'Sue', 62000, {d '2005-08-18'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (9, 'Stephanie', 54000, {d '2006-06-07'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (10, 'Jennifer', 55000, {d '1999-08-11'}, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (11, 'Marcus', 35000, {d '1995-07-22'}, NULL, NULL); + +INSERT INTO PROJECT (ID, NAME) VALUES (1, 'Design Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (2, 'Implement Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (3, 'Test Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (4, 'Release3'); + +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (1, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (4, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (7, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 3); \ No newline at end of file diff --git a/examples/Chapter7/02-namedQueryExample/etc/web/WEB-INF/web.xml b/examples/Chapter7/02-namedQueryExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter7/02-namedQueryExample/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServiceServlet + examples.servlet.EmployeeServiceServlet + + + + EmployeeServiceServlet + /EmployeeServiceServlet + + \ No newline at end of file diff --git a/examples/Chapter7/02-namedQueryExample/src/model/examples/model/Department.java b/examples/Chapter7/02-namedQueryExample/src/model/examples/model/Department.java new file mode 100644 index 0000000..5704081 --- /dev/null +++ b/examples/Chapter7/02-namedQueryExample/src/model/examples/model/Department.java @@ -0,0 +1,38 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="department") + private Collection employees; + + public Department() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter7/02-namedQueryExample/src/model/examples/model/Employee.java b/examples/Chapter7/02-namedQueryExample/src/model/examples/model/Employee.java new file mode 100644 index 0000000..15af75a --- /dev/null +++ b/examples/Chapter7/02-namedQueryExample/src/model/examples/model/Employee.java @@ -0,0 +1,94 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToMany; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.OneToMany; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@NamedQuery(name="findSalaryForNameAndDepartment", + query="SELECT e.salary " + + "FROM Employee e " + + "WHERE e.department.name = :deptName AND " + + " e.name = :empName") +@NamedQueries({ + @NamedQuery(name="Employee.findAll", + query="SELECT e FROM Employee e"), + @NamedQuery(name="Employee.findByPrimaryKey", + query="SELECT e FROM Employee e WHERE e.id = :id"), + @NamedQuery(name="Employee.findByName", + query="SELECT e FROM Employee e WHERE e.name = :name") +}) +public class Employee { + @Id + private int id; + private String name; + private long salary; + @Temporal(TemporalType.DATE) + private Date startDate; + + @ManyToOne + private Employee manager; + + @OneToMany(mappedBy="manager") + private Collection directs; + + @ManyToOne + private Department department; + + @ManyToMany + private Collection projects; + + public Employee() { + projects = new ArrayList(); + directs = new ArrayList(); + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public long getSalary() { + return salary; + } + + public Date getStartDate() { + return startDate; + } + + public Department getDepartment() { + return department; + } + + public Collection getDirects() { + return directs; + } + + public Employee getManager() { + return manager; + } + + public Collection getProjects() { + return projects; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary() + + ", dept: " + ((getDepartment() == null) ? null : getDepartment().getName()); + } +} diff --git a/examples/Chapter7/02-namedQueryExample/src/model/examples/model/Project.java b/examples/Chapter7/02-namedQueryExample/src/model/examples/model/Project.java new file mode 100644 index 0000000..8226327 --- /dev/null +++ b/examples/Chapter7/02-namedQueryExample/src/model/examples/model/Project.java @@ -0,0 +1,37 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToMany; + +@Entity +public class Project { + @Id + protected int id; + protected String name; + @ManyToMany(mappedBy="projects") + private Collection employees; + + public Project() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Project id: " + getId() + ", name: " + getName(); + } +} diff --git a/examples/Chapter7/02-namedQueryExample/src/model/examples/stateless/EmployeeService.java b/examples/Chapter7/02-namedQueryExample/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..6f018fd --- /dev/null +++ b/examples/Chapter7/02-namedQueryExample/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,12 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Collection findAllEmployees(); + public Employee findEmployeeByName(String name); + public Employee findEmployeeByPrimaryKey(int id); + public long findSalaryForNameAndDepartment(String deptName, String empName); +} diff --git a/examples/Chapter7/02-namedQueryExample/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter7/02-namedQueryExample/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..f85d9ce --- /dev/null +++ b/examples/Chapter7/02-namedQueryExample/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,52 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.NoResultException; +import javax.persistence.PersistenceContext; + +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="NamedQueries") + EntityManager em; + + public Employee findEmployeeByName(String name) { + try { + return (Employee) em.createNamedQuery("Employee.findByName") + .setParameter("name", name) + .getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public Employee findEmployeeByPrimaryKey(int id) { + try { + return (Employee) em.createNamedQuery("Employee.findByPrimaryKey") + .setParameter("id", id) + .getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public long findSalaryForNameAndDepartment(String deptName, String empName) { + try { + return (Long) em.createNamedQuery("findSalaryForNameAndDepartment") + .setParameter("deptName", deptName) + .setParameter("empName", empName) + .getSingleResult(); + } catch (NoResultException e) { + return 0; + } + } + + public Collection findAllEmployees() { + return (Collection) em.createNamedQuery("Employee.findAll") + .getResultList(); + } +} diff --git a/examples/Chapter7/02-namedQueryExample/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter7/02-namedQueryExample/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..dd1e5f1 --- /dev/null +++ b/examples/Chapter7/02-namedQueryExample/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,109 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.stateless.EmployeeService; + +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 7: Named Query Example"; + + private final String DESCRIPTION = + "This example demonstrates the basic use of a named query.
" + + "The example allows you to try the named queries shown in this " + + "section of the book."; + + + @EJB + private EmployeeService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action != null) { + if (action.equals("FindSalaryForNameAndDepartment")) { + long salary = service.findSalaryForNameAndDepartment( + request.getParameter("deptName"), + request.getParameter("empName")); + out.println("Found Salary: " + salary); + } else if (action.equals("FindByPrimaryKey")) { + Employee emp = service.findEmployeeByPrimaryKey( + parseInt(request.getParameter("id"))); + out.println("Found " + emp); + } else if (action.equals("FindByName")) { + Employee emp = service.findEmployeeByName( + request.getParameter("empName2")); + out.println("Found " + emp); + } + out.println("
"); + } + out.println("Find All Employees:
"); + for (Employee emp : service.findAllEmployees()) { + out.print(emp + "
"); + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println(""); + // form find + out.println("

Find Employee Salary

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
Department Name:(String)
"); + out.println("
"); + out.println("

Find By Primary Key

"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
"); + out.println("
"); + out.println("

Find By Name

"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Name:(String)
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter7/02-namedQueryExample/undeploy.bat b/examples/Chapter7/02-namedQueryExample/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter7/02-namedQueryExample/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter7/03-paramTypesExample/build.xml b/examples/Chapter7/03-paramTypesExample/build.xml new file mode 100644 index 0000000..be5b8ec --- /dev/null +++ b/examples/Chapter7/03-paramTypesExample/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter7/03-paramTypesExample/deploy.bat b/examples/Chapter7/03-paramTypesExample/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter7/03-paramTypesExample/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter7/03-paramTypesExample/etc/persistence/META-INF/persistence.xml b/examples/Chapter7/03-paramTypesExample/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..7f8e784 --- /dev/null +++ b/examples/Chapter7/03-paramTypesExample/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/paramTypesExample + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter7/03-paramTypesExample/etc/sql/db.sql b/examples/Chapter7/03-paramTypesExample/etc/sql/db.sql new file mode 100644 index 0000000..1d29472 --- /dev/null +++ b/examples/Chapter7/03-paramTypesExample/etc/sql/db.sql @@ -0,0 +1,57 @@ +DROP TABLE EMPLOYEE_PROJECT; +DROP TABLE PROJECT; +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE PROJECT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), STARTDATE DATE, SALARY BIGINT, + DEPARTMENT_ID INTEGER, MANAGER_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPARTMENT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID), + CONSTRAINT MANAGER_FK FOREIGN KEY (MANAGER_ID) REFERENCES EMPLOYEE (ID)); +CREATE TABLE EMPLOYEE_PROJECT (PROJECTS_ID INTEGER NOT NULL, EMPLOYEES_ID INTEGER NOT NULL, + CONSTRAINT PROJECTS_FK FOREIGN KEY (PROJECTS_ID) REFERENCES PROJECT (ID), + CONSTRAINT EMPLOYEES_FK FOREIGN KEY (EMPLOYEES_ID) REFERENCES EMPLOYEE (ID), + PRIMARY KEY (PROJECTS_ID, EMPLOYEES_ID)); + + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'CA13'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'CA19'); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (1, 'Joan', 59000, {d '2003-04-16'}, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (2, 'Sarah', 52000, {d '2002-04-26'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (3, 'John', 55000, {d '2001-01-01'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (4, 'Roberts', 53000, {d '2001-05-23'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (5, 'Peter', 50000, {d '2002-08-06'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (6, 'Frank', 51000, {d '2003-02-17'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (7, 'Scott', 60000, {d '2004-11-14'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (8, 'Sue', 62000, {d '2005-08-18'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (9, 'Stephanie', 54000, {d '2006-06-07'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (10, 'Jennifer', 55000, {d '1999-08-11'}, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (11, 'Marcus', 35000, {d '1995-07-22'}, NULL, NULL); + +INSERT INTO PROJECT (ID, NAME) VALUES (1, 'Design Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (2, 'Implement Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (3, 'Test Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (4, 'Release3'); + +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (1, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (4, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (7, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 3); \ No newline at end of file diff --git a/examples/Chapter7/03-paramTypesExample/etc/web/WEB-INF/web.xml b/examples/Chapter7/03-paramTypesExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter7/03-paramTypesExample/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServiceServlet + examples.servlet.EmployeeServiceServlet + + + + EmployeeServiceServlet + /EmployeeServiceServlet + + \ No newline at end of file diff --git a/examples/Chapter7/03-paramTypesExample/src/model/examples/model/Department.java b/examples/Chapter7/03-paramTypesExample/src/model/examples/model/Department.java new file mode 100644 index 0000000..9d1a2c2 --- /dev/null +++ b/examples/Chapter7/03-paramTypesExample/src/model/examples/model/Department.java @@ -0,0 +1,42 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="department") + private Collection employees; + + public Department() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter7/03-paramTypesExample/src/model/examples/model/Employee.java b/examples/Chapter7/03-paramTypesExample/src/model/examples/model/Employee.java new file mode 100644 index 0000000..43f8b74 --- /dev/null +++ b/examples/Chapter7/03-paramTypesExample/src/model/examples/model/Employee.java @@ -0,0 +1,98 @@ +package examples.model; + +import java.text.DateFormat; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToMany; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.OneToMany; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@NamedQueries({ + @NamedQuery(name="findEmployeesAboveSal", + query="SELECT e " + + "FROM Employee e " + + "WHERE e.department = :dept AND " + + " e.salary > :sal"), + @NamedQuery(name="findHighestPaidByDepartment", + query="SELECT e " + + "FROM Employee e " + + "WHERE e.department = :dept AND " + + " e.salary = (SELECT MAX(e2.salary) " + + " FROM Employee e2 " + + " WHERE e2.department = :dept)") +}) +public class Employee { + @Id + private int id; + private String name; + private long salary; + @Temporal(TemporalType.DATE) + private Date startDate; + + @ManyToOne + private Employee manager; + + @OneToMany(mappedBy="manager") + private Collection directs; + + @ManyToOne + private Department department; + + @ManyToMany + private Collection projects; + + public Employee() { + projects = new ArrayList(); + directs = new ArrayList(); + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public long getSalary() { + return salary; + } + + public Date getStartDate() { + return startDate; + } + + public Department getDepartment() { + return department; + } + + public Collection getDirects() { + return directs; + } + + public Employee getManager() { + return manager; + } + + public Collection getProjects() { + return projects; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary() + + ", startDate: " + DateFormat.getDateInstance().format(getStartDate()) + + ", dept: " + ((getDepartment() == null) ? null : + getDepartment().getId() + ":" + getDepartment().getName()); + } +} diff --git a/examples/Chapter7/03-paramTypesExample/src/model/examples/model/Project.java b/examples/Chapter7/03-paramTypesExample/src/model/examples/model/Project.java new file mode 100644 index 0000000..8226327 --- /dev/null +++ b/examples/Chapter7/03-paramTypesExample/src/model/examples/model/Project.java @@ -0,0 +1,37 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToMany; + +@Entity +public class Project { + @Id + protected int id; + protected String name; + @ManyToMany(mappedBy="projects") + private Collection employees; + + public Project() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Project id: " + getId() + ", name: " + getName(); + } +} diff --git a/examples/Chapter7/03-paramTypesExample/src/model/examples/stateless/EmployeeService.java b/examples/Chapter7/03-paramTypesExample/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..3574a34 --- /dev/null +++ b/examples/Chapter7/03-paramTypesExample/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,14 @@ +package examples.stateless; + +import java.util.Collection; +import java.util.Date; + +import examples.model.Department; +import examples.model.Employee; + +public interface EmployeeService { + public Collection findAllEmployees(); + public Collection findEmployeesAboveSal(Department dept, long minSal); + public Collection findEmployeesHiredDuringPeriod(Date start, Date end); + public Employee findHighestPaidByDepartment(Department dept); +} diff --git a/examples/Chapter7/03-paramTypesExample/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter7/03-paramTypesExample/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..47ef78d --- /dev/null +++ b/examples/Chapter7/03-paramTypesExample/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,51 @@ +package examples.stateless; + +import java.util.Collection; +import java.util.Date; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.NoResultException; +import javax.persistence.PersistenceContext; +import javax.persistence.TemporalType; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + EntityManager em; + + public Collection findEmployeesAboveSal(Department dept, long minSal) { + return (Collection) em.createNamedQuery("findEmployeesAboveSal") + .setParameter("dept", dept) + .setParameter("sal", minSal) + .getResultList(); + } + + public Collection findEmployeesHiredDuringPeriod(Date start, Date end) { + return (Collection) + em.createQuery("SELECT e " + + "FROM Employee e " + + "WHERE e.startDate BETWEEN :start AND :end") + .setParameter("start", start, TemporalType.DATE) + .setParameter("end", end, TemporalType.DATE) + .getResultList(); + } + + public Employee findHighestPaidByDepartment(Department dept) { + try { + return (Employee) em.createNamedQuery("findHighestPaidByDepartment") + .setParameter("dept", dept) + .getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public Collection findAllEmployees() { + return (Collection) em.createQuery( + "SELECT e FROM Employee e").getResultList(); + } +} diff --git a/examples/Chapter7/03-paramTypesExample/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter7/03-paramTypesExample/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..6491429 --- /dev/null +++ b/examples/Chapter7/03-paramTypesExample/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,145 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Calendar; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Department; +import examples.model.Employee; +import examples.stateless.EmployeeService; + +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 7: Parameter Types Example"; + + private final String DESCRIPTION = + "This example demonstrates the basic use of various parameter types.
" + + "The example allows you to execute the queries from this section of the book " + + "and see how types like primitives and temporals are used."; + + + @EJB + private EmployeeService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action != null) { + if (action.equals("FindEmployeesAboveSal")) { + Department d = new Department(); + d.setId(parseInt(request.getParameter("deptId"))); + Collection c = service.findEmployeesAboveSal( + d, parseLong(request.getParameter("minSal"))); + out.println("Found Employees:
"); + printCollection(c, out); + } else if (action.equals("FindEmployeesHiredDuringPeriod")) { + Calendar start = Calendar.getInstance(); + start.set(parseInt(request.getParameter("startYear")), + parseInt(request.getParameter("startMonth"))-1, // month is zero-based + parseInt(request.getParameter("startDate"))); + Calendar end = Calendar.getInstance(); + end.set(parseInt(request.getParameter("endYear")), + parseInt(request.getParameter("endMonth"))-1, // month is zero-based + parseInt(request.getParameter("endDate"))); + Collection c = service.findEmployeesHiredDuringPeriod( + start.getTime(), end.getTime()); + out.println("Found Employees:
"); + printCollection(c, out); + } else if (action.equals("FindHighestPaidByDepartment")) { + Department d = new Department(); + d.setId(parseInt(request.getParameter("deptId2"))); + Employee emp = service.findHighestPaidByDepartment(d); + out.println("Found " + emp); + } + out.println("
"); + } + out.println("Find All Employees:
"); + printCollection(service.findAllEmployees(), out); + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printCollection(Collection c, PrintWriter out) { + for (Object o : c) { + out.print(o + "
"); + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println(""); + // form find + out.println("

Find Employees above Salary

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Department Id:(int)
Min Salary:(long)
"); + out.println("
"); + out.println("

Find Employees hired during period

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Start Date:"); + out.println("-"); + out.println("-"); + out.println(" day-month-year (xx-xx-xxxx)"); + out.println("
End Date:"); + out.println("-"); + out.println("-"); + out.println(" day-month-year (xx-xx-xxxx)"); + out.println("
"); + out.println("
"); + out.println("

Find Highest paid by Department

"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Department Id:(int)
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter7/03-paramTypesExample/undeploy.bat b/examples/Chapter7/03-paramTypesExample/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter7/03-paramTypesExample/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter7/04-executingQueriesExample/build.xml b/examples/Chapter7/04-executingQueriesExample/build.xml new file mode 100644 index 0000000..7bce22f --- /dev/null +++ b/examples/Chapter7/04-executingQueriesExample/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter7/04-executingQueriesExample/deploy.bat b/examples/Chapter7/04-executingQueriesExample/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter7/04-executingQueriesExample/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter7/04-executingQueriesExample/etc/persistence/META-INF/persistence.xml b/examples/Chapter7/04-executingQueriesExample/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..aa6894e --- /dev/null +++ b/examples/Chapter7/04-executingQueriesExample/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/executingQueriesExample + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter7/04-executingQueriesExample/etc/sql/db.sql b/examples/Chapter7/04-executingQueriesExample/etc/sql/db.sql new file mode 100644 index 0000000..72a926d --- /dev/null +++ b/examples/Chapter7/04-executingQueriesExample/etc/sql/db.sql @@ -0,0 +1,57 @@ +DROP TABLE EMPLOYEE_PROJECT; +DROP TABLE PROJECT; +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE PROJECT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), STARTDATE DATE, SALARY BIGINT, + DEPARTMENT_ID INTEGER, MANAGER_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPARTMENT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID), + CONSTRAINT MANAGER_FK FOREIGN KEY (MANAGER_ID) REFERENCES EMPLOYEE (ID)); +CREATE TABLE EMPLOYEE_PROJECT (PROJECTS_ID INTEGER NOT NULL, EMPLOYEES_ID INTEGER NOT NULL, + CONSTRAINT PROJECTS_FK FOREIGN KEY (PROJECTS_ID) REFERENCES PROJECT (ID), + CONSTRAINT EMPLOYEES_FK FOREIGN KEY (EMPLOYEES_ID) REFERENCES EMPLOYEE (ID), + PRIMARY KEY (PROJECTS_ID, EMPLOYEES_ID)); + + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'CA13'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'CA19'); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (1, 'Joan', 59000, {d '2003-04-16'}, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (2, 'Sarah', 52000, {d '2002-04-26'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (3, 'John', 55000, {d '2001-01-01'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (4, 'Roberts', 53000, {d '2001-05-23'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (5, 'Peter', 50000, {d '2002-08-06'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (6, 'Frank', 51000, {d '2003-02-17'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (7, 'Scott', 60000, {d '2004-11-14'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (8, 'Sue', 62000, {d '2005-08-18'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (9, 'Stephanie', 54000, {d '2006-06-07'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (10, 'Jennifer', 55000, {d '1999-08-11'}, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (11, 'Marcus', 35000, {d '1995-07-22'}, NULL, NULL); + +INSERT INTO PROJECT (ID, NAME) VALUES (1, 'Design Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (2, 'Implement Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (3, 'Test Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (4, 'Release3'); + +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (1, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (4, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 4); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (7, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 4); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 4); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 3); \ No newline at end of file diff --git a/examples/Chapter7/04-executingQueriesExample/etc/web/WEB-INF/web.xml b/examples/Chapter7/04-executingQueriesExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter7/04-executingQueriesExample/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServiceServlet + examples.servlet.EmployeeServiceServlet + + + + EmployeeServiceServlet + /EmployeeServiceServlet + + \ No newline at end of file diff --git a/examples/Chapter7/04-executingQueriesExample/src/model/examples/model/Department.java b/examples/Chapter7/04-executingQueriesExample/src/model/examples/model/Department.java new file mode 100644 index 0000000..9d1a2c2 --- /dev/null +++ b/examples/Chapter7/04-executingQueriesExample/src/model/examples/model/Department.java @@ -0,0 +1,42 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="department") + private Collection employees; + + public Department() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter7/04-executingQueriesExample/src/model/examples/model/Employee.java b/examples/Chapter7/04-executingQueriesExample/src/model/examples/model/Employee.java new file mode 100644 index 0000000..8a6d57b --- /dev/null +++ b/examples/Chapter7/04-executingQueriesExample/src/model/examples/model/Employee.java @@ -0,0 +1,82 @@ +package examples.model; + +import java.text.DateFormat; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToMany; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + @Temporal(TemporalType.DATE) + private Date startDate; + + @ManyToOne + private Employee manager; + + @OneToMany(mappedBy="manager") + private Collection directs; + + @ManyToOne + private Department department; + + @ManyToMany + private Collection projects; + + public Employee() { + projects = new ArrayList(); + directs = new ArrayList(); + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public long getSalary() { + return salary; + } + + public Date getStartDate() { + return startDate; + } + + public Department getDepartment() { + return department; + } + + public Collection getDirects() { + return directs; + } + + public Employee getManager() { + return manager; + } + + public Collection getProjects() { + return projects; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary() + + ", startDate: " + DateFormat.getDateInstance().format(getStartDate()) + + ", dept: " + ((getDepartment() == null) ? null : + getDepartment().getId() + ":" + getDepartment().getName()); + } +} diff --git a/examples/Chapter7/04-executingQueriesExample/src/model/examples/model/Project.java b/examples/Chapter7/04-executingQueriesExample/src/model/examples/model/Project.java new file mode 100644 index 0000000..8226327 --- /dev/null +++ b/examples/Chapter7/04-executingQueriesExample/src/model/examples/model/Project.java @@ -0,0 +1,37 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToMany; + +@Entity +public class Project { + @Id + protected int id; + protected String name; + @ManyToMany(mappedBy="projects") + private Collection employees; + + public Project() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Project id: " + getId() + ", name: " + getName(); + } +} diff --git a/examples/Chapter7/04-executingQueriesExample/src/model/examples/stateful/ProjectManager.java b/examples/Chapter7/04-executingQueriesExample/src/model/examples/stateful/ProjectManager.java new file mode 100644 index 0000000..e2f883e --- /dev/null +++ b/examples/Chapter7/04-executingQueriesExample/src/model/examples/stateful/ProjectManager.java @@ -0,0 +1,14 @@ +package examples.stateful; + +import java.util.Collection; +import java.util.List; + +import examples.model.Employee; +import examples.model.Project; + +public interface ProjectManager { + public List findEmployeesWithoutProjects(); + public List findProjectEmployees(String projectName); + public Collection findAllEmployees(); + public Collection findAllProjects(); +} diff --git a/examples/Chapter7/04-executingQueriesExample/src/model/examples/stateful/ProjectManagerBean.java b/examples/Chapter7/04-executingQueriesExample/src/model/examples/stateful/ProjectManagerBean.java new file mode 100644 index 0000000..597ca3c --- /dev/null +++ b/examples/Chapter7/04-executingQueriesExample/src/model/examples/stateful/ProjectManagerBean.java @@ -0,0 +1,52 @@ +package examples.stateful; + +import static javax.persistence.PersistenceContextType.EXTENDED; + +import java.util.Collection; +import java.util.List; + +import javax.annotation.PostConstruct; +import javax.ejb.Stateful; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Employee; +import examples.model.Project; + +@Stateful +public class ProjectManagerBean implements ProjectManager { + @PersistenceContext(unitName="EmployeeService"/*, type=EXTENDED*/) + EntityManager em; + + Query unassignedQuery; + + @PostConstruct + public void init() { + unassignedQuery = + em.createQuery("SELECT e " + + "FROM Employee e " + + "WHERE e.projects IS EMPTY"); + } + + public List findEmployeesWithoutProjects() { + return unassignedQuery.getResultList(); + } + + public List findProjectEmployees(String projectName) { + return em.createQuery("SELECT e " + + "FROM Project p JOIN p.employees e " + + "WHERE p.name = :project " + + "ORDER BY e.name") + .setParameter("project", projectName) + .getResultList(); + } + + public Collection findAllEmployees() { + return em.createQuery("SELECT e FROM Employee e").getResultList(); + } + + public Collection findAllProjects() { + return em.createQuery("SELECT p FROM Project p").getResultList(); + } +} diff --git a/examples/Chapter7/04-executingQueriesExample/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter7/04-executingQueriesExample/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..67ae627 --- /dev/null +++ b/examples/Chapter7/04-executingQueriesExample/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,104 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Iterator; +import java.util.List; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.model.Project; +import examples.stateful.ProjectManager; + +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 7: Executing Queries Example"; + + private final String DESCRIPTION = + "This example demonstrates a couple of ways to execute queries."; + + @EJB // note: it's dangerous to inject a sfsb into servlet since servlets are typically multi-threaded + private ProjectManager service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action != null) { + if (action.equals("DisplayProjectEmployees")) { + List result = service.findProjectEmployees( + request.getParameter("projName")); + out.println("Found Employees:
"); + printEmployees(result, out); + } else if (action.equals("FindEmployeesWithoutProjects")) { + List result = service.findEmployeesWithoutProjects(); + out.println("Found Employees:
"); + for (Object emp : result) { + out.print(emp + "
"); + } + } + out.println("
"); + } + out.println("All Employees:
"); + for (Employee emp : service.findAllEmployees()) { + out.print(emp + "
"); + } + out.println("
All Projects:
"); + for (Project proj : service.findAllProjects()) { + out.print(proj + "
"); + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private void printEmployees(List result, PrintWriter out) { + int count = 0; + for (Iterator i = result.iterator(); i.hasNext();) { + Employee e = (Employee) i.next(); + out.print(++count + ": " + e.getName() + ", " + + e.getDepartment().getName() + "
"); + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println(""); + // form find + out.println("

Find Employees for Project (ordered by name)

"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Project Name:(String)
"); + out.println("
"); + out.println("

Find Employees without Projects

"); + out.println(""); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter7/04-executingQueriesExample/undeploy.bat b/examples/Chapter7/04-executingQueriesExample/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter7/04-executingQueriesExample/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter7/05-queryResultsExample/build.xml b/examples/Chapter7/05-queryResultsExample/build.xml new file mode 100644 index 0000000..f1fd9d7 --- /dev/null +++ b/examples/Chapter7/05-queryResultsExample/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter7/05-queryResultsExample/deploy.bat b/examples/Chapter7/05-queryResultsExample/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter7/05-queryResultsExample/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter7/05-queryResultsExample/etc/persistence/META-INF/persistence.xml b/examples/Chapter7/05-queryResultsExample/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..e7cd79f --- /dev/null +++ b/examples/Chapter7/05-queryResultsExample/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/queryResultsExample + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter7/05-queryResultsExample/etc/sql/db.sql b/examples/Chapter7/05-queryResultsExample/etc/sql/db.sql new file mode 100644 index 0000000..1d29472 --- /dev/null +++ b/examples/Chapter7/05-queryResultsExample/etc/sql/db.sql @@ -0,0 +1,57 @@ +DROP TABLE EMPLOYEE_PROJECT; +DROP TABLE PROJECT; +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE PROJECT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), STARTDATE DATE, SALARY BIGINT, + DEPARTMENT_ID INTEGER, MANAGER_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPARTMENT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID), + CONSTRAINT MANAGER_FK FOREIGN KEY (MANAGER_ID) REFERENCES EMPLOYEE (ID)); +CREATE TABLE EMPLOYEE_PROJECT (PROJECTS_ID INTEGER NOT NULL, EMPLOYEES_ID INTEGER NOT NULL, + CONSTRAINT PROJECTS_FK FOREIGN KEY (PROJECTS_ID) REFERENCES PROJECT (ID), + CONSTRAINT EMPLOYEES_FK FOREIGN KEY (EMPLOYEES_ID) REFERENCES EMPLOYEE (ID), + PRIMARY KEY (PROJECTS_ID, EMPLOYEES_ID)); + + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'CA13'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'CA19'); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (1, 'Joan', 59000, {d '2003-04-16'}, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (2, 'Sarah', 52000, {d '2002-04-26'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (3, 'John', 55000, {d '2001-01-01'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (4, 'Roberts', 53000, {d '2001-05-23'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (5, 'Peter', 50000, {d '2002-08-06'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (6, 'Frank', 51000, {d '2003-02-17'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (7, 'Scott', 60000, {d '2004-11-14'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (8, 'Sue', 62000, {d '2005-08-18'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (9, 'Stephanie', 54000, {d '2006-06-07'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (10, 'Jennifer', 55000, {d '1999-08-11'}, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (11, 'Marcus', 35000, {d '1995-07-22'}, NULL, NULL); + +INSERT INTO PROJECT (ID, NAME) VALUES (1, 'Design Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (2, 'Implement Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (3, 'Test Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (4, 'Release3'); + +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (1, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (4, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (7, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 3); \ No newline at end of file diff --git a/examples/Chapter7/05-queryResultsExample/etc/web/WEB-INF/web.xml b/examples/Chapter7/05-queryResultsExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter7/05-queryResultsExample/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServiceServlet + examples.servlet.EmployeeServiceServlet + + + + EmployeeServiceServlet + /EmployeeServiceServlet + + \ No newline at end of file diff --git a/examples/Chapter7/05-queryResultsExample/src/model/examples/EmpMenu.java b/examples/Chapter7/05-queryResultsExample/src/model/examples/EmpMenu.java new file mode 100644 index 0000000..8ac9700 --- /dev/null +++ b/examples/Chapter7/05-queryResultsExample/src/model/examples/EmpMenu.java @@ -0,0 +1,20 @@ +package examples; + +public class EmpMenu { + private String employeeName; + private String departmentName; + + public EmpMenu(String employeeName, String departmentName) { + this.employeeName = employeeName; + this.departmentName = departmentName; + } + + public String getEmployeeName() { + return employeeName; + } + + public String getDepartmentName() { + return departmentName; + } +} + diff --git a/examples/Chapter7/05-queryResultsExample/src/model/examples/model/Department.java b/examples/Chapter7/05-queryResultsExample/src/model/examples/model/Department.java new file mode 100644 index 0000000..9d1a2c2 --- /dev/null +++ b/examples/Chapter7/05-queryResultsExample/src/model/examples/model/Department.java @@ -0,0 +1,42 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="department") + private Collection employees; + + public Department() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter7/05-queryResultsExample/src/model/examples/model/Employee.java b/examples/Chapter7/05-queryResultsExample/src/model/examples/model/Employee.java new file mode 100644 index 0000000..8a6d57b --- /dev/null +++ b/examples/Chapter7/05-queryResultsExample/src/model/examples/model/Employee.java @@ -0,0 +1,82 @@ +package examples.model; + +import java.text.DateFormat; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToMany; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + @Temporal(TemporalType.DATE) + private Date startDate; + + @ManyToOne + private Employee manager; + + @OneToMany(mappedBy="manager") + private Collection directs; + + @ManyToOne + private Department department; + + @ManyToMany + private Collection projects; + + public Employee() { + projects = new ArrayList(); + directs = new ArrayList(); + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public long getSalary() { + return salary; + } + + public Date getStartDate() { + return startDate; + } + + public Department getDepartment() { + return department; + } + + public Collection getDirects() { + return directs; + } + + public Employee getManager() { + return manager; + } + + public Collection getProjects() { + return projects; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary() + + ", startDate: " + DateFormat.getDateInstance().format(getStartDate()) + + ", dept: " + ((getDepartment() == null) ? null : + getDepartment().getId() + ":" + getDepartment().getName()); + } +} diff --git a/examples/Chapter7/05-queryResultsExample/src/model/examples/model/Project.java b/examples/Chapter7/05-queryResultsExample/src/model/examples/model/Project.java new file mode 100644 index 0000000..8226327 --- /dev/null +++ b/examples/Chapter7/05-queryResultsExample/src/model/examples/model/Project.java @@ -0,0 +1,37 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToMany; + +@Entity +public class Project { + @Id + protected int id; + protected String name; + @ManyToMany(mappedBy="projects") + private Collection employees; + + public Project() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Project id: " + getId() + ", name: " + getName(); + } +} diff --git a/examples/Chapter7/05-queryResultsExample/src/model/examples/stateless/QueryService.java b/examples/Chapter7/05-queryResultsExample/src/model/examples/stateless/QueryService.java new file mode 100644 index 0000000..86002db --- /dev/null +++ b/examples/Chapter7/05-queryResultsExample/src/model/examples/stateless/QueryService.java @@ -0,0 +1,15 @@ +package examples.stateless; + +import java.util.Collection; +import java.util.List; + +import examples.model.Employee; +import examples.model.Project; + +public interface QueryService { + public List findAllDepartmentsDetached(); + public List findProjectEmployees(String projectName); + public List findProjectEmployeesWithConstructor(String projectName); + public Collection findAllEmployees(); + public Collection findAllProjects(); +} diff --git a/examples/Chapter7/05-queryResultsExample/src/model/examples/stateless/QueryServiceBean.java b/examples/Chapter7/05-queryResultsExample/src/model/examples/stateless/QueryServiceBean.java new file mode 100644 index 0000000..5d5c077 --- /dev/null +++ b/examples/Chapter7/05-queryResultsExample/src/model/examples/stateless/QueryServiceBean.java @@ -0,0 +1,52 @@ +package examples.stateless; + +import static javax.ejb.TransactionAttributeType.NOT_SUPPORTED; + +import java.util.Collection; +import java.util.List; + +import javax.ejb.Stateless; +import javax.ejb.TransactionAttribute; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Employee; +import examples.model.Project; + +@Stateless +public class QueryServiceBean implements QueryService { + @PersistenceContext(unitName="EmployeeService") + EntityManager em; + + @TransactionAttribute(NOT_SUPPORTED) + public List findAllDepartmentsDetached() { + return em.createQuery("SELECT d FROM Department d") + .getResultList(); + } + + public List findProjectEmployees(String projectName) { + return em.createQuery("SELECT e.name, e.department.name " + + "FROM Project p JOIN p.employees e " + + "WHERE p.name = :project " + + "ORDER BY e.name") + .setParameter("project", projectName) + .getResultList(); + } + + public List findProjectEmployeesWithConstructor(String projectName) { + return em.createQuery("SELECT NEW examples.EmpMenu(e.name, e.department.name) " + + "FROM Project p JOIN p.employees e " + + "WHERE p.name = :project " + + "ORDER BY e.name") + .setParameter("project", projectName) + .getResultList(); + } + + public Collection findAllEmployees() { + return em.createQuery("SELECT e FROM Employee e").getResultList(); + } + + public Collection findAllProjects() { + return em.createQuery("SELECT p FROM Project p").getResultList(); + } +} diff --git a/examples/Chapter7/05-queryResultsExample/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter7/05-queryResultsExample/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..9963e56 --- /dev/null +++ b/examples/Chapter7/05-queryResultsExample/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,127 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Iterator; +import java.util.List; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.EmpMenu; +import examples.model.Employee; +import examples.model.Project; +import examples.stateless.QueryService; + +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 7: Query Results Example"; + + private final String DESCRIPTION = + "This example demonstrates a couple of ways to get query results.
" + + "It shows execution of a query outside of a transaction and how to get and " + + "deal with various result types."; + + + @EJB + private QueryService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action != null) { + if (action.equals("FindDepartmentsDetached")) { + List result = service.findAllDepartmentsDetached(); + out.println("Found Departments:
"); + for (Object dept : result) { + out.print(dept + "
"); + } + } else if (action.equals("DisplayProjectEmployees")) { + List result = service.findProjectEmployees( + request.getParameter("projName")); + out.println("Found Employees:
"); + printEmployees(result, out); + } else if (action.equals("DisplayProjectEmployeesUsingConstructor")) { + List result = service.findProjectEmployeesWithConstructor( + request.getParameter("projName2")); + out.println("Found Employees:
"); + printEmployees2(result, out); + } + out.println("
"); + } + out.println("All Employees:
"); + for (Employee emp : service.findAllEmployees()) { + out.print(emp + "
"); + } + out.println("
All Projects:
"); + for (Project proj : service.findAllProjects()) { + out.print(proj + "
"); + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private void printEmployees(List result, PrintWriter out) { + int count = 0; + for (Iterator i = result.iterator(); i.hasNext();) { + Object[] values = (Object[]) i.next(); + out.print(++count + ": " + values[0] + ", " + values[1] + "
"); + } + } + + private void printEmployees2(List result, PrintWriter out) { + int count = 0; + for (Iterator i = result.iterator(); i.hasNext();) { + EmpMenu menu = (EmpMenu) i.next(); + out.print(++count + ": " + menu.getEmployeeName() + ", " + + menu.getDepartmentName() + "
"); + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println(""); + // form find + out.println("

Find Departments Detached (query outside a transaction)

"); + out.println(""); + out.println(""); + out.println("
"); + out.println("
"); + out.println("

Find Employees for Project (multiple result types)

"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Project Name:(String)
"); + out.println("
"); + out.println("

Find Employees for Project Using Constructor

"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Project Name:(String)
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter7/05-queryResultsExample/undeploy.bat b/examples/Chapter7/05-queryResultsExample/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter7/05-queryResultsExample/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter7/06-queryPagingExample/build.xml b/examples/Chapter7/06-queryPagingExample/build.xml new file mode 100644 index 0000000..79d099b --- /dev/null +++ b/examples/Chapter7/06-queryPagingExample/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter7/06-queryPagingExample/deploy.bat b/examples/Chapter7/06-queryPagingExample/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter7/06-queryPagingExample/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter7/06-queryPagingExample/etc/persistence/META-INF/persistence.xml b/examples/Chapter7/06-queryPagingExample/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..fa87c8c --- /dev/null +++ b/examples/Chapter7/06-queryPagingExample/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/queryPagingDB + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter7/06-queryPagingExample/etc/sql/db.sql b/examples/Chapter7/06-queryPagingExample/etc/sql/db.sql new file mode 100644 index 0000000..1d29472 --- /dev/null +++ b/examples/Chapter7/06-queryPagingExample/etc/sql/db.sql @@ -0,0 +1,57 @@ +DROP TABLE EMPLOYEE_PROJECT; +DROP TABLE PROJECT; +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE PROJECT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), STARTDATE DATE, SALARY BIGINT, + DEPARTMENT_ID INTEGER, MANAGER_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPARTMENT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID), + CONSTRAINT MANAGER_FK FOREIGN KEY (MANAGER_ID) REFERENCES EMPLOYEE (ID)); +CREATE TABLE EMPLOYEE_PROJECT (PROJECTS_ID INTEGER NOT NULL, EMPLOYEES_ID INTEGER NOT NULL, + CONSTRAINT PROJECTS_FK FOREIGN KEY (PROJECTS_ID) REFERENCES PROJECT (ID), + CONSTRAINT EMPLOYEES_FK FOREIGN KEY (EMPLOYEES_ID) REFERENCES EMPLOYEE (ID), + PRIMARY KEY (PROJECTS_ID, EMPLOYEES_ID)); + + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'CA13'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'CA19'); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (1, 'Joan', 59000, {d '2003-04-16'}, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (2, 'Sarah', 52000, {d '2002-04-26'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (3, 'John', 55000, {d '2001-01-01'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (4, 'Roberts', 53000, {d '2001-05-23'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (5, 'Peter', 50000, {d '2002-08-06'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (6, 'Frank', 51000, {d '2003-02-17'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (7, 'Scott', 60000, {d '2004-11-14'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (8, 'Sue', 62000, {d '2005-08-18'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (9, 'Stephanie', 54000, {d '2006-06-07'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (10, 'Jennifer', 55000, {d '1999-08-11'}, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (11, 'Marcus', 35000, {d '1995-07-22'}, NULL, NULL); + +INSERT INTO PROJECT (ID, NAME) VALUES (1, 'Design Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (2, 'Implement Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (3, 'Test Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (4, 'Release3'); + +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (1, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (4, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (7, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 3); \ No newline at end of file diff --git a/examples/Chapter7/06-queryPagingExample/etc/web/WEB-INF/web.xml b/examples/Chapter7/06-queryPagingExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..0c884a7 --- /dev/null +++ b/examples/Chapter7/06-queryPagingExample/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeePagingServlet + examples.servlet.EmployeePagingServlet + + + + EmployeePagingServlet + /EmployeePagingServlet + + \ No newline at end of file diff --git a/examples/Chapter7/06-queryPagingExample/src/model/examples/model/Department.java b/examples/Chapter7/06-queryPagingExample/src/model/examples/model/Department.java new file mode 100644 index 0000000..9d1a2c2 --- /dev/null +++ b/examples/Chapter7/06-queryPagingExample/src/model/examples/model/Department.java @@ -0,0 +1,42 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="department") + private Collection employees; + + public Department() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter7/06-queryPagingExample/src/model/examples/model/Employee.java b/examples/Chapter7/06-queryPagingExample/src/model/examples/model/Employee.java new file mode 100644 index 0000000..6a7f784 --- /dev/null +++ b/examples/Chapter7/06-queryPagingExample/src/model/examples/model/Employee.java @@ -0,0 +1,90 @@ +package examples.model; + +import java.text.DateFormat; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToMany; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.OneToMany; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@NamedQueries({ + @NamedQuery(name="countEmployees", + query="SELECT COUNT(e) FROM Employee e"), + @NamedQuery(name="findAllEmployees", + query="SELECT e FROM Employee e") +}) +public class Employee { + @Id + private int id; + private String name; + private long salary; + @Temporal(TemporalType.DATE) + private Date startDate; + + @ManyToOne + private Employee manager; + + @OneToMany(mappedBy="manager") + private Collection directs; + + @ManyToOne + private Department department; + + @ManyToMany + private Collection projects; + + public Employee() { + projects = new ArrayList(); + directs = new ArrayList(); + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public long getSalary() { + return salary; + } + + public Date getStartDate() { + return startDate; + } + + public Department getDepartment() { + return department; + } + + public Collection getDirects() { + return directs; + } + + public Employee getManager() { + return manager; + } + + public Collection getProjects() { + return projects; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary() + + ", startDate: " + DateFormat.getDateInstance().format(getStartDate()) + + ", dept: " + ((getDepartment() == null) ? null : + getDepartment().getId() + ":" + getDepartment().getName()); + } +} diff --git a/examples/Chapter7/06-queryPagingExample/src/model/examples/model/Project.java b/examples/Chapter7/06-queryPagingExample/src/model/examples/model/Project.java new file mode 100644 index 0000000..8226327 --- /dev/null +++ b/examples/Chapter7/06-queryPagingExample/src/model/examples/model/Project.java @@ -0,0 +1,37 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToMany; + +@Entity +public class Project { + @Id + protected int id; + protected String name; + @ManyToMany(mappedBy="projects") + private Collection employees; + + public Project() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Project id: " + getId() + ", name: " + getName(); + } +} diff --git a/examples/Chapter7/06-queryPagingExample/src/model/examples/stateful/ResultPager.java b/examples/Chapter7/06-queryPagingExample/src/model/examples/stateful/ResultPager.java new file mode 100644 index 0000000..5c29b6e --- /dev/null +++ b/examples/Chapter7/06-queryPagingExample/src/model/examples/stateful/ResultPager.java @@ -0,0 +1,13 @@ +package examples.stateful; + +import java.util.List; + +public interface ResultPager { + public void init(int pageSize, String countQueryName, String reportQueryName); + public List getCurrentResults(); + public void next(); + public void previous(); + public void finished(); + public int getCurrentPage(); + public int getMaxPages(); +} diff --git a/examples/Chapter7/06-queryPagingExample/src/model/examples/stateful/ResultPagerBean.java b/examples/Chapter7/06-queryPagingExample/src/model/examples/stateful/ResultPagerBean.java new file mode 100644 index 0000000..25f882c --- /dev/null +++ b/examples/Chapter7/06-queryPagingExample/src/model/examples/stateful/ResultPagerBean.java @@ -0,0 +1,66 @@ +package examples.stateful; + +import java.util.List; + +import javax.ejb.Remove; +import javax.ejb.Stateful; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +@Stateful +public class ResultPagerBean implements ResultPager { + @PersistenceContext(unitName="QueryPaging") + private EntityManager em; + + private String reportQueryName; + private int currentPage; + private int maxResults; + private int pageSize; + + public int getPageSize() { + return pageSize; + } + + public int getMaxPages() { + return maxResults / pageSize; + } + + public void init(int pageSize, String countQueryName, + String reportQueryName) { + this.pageSize = pageSize; + this.reportQueryName = reportQueryName; + maxResults = ((Long) em.createNamedQuery(countQueryName) + .getSingleResult()).intValue(); + currentPage = 0; + } + + public List getCurrentResults() { + return em.createNamedQuery(reportQueryName) + .setFirstResult(currentPage * pageSize) + .setMaxResults(pageSize) + .getResultList(); + } + + public void next() { + currentPage++; + } + + public void previous() { + currentPage--; + if (currentPage < 0) { + currentPage = 0; + } + } + + public int getCurrentPage() { + return currentPage; + } + + public void setCurrentPage(int currentPage) { + this.currentPage = currentPage; + } + + @Remove + public void finished() { + } +} diff --git a/examples/Chapter7/06-queryPagingExample/src/servlet/examples/servlet/EmployeePagingServlet.java b/examples/Chapter7/06-queryPagingExample/src/servlet/examples/servlet/EmployeePagingServlet.java new file mode 100644 index 0000000..d6edd9d --- /dev/null +++ b/examples/Chapter7/06-queryPagingExample/src/servlet/examples/servlet/EmployeePagingServlet.java @@ -0,0 +1,108 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.ejb.EJB; +import javax.naming.InitialContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateful.ResultPager; + +@EJB(name="ResultPager", beanInterface=ResultPager.class) +public class EmployeePagingServlet extends HttpServlet { + + private final String TITLE = + "Chapter 7: Query Paging Example"; + + private final String DESCRIPTION = + "This example demonstrates the use of query paging.
" + + "The example allows you to browse over a set employees " + + "by using the setFirstResult() and setMaxResults() api. "; + + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + out.println(""); + } else { + ResultPager pager = (ResultPager) request.getSession().getAttribute("pager"); + if (action.equals("FindAll")) { + try { + pager = (ResultPager) + new InitialContext().lookup("java:comp/env/ResultPager"); + request.getSession().setAttribute("pager", pager); + } catch (Exception e) { + throw new ServletException(e); + } + pager.init(3, "countEmployees", "findAllEmployees"); + printCurrentPage(pager, out); + } else if (action.equals("Next")) { + pager.next(); + printCurrentPage(pager, out); + } else if (action.equals("Previous")) { + pager.previous(); + printCurrentPage(pager, out); + } else if (action.equals("Finished")) { + pager.finished(); + request.getSession().removeAttribute("pager"); + out.println(""); + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private void printCurrentPage(ResultPager pager, PrintWriter out) { + out.println("Employees:
"); + for (Object o : pager.getCurrentResults()) { + out.print(o + "
"); + } + + out.println("
"); + out.println("Page " + (pager.getCurrentPage()+1) + " of " + pager.getMaxPages()); + out.println("
"); + out.print(""); + + out.print(""); + out.println(""); + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println(""); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter7/06-queryPagingExample/undeploy.bat b/examples/Chapter7/06-queryPagingExample/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter7/06-queryPagingExample/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter7/07-messageBoardExample/build.xml b/examples/Chapter7/07-messageBoardExample/build.xml new file mode 100644 index 0000000..fd5c242 --- /dev/null +++ b/examples/Chapter7/07-messageBoardExample/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter7/07-messageBoardExample/deploy.bat b/examples/Chapter7/07-messageBoardExample/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter7/07-messageBoardExample/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter7/07-messageBoardExample/etc/persistence/META-INF/persistence.xml b/examples/Chapter7/07-messageBoardExample/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..97329c7 --- /dev/null +++ b/examples/Chapter7/07-messageBoardExample/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/messageBoardExample + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter7/07-messageBoardExample/etc/sql/db.sql b/examples/Chapter7/07-messageBoardExample/etc/sql/db.sql new file mode 100644 index 0000000..97e4f91 --- /dev/null +++ b/examples/Chapter7/07-messageBoardExample/etc/sql/db.sql @@ -0,0 +1,33 @@ +DROP TABLE MESSAGE; +DROP TABLE CONVERSATION; + +CREATE TABLE CONVERSATION (ID INTEGER NOT NULL, STATUS VARCHAR(10), PRIMARY KEY (ID)); +CREATE TABLE MESSAGE (ID INTEGER NOT NULL, MESSAGE VARCHAR(255), POSTINGDATE DATE, CONVERSATION_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT CONVERSATION_FK FOREIGN KEY (CONVERSATION_ID) REFERENCES CONVERSATION(ID)); + + +INSERT INTO CONVERSATION (ID, STATUS) VALUES (1, 'ACTIVE'); +INSERT INTO MESSAGE (ID, MESSAGE, POSTINGDATE, CONVERSATION_ID) VALUES (1, 'Hey', {d '2006-06-26'}, 1); +INSERT INTO MESSAGE (ID, MESSAGE, POSTINGDATE, CONVERSATION_ID) VALUES (2, 'How are you?', {d '2006-06-26'}, 1); +INSERT INTO MESSAGE (ID, MESSAGE, POSTINGDATE, CONVERSATION_ID) VALUES (3, 'Great!', {d '2006-06-26'}, 1); + +INSERT INTO CONVERSATION (ID, STATUS) VALUES (2, 'ACTIVE'); +INSERT INTO MESSAGE (ID, MESSAGE, POSTINGDATE, CONVERSATION_ID) VALUES (4, 'Have you finished yet?', {d '2006-06-20'}, 2); +INSERT INTO MESSAGE (ID, MESSAGE, POSTINGDATE, CONVERSATION_ID) VALUES (5, 'no.', {d '2006-06-20'}, 2); + +INSERT INTO CONVERSATION (ID, STATUS) VALUES (3, 'ACTIVE'); +INSERT INTO MESSAGE (ID, MESSAGE, POSTINGDATE, CONVERSATION_ID) VALUES (6, 'When is your birthday?', {d '2006-06-13'}, 3); +INSERT INTO MESSAGE (ID, MESSAGE, POSTINGDATE, CONVERSATION_ID) VALUES (7, 'Next week.', {d '2006-06-13'}, 3); +INSERT INTO MESSAGE (ID, MESSAGE, POSTINGDATE, CONVERSATION_ID) VALUES (8, 'How old will you be?', {d '2006-06-13'}, 3); +INSERT INTO MESSAGE (ID, MESSAGE, POSTINGDATE, CONVERSATION_ID) VALUES (9, '30', {d '2006-06-13'}, 3); + +INSERT INTO CONVERSATION (ID, STATUS) VALUES (4, 'ACTIVE'); +INSERT INTO MESSAGE (ID, MESSAGE, POSTINGDATE, CONVERSATION_ID) VALUES (10, 'Do you know a good query language?', {d '2006-05-22'}, 4); +INSERT INTO MESSAGE (ID, MESSAGE, POSTINGDATE, CONVERSATION_ID) VALUES (11, 'Sure. Try JPQL', {d '2006-05-22'}, 4); +INSERT INTO MESSAGE (ID, MESSAGE, POSTINGDATE, CONVERSATION_ID) VALUES (12, 'Thanks!', {d '2006-05-22'}, 4); + +INSERT INTO CONVERSATION (ID, STATUS) VALUES (5, 'ACTIVE'); +INSERT INTO MESSAGE (ID, MESSAGE, POSTINGDATE, CONVERSATION_ID) VALUES (13, 'Does EJB 3.0 support inheritance?', {d '2006-05-21'}, 5); +INSERT INTO MESSAGE (ID, MESSAGE, POSTINGDATE, CONVERSATION_ID) VALUES (14, 'Yes. See @Inheritance', {d '2006-05-21'}, 5); +INSERT INTO MESSAGE (ID, MESSAGE, POSTINGDATE, CONVERSATION_ID) VALUES (15, 'Ok. What about polymorphism in the queries?', {d '2006-05-21'}, 5); +INSERT INTO MESSAGE (ID, MESSAGE, POSTINGDATE, CONVERSATION_ID) VALUES (16, 'It supports that too!', {d '2006-05-21'}, 5); diff --git a/examples/Chapter7/07-messageBoardExample/etc/web/WEB-INF/web.xml b/examples/Chapter7/07-messageBoardExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..b6ebd37 --- /dev/null +++ b/examples/Chapter7/07-messageBoardExample/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + MessageBoardServlet + examples.servlet.MessageBoardServlet + + + + MessageBoardServlet + /MessageBoardServlet + + \ No newline at end of file diff --git a/examples/Chapter7/07-messageBoardExample/src/model/examples/model/Conversation.java b/examples/Chapter7/07-messageBoardExample/src/model/examples/model/Conversation.java new file mode 100644 index 0000000..f883074 --- /dev/null +++ b/examples/Chapter7/07-messageBoardExample/src/model/examples/model/Conversation.java @@ -0,0 +1,70 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.OneToMany; + +@Entity +@NamedQueries({ + @NamedQuery(name="findActiveConversations", + query="SELECT c " + + "FROM Conversation c " + + "WHERE c.status = 'ACTIVE'"), + @NamedQuery(name="findLastMessageDate", + query="SELECT MAX(m.postingDate) " + + "FROM Conversation c JOIN c.messages m " + + "WHERE c = :conversation") +}) + +public class Conversation { + public final static String ACTIVE = "ACTIVE"; + public final static String INACTIVE = "INACTIVE"; + + @Id + private int id; + private String status; + + @OneToMany(mappedBy="conversation") + private Collection messages = new ArrayList(); + + public int getId() { + return id; + } + + public void setId(int empNo) { + this.id = empNo; + } + + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + + public Collection getMessages() { + return messages; + } + + public void addMessage(Message m) { + if (!getMessages().contains(m)) { + getMessages().add(m); + if (m.getConversation() != null) { + m.getConversation().getMessages().remove(m); + } + m.setConversation(this); + } + } + + public String toString() { + return "Conversation " + getId() + ": status: " + getStatus(); + } +} diff --git a/examples/Chapter7/07-messageBoardExample/src/model/examples/model/Message.java b/examples/Chapter7/07-messageBoardExample/src/model/examples/model/Message.java new file mode 100644 index 0000000..1854c90 --- /dev/null +++ b/examples/Chapter7/07-messageBoardExample/src/model/examples/model/Message.java @@ -0,0 +1,56 @@ +package examples.model; + +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +public class Message { + @Id + private int id; + private String message; + @Temporal(TemporalType.DATE) + private Date postingDate; + @ManyToOne Conversation conversation; + + public int getId() { + return id; + } + + public void setId(int empNo) { + this.id = empNo; + } + + public String getMessage() { + return message; + } + + public void setMessage(String name) { + this.message = name; + } + + public Date getPostingDate() { + return postingDate; + } + + public void setPostingDate(Date postingDate) { + this.postingDate = postingDate; + } + + public Conversation getConversation() { + return conversation; + } + + public void setConversation(Conversation conversation) { + this.conversation = conversation; + } + + public String toString() { + return "Message " + getId() + ": " + getMessage() + + " posted: " + getPostingDate(); + } +} diff --git a/examples/Chapter7/07-messageBoardExample/src/model/examples/stateless/ConversationMaintenance.java b/examples/Chapter7/07-messageBoardExample/src/model/examples/stateless/ConversationMaintenance.java new file mode 100644 index 0000000..6cd84ee --- /dev/null +++ b/examples/Chapter7/07-messageBoardExample/src/model/examples/stateless/ConversationMaintenance.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.Collection; +import java.util.Date; + +import examples.model.Conversation; + +public interface ConversationMaintenance { + public void archiveConversations(Date minAge); + public Collection findAllConversations(); +} diff --git a/examples/Chapter7/07-messageBoardExample/src/model/examples/stateless/ConversationMaintenanceBean.java b/examples/Chapter7/07-messageBoardExample/src/model/examples/stateless/ConversationMaintenanceBean.java new file mode 100644 index 0000000..e1a8291 --- /dev/null +++ b/examples/Chapter7/07-messageBoardExample/src/model/examples/stateless/ConversationMaintenanceBean.java @@ -0,0 +1,44 @@ +package examples.stateless; + +import java.util.Collection; +import java.util.Date; +import java.util.List; + +import javax.ejb.Stateless; +import javax.ejb.TransactionAttribute; +import javax.ejb.TransactionAttributeType; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import javax.persistence.FlushModeType; + +import examples.model.Conversation; + +@Stateless +public class ConversationMaintenanceBean implements ConversationMaintenance { + @PersistenceContext(unitName="MessageBoard") + private EntityManager em; + + + public void archiveConversations(Date minAge) { + List active = (List) + em.createNamedQuery("findActiveConversations") + .getResultList(); + Query maxAge = em.createNamedQuery("findLastMessageDate"); + maxAge.setFlushMode(FlushModeType.COMMIT); + for (Conversation c : active) { + maxAge.setParameter("conversation", c); + Date lastMessageDate = (Date) maxAge.getSingleResult(); + if (lastMessageDate.before(minAge)) { + c.setStatus("INACTIVE"); + } + } + } + + + @TransactionAttribute(TransactionAttributeType.SUPPORTS) + public Collection findAllConversations() { + return (Collection) em.createQuery( + "SELECT c FROM Conversation c").getResultList(); + } +} diff --git a/examples/Chapter7/07-messageBoardExample/src/servlet/examples/servlet/MessageBoardServlet.java b/examples/Chapter7/07-messageBoardExample/src/servlet/examples/servlet/MessageBoardServlet.java new file mode 100644 index 0000000..6f2c0ab --- /dev/null +++ b/examples/Chapter7/07-messageBoardExample/src/servlet/examples/servlet/MessageBoardServlet.java @@ -0,0 +1,100 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Calendar; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Conversation; +import examples.model.Message; +import examples.stateless.ConversationMaintenance; + +public class MessageBoardServlet extends HttpServlet { + + private final String TITLE = + "Chapter 7: Queries and Transactions Example (MessageBoard)"; + + private final String DESCRIPTION = + "This example demonstrates the use of FlushMode.
" + + "The example allows you to archive Conversations for a message board that " + + "are older than a given date. Also displays all Conversations."; + + + @EJB + private ConversationMaintenance service; + + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action != null) { + if (action.equals("Archive")) { + Calendar c = Calendar.getInstance(); + c.set(parseInt(request.getParameter("year")), + parseInt(request.getParameter("month"))-1, // month is zero-based + parseInt(request.getParameter("date"))); + service.archiveConversations(c.getTime()); + } + } + out.println("All Conversations:
"); + printConversations(service.findAllConversations(), out); + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printConversations(Collection conversations, PrintWriter out) { + for (Conversation c : conversations) { + out.print(c + "
"); + for (Message m : c.getMessages()) { + out.print("        " + m + "
"); + + } + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form find + out.println("

Archive Messages older than:

"); + out.println("-"); + out.println("-"); + out.println(" day-month-year (xx-xx-xxxx)"); + out.println(""); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter7/07-messageBoardExample/undeploy.bat b/examples/Chapter7/07-messageBoardExample/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter7/07-messageBoardExample/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter7/08-bulkQueryExample/build.xml b/examples/Chapter7/08-bulkQueryExample/build.xml new file mode 100644 index 0000000..3aba8f9 --- /dev/null +++ b/examples/Chapter7/08-bulkQueryExample/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter7/08-bulkQueryExample/deploy.bat b/examples/Chapter7/08-bulkQueryExample/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter7/08-bulkQueryExample/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter7/08-bulkQueryExample/etc/persistence/META-INF/persistence.xml b/examples/Chapter7/08-bulkQueryExample/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..4b385d2 --- /dev/null +++ b/examples/Chapter7/08-bulkQueryExample/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/bulkQueryExample + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter7/08-bulkQueryExample/etc/sql/db.sql b/examples/Chapter7/08-bulkQueryExample/etc/sql/db.sql new file mode 100644 index 0000000..6b3ade0 --- /dev/null +++ b/examples/Chapter7/08-bulkQueryExample/etc/sql/db.sql @@ -0,0 +1,57 @@ +DROP TABLE EMPLOYEE_PROJECT; +DROP TABLE PROJECT; +DROP TABLE EMPLOYEE; +DROP TABLE DEPARTMENT; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE PROJECT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), STARTDATE DATE, SALARY BIGINT, + DEPARTMENT_ID INTEGER, MANAGER_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPARTMENT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID), + CONSTRAINT MANAGER_FK FOREIGN KEY (MANAGER_ID) REFERENCES EMPLOYEE (ID)); +CREATE TABLE EMPLOYEE_PROJECT (PROJECTS_ID INTEGER NOT NULL, EMPLOYEES_ID INTEGER NOT NULL, + CONSTRAINT PROJECTS_FK FOREIGN KEY (PROJECTS_ID) REFERENCES PROJECT (ID), + CONSTRAINT EMPLOYEES_FK FOREIGN KEY (EMPLOYEES_ID) REFERENCES EMPLOYEE (ID), + PRIMARY KEY (PROJECTS_ID, EMPLOYEES_ID)); + + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'CA13'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'CA19'); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (1, 'Joan', 59000, {d '2003-04-16'}, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (2, 'Sarah', 52000, {d '2002-04-26'}, 2, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (3, 'John', 55000, {d '2001-01-01'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (4, 'Roberts', 53000, {d '2001-05-23'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (5, 'Peter', 50000, {d '2002-08-06'}, 2, 1); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (6, 'Frank', 51000, {d '2003-02-17'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (7, 'Scott', 60000, {d '2004-11-14'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (8, 'Sue', 62000, {d '2005-08-18'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (9, 'Stephanie', 54000, {d '2006-06-07'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (10, 'Jennifer', 55000, {d '1999-08-11'}, 1, 2); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, DEPARTMENT_ID, MANAGER_ID) VALUES (11, 'Marcus', 35000, {d '1995-07-22'}, NULL, NULL); + +INSERT INTO PROJECT (ID, NAME) VALUES (1, 'Design Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (2, 'Implement Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (3, 'Test Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (4, 'Release3'); + +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (1, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (4, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (7, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 3); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 1); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 2); +INSERT INTO EMPLOYEE_PROJECT (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 3); \ No newline at end of file diff --git a/examples/Chapter7/08-bulkQueryExample/etc/web/WEB-INF/web.xml b/examples/Chapter7/08-bulkQueryExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter7/08-bulkQueryExample/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServiceServlet + examples.servlet.EmployeeServiceServlet + + + + EmployeeServiceServlet + /EmployeeServiceServlet + + \ No newline at end of file diff --git a/examples/Chapter7/08-bulkQueryExample/src/model/examples/model/Department.java b/examples/Chapter7/08-bulkQueryExample/src/model/examples/model/Department.java new file mode 100644 index 0000000..9d1a2c2 --- /dev/null +++ b/examples/Chapter7/08-bulkQueryExample/src/model/examples/model/Department.java @@ -0,0 +1,42 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="department") + private Collection employees; + + public Department() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter7/08-bulkQueryExample/src/model/examples/model/Employee.java b/examples/Chapter7/08-bulkQueryExample/src/model/examples/model/Employee.java new file mode 100644 index 0000000..51584b7 --- /dev/null +++ b/examples/Chapter7/08-bulkQueryExample/src/model/examples/model/Employee.java @@ -0,0 +1,84 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToMany; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + @Temporal(TemporalType.DATE) + private Date startDate; + + @ManyToOne + private Employee manager; + + @OneToMany(mappedBy="manager") + private Collection directs; + + @ManyToOne + private Department department; + + @ManyToMany + private Collection projects; + + public Employee() { + projects = new ArrayList(); + directs = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public long getSalary() { + return salary; + } + + public Date getStartDate() { + return startDate; + } + + public Department getDepartment() { + return department; + } + + public Collection getDirects() { + return directs; + } + + public Employee getManager() { + return manager; + } + + public Collection getProjects() { + return projects; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary() + + ((getDepartment() == null) ? "" : (", dept: " + getDepartment().getName())) + + ((getManager() == null) ? "" : (", mgrId: " + getManager().getId())); + } +} diff --git a/examples/Chapter7/08-bulkQueryExample/src/model/examples/model/Project.java b/examples/Chapter7/08-bulkQueryExample/src/model/examples/model/Project.java new file mode 100644 index 0000000..8226327 --- /dev/null +++ b/examples/Chapter7/08-bulkQueryExample/src/model/examples/model/Project.java @@ -0,0 +1,37 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToMany; + +@Entity +public class Project { + @Id + protected int id; + protected String name; + @ManyToMany(mappedBy="projects") + private Collection employees; + + public Project() { + employees = new ArrayList(); + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Project id: " + getId() + ", name: " + getName(); + } +} diff --git a/examples/Chapter7/08-bulkQueryExample/src/model/examples/stateless/DepartmentService.java b/examples/Chapter7/08-bulkQueryExample/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..8da256f --- /dev/null +++ b/examples/Chapter7/08-bulkQueryExample/src/model/examples/stateless/DepartmentService.java @@ -0,0 +1,12 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Department; + +public interface DepartmentService { + public void removeDepartmentFailure(); + public void removeDepartment(); + public Department findDepartment(int id); + public Collection findAllDepartments(); +} diff --git a/examples/Chapter7/08-bulkQueryExample/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter7/08-bulkQueryExample/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..93eb3ea --- /dev/null +++ b/examples/Chapter7/08-bulkQueryExample/src/model/examples/stateless/DepartmentServiceBean.java @@ -0,0 +1,43 @@ +package examples.stateless; + +import static javax.ejb.TransactionAttributeType.REQUIRES_NEW; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.ejb.TransactionAttribute; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Department; + +@Stateless +public class DepartmentServiceBean implements DepartmentService { + @PersistenceContext(unitName="BulkQueries") + protected EntityManager em; + + + @TransactionAttribute(REQUIRES_NEW) + public void removeDepartmentFailure() { + em.createQuery("DELETE FROM Department d " + + "WHERE d.name IN ('CA13', 'CA19', 'NY30')") + .executeUpdate(); + } + + @TransactionAttribute(REQUIRES_NEW) + public void removeDepartment() { + em.createQuery("UPDATE Employee e " + + "SET e.department = null " + + "WHERE e.department.name IN ('CA13', 'CA19', 'NY30')") + .executeUpdate(); + } + + public Department findDepartment(int id) { + return em.find(Department.class, id); + } + + public Collection findAllDepartments() { + return (Collection) em.createQuery( + "SELECT d FROM Department d").getResultList(); + } +} diff --git a/examples/Chapter7/08-bulkQueryExample/src/model/examples/stateless/EmployeeService.java b/examples/Chapter7/08-bulkQueryExample/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..6ab3e2f --- /dev/null +++ b/examples/Chapter7/08-bulkQueryExample/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,12 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Department; +import examples.model.Employee; + +public interface EmployeeService { + public void assignManager(Department dept, Employee manager); + public Employee findEmployee(int id); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter7/08-bulkQueryExample/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter7/08-bulkQueryExample/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..8a0bf68 --- /dev/null +++ b/examples/Chapter7/08-bulkQueryExample/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,38 @@ +package examples.stateless; + +import static javax.ejb.TransactionAttributeType.REQUIRES_NEW; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.ejb.TransactionAttribute; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="BulkQueries") + EntityManager em; + + @TransactionAttribute(REQUIRES_NEW) + public void assignManager(Department dept, Employee manager) { + em.createQuery("UPDATE Employee e " + + "SET e.manager = :manager " + + "WHERE e.department = :dept ") + .setParameter("manager", manager) + .setParameter("dept", dept) + .executeUpdate(); + } + + public Employee findEmployee(int id) { + return em.find(Employee.class, id); + } + + public Collection findAllEmployees() { + return (Collection) em.createQuery( + "SELECT e FROM Employee e").getResultList(); + } +} diff --git a/examples/Chapter7/08-bulkQueryExample/src/model/examples/stateless/ProjectService.java b/examples/Chapter7/08-bulkQueryExample/src/model/examples/stateless/ProjectService.java new file mode 100644 index 0000000..4fc65e3 --- /dev/null +++ b/examples/Chapter7/08-bulkQueryExample/src/model/examples/stateless/ProjectService.java @@ -0,0 +1,10 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Project; + +public interface ProjectService { + public void removeEmptyProjects(); + public Collection findAllProjects(); +} diff --git a/examples/Chapter7/08-bulkQueryExample/src/model/examples/stateless/ProjectServiceBean.java b/examples/Chapter7/08-bulkQueryExample/src/model/examples/stateless/ProjectServiceBean.java new file mode 100644 index 0000000..f3f0159 --- /dev/null +++ b/examples/Chapter7/08-bulkQueryExample/src/model/examples/stateless/ProjectServiceBean.java @@ -0,0 +1,30 @@ +package examples.stateless; + +import static javax.ejb.TransactionAttributeType.REQUIRES_NEW; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.ejb.TransactionAttribute; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Project; + +@Stateless +public class ProjectServiceBean implements ProjectService { + @PersistenceContext(unitName="BulkQueries") + EntityManager em; + + @TransactionAttribute(REQUIRES_NEW) + public void removeEmptyProjects() { + em.createQuery("DELETE FROM Project p " + + "WHERE p.employees IS EMPTY ") + .executeUpdate(); + } + + public Collection findAllProjects() { + return (Collection) em.createQuery( + "SELECT p FROM Project p").getResultList(); + } +} diff --git a/examples/Chapter7/08-bulkQueryExample/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter7/08-bulkQueryExample/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..7e792ab --- /dev/null +++ b/examples/Chapter7/08-bulkQueryExample/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,133 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.ejb.EJBException; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateless.DepartmentService; +import examples.stateless.EmployeeService; +import examples.stateless.ProjectService; + +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 6: Bulk Query Examples"; + + private final String DESCRIPTION = + "This example demonstrates bulk UPDATE and DELETE queries.
" + + "The example allows you to update all employees' manager, remove " + + "all empty projects, and delete all departments of a given name."; + + + @EJB + private EmployeeService empService; + @EJB + private ProjectService projService; + @EJB + private DepartmentService deptService; + + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action != null) { + if (action.equals("UpdateManagers")) { + empService.assignManager( + deptService.findDepartment(parseInt(request.getParameter("deptId"))), + empService.findEmployee(parseInt(request.getParameter("mgrId")))); + } else if (action.equals("RemoveEmptyProjects")) { + projService.removeEmptyProjects(); + } else if (action.equals("RemoveDepartmentsFailure")) { + try { + deptService.removeDepartmentFailure(); + } catch (EJBException e) { + out.println("Unable to remove departments: " + e.getCause()); + out.println("
"); + } + } else if (action.equals("RemoveDepartments")) { + deptService.removeDepartment(); + } + } + out.println("Employees:
"); + printCollection(empService.findAllEmployees(), out); + out.println("Departments:
"); + printCollection(deptService.findAllDepartments(), out); + out.println("Projects:
"); + printCollection(projService.findAllProjects(), out); + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printCollection(Collection c, PrintWriter out) { + for (Object o : c) { + out.print(o + "
"); + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println(""); + // form to update + out.println("

Update Department Managers

"); + out.println("This will set all employees' manager in the given department to the given manager."); + out.println(""); + out.println(""); + out.println("" + + ""); + out.println("
Department Id:(int)
Manager Id:(int)
"); + out.println("
"); + // form to remove empty projects + out.println("

Remove empty Projects

"); + out.println(""); + out.println(""); + out.println("
"); + out.println("
"); + // form to remove departments + out.println("

Remove Departments (with constraint failure)

"); + out.println(""); + out.println(""); + out.println("
"); + out.println("
"); + // form to remove departments + out.println("

Remove Departments

"); + out.println(""); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter7/08-bulkQueryExample/undeploy.bat b/examples/Chapter7/08-bulkQueryExample/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter7/08-bulkQueryExample/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter7/09-queryHintsExample/build.xml b/examples/Chapter7/09-queryHintsExample/build.xml new file mode 100644 index 0000000..2726647 --- /dev/null +++ b/examples/Chapter7/09-queryHintsExample/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter7/09-queryHintsExample/deploy.bat b/examples/Chapter7/09-queryHintsExample/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter7/09-queryHintsExample/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter7/09-queryHintsExample/etc/persistence/META-INF/persistence.xml b/examples/Chapter7/09-queryHintsExample/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..8476bab --- /dev/null +++ b/examples/Chapter7/09-queryHintsExample/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,12 @@ + + + jdbc/queryHintsExample + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter7/09-queryHintsExample/etc/sql/db.sql b/examples/Chapter7/09-queryHintsExample/etc/sql/db.sql new file mode 100644 index 0000000..72746e4 --- /dev/null +++ b/examples/Chapter7/09-queryHintsExample/etc/sql/db.sql @@ -0,0 +1,15 @@ +DROP TABLE EMPLOYEE; + +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, PRIMARY KEY (ID)); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY) VALUES (1, 'Joan', 59000); +INSERT INTO EMPLOYEE (ID, NAME, SALARY) VALUES (2, 'Sarah', 52000); +INSERT INTO EMPLOYEE (ID, NAME, SALARY) VALUES (3, 'John', 55000); +INSERT INTO EMPLOYEE (ID, NAME, SALARY) VALUES (4, 'Roberts', 53000); +INSERT INTO EMPLOYEE (ID, NAME, SALARY) VALUES (5, 'Peter', 50000); +INSERT INTO EMPLOYEE (ID, NAME, SALARY) VALUES (6, 'Frank', 51000); +INSERT INTO EMPLOYEE (ID, NAME, SALARY) VALUES (7, 'Scott', 60000); +INSERT INTO EMPLOYEE (ID, NAME, SALARY) VALUES (8, 'Sue', 62000); +INSERT INTO EMPLOYEE (ID, NAME, SALARY) VALUES (9, 'Stephanie', 54000); +INSERT INTO EMPLOYEE (ID, NAME, SALARY) VALUES (10, 'Jennifer', 55000); +INSERT INTO EMPLOYEE (ID, NAME, SALARY) VALUES (11, 'Marcus', 35000); diff --git a/examples/Chapter7/09-queryHintsExample/etc/web/WEB-INF/web.xml b/examples/Chapter7/09-queryHintsExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter7/09-queryHintsExample/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + EmployeeServiceServlet + examples.servlet.EmployeeServiceServlet + + + + EmployeeServiceServlet + /EmployeeServiceServlet + + \ No newline at end of file diff --git a/examples/Chapter7/09-queryHintsExample/src/model/examples/model/Employee.java b/examples/Chapter7/09-queryHintsExample/src/model/examples/model/Employee.java new file mode 100644 index 0000000..e9728e5 --- /dev/null +++ b/examples/Chapter7/09-queryHintsExample/src/model/examples/model/Employee.java @@ -0,0 +1,35 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.NamedQuery; +import javax.persistence.QueryHint; + +@Entity +@NamedQuery(name="findEmployeeNoCache", + query="SELECT e FROM Employee e WHERE e.id = ?1", + hints={@QueryHint(name="toplink.cache-usage", value="DoNotCheckCache")}) +public class Employee { + @Id + private int id; + private String name; + private long salary; + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public long getSalary() { + return salary; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary(); + } +} diff --git a/examples/Chapter7/09-queryHintsExample/src/model/examples/stateless/EmployeeService.java b/examples/Chapter7/09-queryHintsExample/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..f01c203 --- /dev/null +++ b/examples/Chapter7/09-queryHintsExample/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,12 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public Employee findEmployeeNoCache(int id); + public Employee findEmployeeNoCacheNamed(int id); + public Employee findEmployee(int id); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter7/09-queryHintsExample/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter7/09-queryHintsExample/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..3d32902 --- /dev/null +++ b/examples/Chapter7/09-queryHintsExample/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,57 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.NoResultException; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import org.eclipse.persistence.queries.ObjectLevelReadQuery; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="QueryHints") + private EntityManager em; + + + public Employee findEmployee(int empId) { + Query q = em.createQuery("SELECT e FROM Employee e WHERE e.id = ?1"); + q.setParameter(1, empId); + try { + return (Employee) q.getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public Employee findEmployeeNoCache(int empId) { + Query q = em.createQuery("SELECT e FROM Employee e WHERE e.id = ?1"); + // force read from database + q.setHint("cacheUsage", ObjectLevelReadQuery.DoNotCheckCache); + q.setParameter(1, empId); + try { + return (Employee) q.getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + + public Employee findEmployeeNoCacheNamed(int empId) { + Query q = em.createNamedQuery("findEmployeeNoCache"); + q.setParameter(1, empId); + try { + return (Employee) q.getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public Collection findAllEmployees() { + return (Collection) em.createQuery( + "SELECT e FROM Employee e").getResultList(); + } +} diff --git a/examples/Chapter7/09-queryHintsExample/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter7/09-queryHintsExample/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..5a3e6e8 --- /dev/null +++ b/examples/Chapter7/09-queryHintsExample/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,100 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.stateless.EmployeeService; + +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 7: Query Hints Examples"; + + private final String DESCRIPTION = + "This example demonstrates the use of query hints.
" + + "The example allows you to find an all employees using either " + + "a regular query, or one configured to use a 'cacheUsage' hint. " + + "The hint can be used with either a dynamic or named query"; + + + @EJB + private EmployeeService service; + + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action != null) { + Employee emp = null; + if (action.equals("Find")) { + emp = service.findEmployee(parseInt(request.getParameter("id"))); + } else if (action.equals("FindNoCacheDynamic")) { + emp = service.findEmployeeNoCache(parseInt(request.getParameter("id"))); + } else if (action.equals("FindNoCacheNamed")) { + emp = service.findEmployeeNoCacheNamed(parseInt(request.getParameter("id"))); + } + out.println("Found " + emp); + out.println("
"); + } + out.println("All Employees:
"); + printCollection(service.findAllEmployees(), out); + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printCollection(Collection c, PrintWriter out) { + for (Object o : c) { + out.print(o + "
"); + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println(""); + // form find + out.println("

Find Employee

"); + out.println(""); + out.println("" + + "" + + "" + + ""); + out.println("
Employee Id:(int)
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter7/09-queryHintsExample/undeploy.bat b/examples/Chapter7/09-queryHintsExample/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter7/09-queryHintsExample/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter8/jpqlExamples/build.xml b/examples/Chapter8/jpqlExamples/build.xml new file mode 100644 index 0000000..3bc56a0 --- /dev/null +++ b/examples/Chapter8/jpqlExamples/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter8/jpqlExamples/deploy.bat b/examples/Chapter8/jpqlExamples/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter8/jpqlExamples/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter8/jpqlExamples/etc/persistence/META-INF/persistence.xml b/examples/Chapter8/jpqlExamples/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..9da9ef1 --- /dev/null +++ b/examples/Chapter8/jpqlExamples/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,20 @@ + + + + jdbc/jpqlExamples + examples.model.Employee + examples.model.Department + examples.model.Address + examples.model.DesignProject + examples.model.Phone + examples.model.Project + examples.model.QualityProject + NONE + + + + + + + \ No newline at end of file diff --git a/examples/Chapter8/jpqlExamples/etc/sql/db.sql b/examples/Chapter8/jpqlExamples/etc/sql/db.sql new file mode 100644 index 0000000..c45c7ab --- /dev/null +++ b/examples/Chapter8/jpqlExamples/etc/sql/db.sql @@ -0,0 +1,95 @@ +DROP TABLE DEPARTMENT; +DROP TABLE PROJECT; +DROP TABLE PROJECT_EMPLOYEE; +DROP TABLE EMPLOYEE; +DROP TABLE PHONE; +DROP TABLE ADDRESS; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE PROJECT (ID INTEGER NOT NULL, DTYPE VARCHAR(31), NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE PROJECT_EMPLOYEE (EMPLOYEES_ID INTEGER, PROJECTS_ID INTEGER); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, STARTDATE DATE, ADDRESS_ID INTEGER, DEPARTMENT_ID INTEGER, MANAGER_ID INTEGER, PRIMARY KEY (ID)); +CREATE TABLE PHONE (ID BIGINT NOT NULL, NUMBER VARCHAR(255), TYPE VARCHAR(255), EMPLOYEE_ID INTEGER, PRIMARY KEY (ID)); +CREATE TABLE ADDRESS (ID INTEGER NOT NULL, CITY VARCHAR(255), STATE VARCHAR(255), STREET VARCHAR(255), ZIP VARCHAR(255), PRIMARY KEY (ID)); + + +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (1, 'New York', 'NY', '123 Apple Tree Cr.', '10001'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (2, 'Manhattan', 'NY', '654 Stanton Way.', '10003'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (3, 'New York', 'NY', '99 Queen St.', '10001'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (4, 'Redwood Shores', 'CA', '445 McDonell Cr.', '90123'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (5, 'San Jose', 'CA', '624 Hamilton Dr.', '90123'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (6, 'San Jose', 'CA', '724 Coventry Rd.', '90123'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (7, 'San Francisco', 'CA', '77 Manchester Blvd.', '90123'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (8, 'Moorestown', 'NJ', '53 King St.', '08057'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (9, 'New York', 'NY', '14 Industrial Ave.', '10001'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (10, 'Redwood Shores', 'CA', '777 High Tech Ln.', '90123'); + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'QA'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'Accounting'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (4, 'CAEngOtt'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (5, 'USEngCal'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (6, 'CADocOtt'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (7, 'QA_East'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (8, 'QANorth'); + +INSERT INTO PROJECT (ID, NAME, DTYPE) VALUES (1, 'Design Release2', 'DP'); +INSERT INTO PROJECT (ID, NAME, DTYPE) VALUES (2, 'Release1', 'DP'); +INSERT INTO PROJECT (ID, NAME, DTYPE) VALUES (3, 'Test Release2', 'QP'); +INSERT INTO PROJECT (ID, NAME, DTYPE) VALUES (4, 'Implement Release3', 'P'); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (1, 'John', 55000, {d '2001-01-01'}, 1, 2, 9); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (2, 'Rob', 53000, {d '2001-05-23'}, 2, 2, 9); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (3, 'Peter', 40000, {d '2002-08-06'}, 3, 2, 9); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (4, 'Frank', 41000, {d '2003-02-17'}, 4, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (5, 'Scott', 60000, {d '2004-11-14'}, 5, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (6, 'Sue', 62000, {d '2005-08-18'}, 6, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (7, 'Stephanie', 54000, {d '2006-06-07'}, 7, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (8, 'Jennifer', 45000, {d '1999-08-11'}, 8, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (9, 'Sarah', 52000, {d '2002-04-26'}, 9, 2, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (10, 'Joan', 59000, {d '2003-04-16'}, 10, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (11, 'Marcus', 35000, {d '1995-07-22'}, NULL, NULL, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (12, 'Joe', 36000, {d '1995-07-22'}, NULL, 3, 11); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (13, 'Jack', 43000, {d '1995-07-22'}, NULL, 3, NULL); + +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (1, '(212)555-1234', 'Office', 1); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (2, '(212)555-9843', 'Home', 1); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (3, '(315)555-6253', 'Office', 2); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (4, '(516)555-9837', 'Office', 3); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (5, '(516)555-2034', 'Cell', 3); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (6, '(650)555-7583', 'Office', 4); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (7, '(650)555-5345', 'Home', 4); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (8, '(650)555-9386', 'Office', 5); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (9, '(650)555-4885', 'Cell', 5); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (10, '(650)555-3836', 'Office', 6); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (11, '(650)555-0985', 'Home', 6); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (12, '(650)555-1946', 'Cell', 6); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (13, '(650)555-4759', 'Office', 7); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (14, '(650)555-4757', 'Home', 7); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (15, '(650)555-6753', 'Office', 8); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (16, '(585)555-0693', 'Office', 9); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (17, '(585)555-3098', 'Home', 9); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (18, '(585)555-1457', 'Cell', 9); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (19, '(650)555-9838', 'Office', 10); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (20, '(650)555-2346', 'Home', 10); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (21, '(650)555-9874', 'Cell', 10); + +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (1, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (4, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (7, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 3); \ No newline at end of file diff --git a/examples/Chapter8/jpqlExamples/etc/web/WEB-INF/web.xml b/examples/Chapter8/jpqlExamples/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..010ba31 --- /dev/null +++ b/examples/Chapter8/jpqlExamples/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + ClientServlet + examples.servlet.ClientServlet + + + + ClientServlet + /ClientServlet + + \ No newline at end of file diff --git a/examples/Chapter8/jpqlExamples/etc/web/index.html b/examples/Chapter8/jpqlExamples/etc/web/index.html new file mode 100644 index 0000000..da81325 --- /dev/null +++ b/examples/Chapter8/jpqlExamples/etc/web/index.html @@ -0,0 +1,300 @@ + + +Chapter 8: Query Language +

Chapter 8: Query Language

This example shows some basic JPQL queries.
+ The example allows you to try the named queries shown in this + chapter of the book, as well as try your own queries.

+
+ + +

Try your own query

+ + + +
+
+ +

SELECT clause examples

+ + + + + + + + + + + + + + + + + + + + + +
SELECT e
+ FROM Employee e
SELECT d
+ FROM Department d
SELECT OBJECT(d)
+ FROM Department d
SELECT e.name
+ FROM Employee e
SELECT e.department
+ FROM Employee e
SELECT DISTINCT e.department
+ FROM Employee e
SELECT d.employees
+ FROM Department d
SELECT e.name, e.salary
+ FROM Employee e
SELECT NEW examples.model.EmployeeDetails(e.name, e.salary, e.department.name)
+ FROM Employee e
SELECT p
+ FROM Project p
+ WHERE p.employees IS NOT EMPTY
+ +

FROM clause examples

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SELECT p
+ FROM Employee e JOIN e.phones p
SELECT DISTINCT p
+ FROM Employee e, IN(e.phones) p
SELECT p.number
+ FROM Employee e JOIN e.phones p
SELECT d
+ FROM Employee e JOIN e.department d
SELECT e.department
+ FROM Employee e
SELECT DISTINCT e.department
+ FROM Project p JOIN p.employees e
+ WHERE p.name = 'Release1' AND e.address.state = 'CA'
SELECT DISTINCT d
+ FROM Project p JOIN p.employees e JOIN e.department d JOIN e.address a
+ WHERE p.name = 'Release1' AND a.state = 'CA'
SELECT DISTINCT d
+ FROM Department d, Employee e
+ WHERE d = e.department
SELECT d, m
+ FROM Department d, Employee m
+ WHERE d = m.department AND m.directs IS NOT EMPTY
SELECT DISTINCT p
+ FROM Department d JOIN d.employees e JOIN e.projects p
SELECT e, d
+ FROM Employee e LEFT JOIN e.department d
SELECT e
+ FROM Employee e JOIN FETCH e.address
SELECT e, a
+ FROM Employee e JOIN e.address a
SELECT d
+ FROM Department d LEFT JOIN FETCH d.employees
SELECT d, e
+ FROM Department d LEFT JOIN d.employees e
+ +

WHERE clause examples

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SELECT e
+ FROM Employee e
+ WHERE e.salary BETWEEN 40000 AND 45000
SELECT e
+ FROM Employee e
+ WHERE e.salary >= 40000 AND e.salary <= 45000
SELECT d
+ FROM Department d
+ WHERE d.name LIKE '__Eng%'
SELECT d
+ FROM Department d
+ WHERE d.name LIKE 'QA\_%' ESCAPE '\'
SELECT e
+ FROM Employee e
+ WHERE e.salary = (SELECT MAX(e2.salary)
+ FROM Employee e2)
SELECT e
+ FROM Employee e
+ WHERE EXISTS (SELECT p
+ FROM Phone p
+ WHERE p.employee = e AND p.type = 'Cell')
SELECT e
+ FROM Employee e
+ WHERE EXISTS (SELECT p
+ FROM e.phones p
+ WHERE p.type = 'Cell')
SELECT e
+ FROM Employee e
+ WHERE e.address.state IN ('NY', 'CA')
SELECT e
+ FROM Employee e
+ WHERE e.department IN (SELECT DISTINCT d
+ FROM Department d JOIN d.employees de JOIN de.projects p
+ WHERE p.name LIKE 'QA%')
SELECT p
+ FROM Phone p
+ WHERE p.type NOT IN ('Office', 'Home')
SELECT e
+ FROM Employee e
+ WHERE e.directs IS NOT EMPTY
SELECT m
+ FROM Employee m
+ WHERE (SELECT COUNT(e)
+ FROM Employee e
+ WHERE e.manager = m) > 0
SELECT e
+ FROM Employee e
+ WHERE e MEMBER OF e.directs
SELECT e
+ FROM Employee e
+ WHERE NOT EXISTS (SELECT p
+ FROM e.phones p
+ WHERE p.type = 'Cell')
SELECT e
+ FROM Employee e
+ WHERE e.directs IS NOT EMPTY AND
+ e.salary < ALL (SELECT d.salary
+ FROM e.directs d)
SELECT e
+ FROM Employee e
+ WHERE e.department = ANY (SELECT DISTINCT d
+ FROM Department d JOIN d.employees de JOIN de.projects p
+ WHERE p.name LIKE 'QA%')
SELECT d
+ FROM Department d
+ WHERE SIZE(d.employees) = 2
SELECT d
+ FROM Department d
+ WHERE (SELECT COUNT(e)
+ FROM d.employees e) = 2
+ +

ORDER BY examples

+ + + + + + + +
SELECT e
+ FROM Employee e
+ ORDER BY e.name DESC
SELECT e
+ FROM Employee e JOIN e.department d
+ ORDER BY d.name, e.name DESC
SELECT e.name
+ FROM Employee e
+ ORDER BY e.salary DESC
+ +

Aggregate Query examples

+ + + + + + + + + + + + + +
SELECT AVG(e.salary)
+ FROM Employee e
SELECT d.name, AVG(e.salary)
+ FROM Department d JOIN d.employees e
+ GROUP BY d.name
SELECT d.name, AVG(e.salary)
+ FROM Department d JOIN d.employees e
+ WHERE e.directs IS EMPTY
+ GROUP BY d.name
SELECT d.name, AVG(e.salary)
+ FROM Department d JOIN d.employees e
+ WHERE e.directs IS EMPTY
+ GROUP BY d.name
+ HAVING AVG(e.salary) > 50000
SELECT d.name, e.salary
+ FROM Department d JOIN d.employees e
+ WHERE e.directs IS EMPTY
SELECT e, COUNT(p), COUNT(DISTINCT p.type)
+ FROM Employee e JOIN e.phones p
+ GROUP BY e
+ +

GROUP BY Clause examples

+ + + + + + + + + +
SELECT d.name, COUNT(e)
+ FROM Department d JOIN d.employees e
+ GROUP BY d.name
SELECT d.name, COUNT(e), AVG(e.salary)
+ FROM Department d JOIN d.employees e
+ GROUP BY d.name
SELECT d.name, e.salary, COUNT(p)
+ FROM Department d JOIN d.employees e JOIN e.projects p
+ GROUP BY d.name, e.salary
SELECT COUNT(e), AVG(e.salary)
+ FROM Employee e
+ +

HAVING Clause example

+ + + +
SELECT e, COUNT(p)
+ FROM Employee e JOIN e.projects p
+ GROUP BY e
+ HAVING COUNT(p) >= 2
+ +

UPDATE Query examples

+ + + + + + + +
UPDATE Employee e
+ SET e.salary = 60000
+ WHERE e.salary = 55000
UPDATE Employee e
+ SET e.salary = e.salary + 5000
+ WHERE EXISTS (SELECT p
+ FROM e.projects p
+ WHERE p.name = 'Release1')
UPDATE Phone p
+ SET p.number = CONCAT('288', SUBSTRING(p.number, LOCATE(p.number, '-'), 4)),
+ p.type = 'Business'
+ WHERE p.employee.address.city = 'New York' AND p.type = 'Office'
+ +

DELETE Query example

+ + + +
DELETE FROM Employee e
+ WHERE e.department IS NULL
+ + + + diff --git a/examples/Chapter8/jpqlExamples/src/model/examples/model/Address.java b/examples/Chapter8/jpqlExamples/src/model/examples/model/Address.java new file mode 100644 index 0000000..e18406b --- /dev/null +++ b/examples/Chapter8/jpqlExamples/src/model/examples/model/Address.java @@ -0,0 +1,62 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Address { + @Id + private int id; + private String street; + private String city; + private String state; + private String zip; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getStreet() { + return street; + } + + public void setStreet(String address) { + this.street = address; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getZip() { + return zip; + } + + public void setZip(String zip) { + this.zip = zip; + } + public String toString() { + return "Address id: " + getId() + + ", street: " + getStreet() + + ", city: " + getCity() + + ", state: " + getState() + + ", zip: " + getZip(); + } + +} diff --git a/examples/Chapter8/jpqlExamples/src/model/examples/model/Department.java b/examples/Chapter8/jpqlExamples/src/model/examples/model/Department.java new file mode 100644 index 0000000..a1ac11c --- /dev/null +++ b/examples/Chapter8/jpqlExamples/src/model/examples/model/Department.java @@ -0,0 +1,42 @@ +package examples.model; + +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="department") + private Set employees = new HashSet(); + + public int getId() { + return id; + } + + public void setId(int deptNo) { + this.id = deptNo; + } + + public String getName() { + return name; + } + + public void setName(String deptName) { + this.name = deptName; + } + + public Set getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter8/jpqlExamples/src/model/examples/model/DesignProject.java b/examples/Chapter8/jpqlExamples/src/model/examples/model/DesignProject.java new file mode 100644 index 0000000..6b9f13a --- /dev/null +++ b/examples/Chapter8/jpqlExamples/src/model/examples/model/DesignProject.java @@ -0,0 +1,9 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.DiscriminatorValue; + +@Entity +@DiscriminatorValue("DP") +public class DesignProject extends Project { +} diff --git a/examples/Chapter8/jpqlExamples/src/model/examples/model/Employee.java b/examples/Chapter8/jpqlExamples/src/model/examples/model/Employee.java new file mode 100644 index 0000000..806ef9f --- /dev/null +++ b/examples/Chapter8/jpqlExamples/src/model/examples/model/Employee.java @@ -0,0 +1,153 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToMany; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.OneToOne; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + @Temporal(TemporalType.DATE) + private Date startDate; + + @OneToOne + private Address address; + + @OneToMany(mappedBy="employee") + private Collection phones = new ArrayList(); + + @ManyToOne + private Department department; + + @ManyToOne + private Employee manager; + + @OneToMany(mappedBy="manager") + private Collection directs = new ArrayList(); + + @ManyToMany(mappedBy="employees") + private Collection projects = new ArrayList(); + + public int getId() { + return id; + } + + public void setId(int empNo) { + this.id = empNo; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public Collection getPhones() { + return phones; + } + + public void addPhone(Phone phone) { + if (!getPhones().contains(phone)) { + getPhones().add(phone); + if (phone.getEmployee() != null) { + phone.getEmployee().getPhones().remove(phone); + } + phone.setEmployee(this); + } + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + if (this.department != null) { + this.department.getEmployees().remove(this); + } + this.department = department; + this.department.getEmployees().add(this); + } + + public Collection getDirects() { + return directs; + } + + public void addDirect(Employee employee) { + if (!getDirects().contains(employee)) { + getDirects().add(employee); + if (employee.getManager() != null) { + employee.getManager().getDirects().remove(employee); + } + employee.setManager(this); + } + } + + public Employee getManager() { + return manager; + } + + public void setManager(Employee manager) { + this.manager = manager; + } + + public Collection getProjects() { + return projects; + } + + public void addProject(Project project) { + if (!getProjects().contains(project)) { + getProjects().add(project); + } + if (!project.getEmployees().contains(this)) { + project.getEmployees().add(this); + } + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary() + + ", phones: " + getPhones() + + ", managerNo: " + ((getManager() == null) ? null : getManager().getId()) + + ", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId()); + } + +} diff --git a/examples/Chapter8/jpqlExamples/src/model/examples/model/EmployeeDetails.java b/examples/Chapter8/jpqlExamples/src/model/examples/model/EmployeeDetails.java new file mode 100644 index 0000000..284aac7 --- /dev/null +++ b/examples/Chapter8/jpqlExamples/src/model/examples/model/EmployeeDetails.java @@ -0,0 +1,19 @@ +package examples.model; + +public class EmployeeDetails { + private String name; + private long salary; + private String deptName; + + public EmployeeDetails(String name, long salary, String deptName) { + this.name = name; + this.salary = salary; + this.deptName = deptName; + } + + public String toString() { + return "EmployeeDetails name: " + name + + ", salary: " + salary + + ", deptName: " + deptName; + } +} diff --git a/examples/Chapter8/jpqlExamples/src/model/examples/model/Phone.java b/examples/Chapter8/jpqlExamples/src/model/examples/model/Phone.java new file mode 100644 index 0000000..afa5419 --- /dev/null +++ b/examples/Chapter8/jpqlExamples/src/model/examples/model/Phone.java @@ -0,0 +1,52 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToOne; + +@Entity +public class Phone { + @Id + private long id; + private String number; + private String type; + @OneToOne Employee employee; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getNumber() { + return number; + } + + public void setNumber(String phoneNo) { + this.number = phoneNo; + } + + public String getType() { + return type; + } + + public void setType(String phoneType) { + this.type = phoneType; + } + + public Employee getEmployee() { + return employee; + } + + public void setEmployee(Employee employee) { + this.employee = employee; + } + + public String toString() { + return "Phone id: " + getId() + + ", no: " + getNumber() + + ", type: " + getType(); + } +} diff --git a/examples/Chapter8/jpqlExamples/src/model/examples/model/Project.java b/examples/Chapter8/jpqlExamples/src/model/examples/model/Project.java new file mode 100644 index 0000000..d1261d3 --- /dev/null +++ b/examples/Chapter8/jpqlExamples/src/model/examples/model/Project.java @@ -0,0 +1,54 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.ManyToMany; + +@Entity +@Inheritance +public class Project { + @Id + protected int id; + protected String name; + @ManyToMany + protected Collection employees = new ArrayList(); + + public int getId() { + return id; + } + + public void setId(int projectNo) { + this.id = projectNo; + } + + public String getName() { + return name; + } + + public void setName(String projectName) { + this.name = projectName; + } + + public Collection getEmployees() { + return employees; + } + + public void addEmployee(Employee employee) { + if (!getEmployees().contains(employee)) { + getEmployees().add(employee); + } + if (!employee.getProjects().contains(this)) { + employee.getProjects().add(this); + } + } + + public String toString() { + return getClass().getName().substring(getClass().getName().lastIndexOf('.')+1) + + " no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter8/jpqlExamples/src/model/examples/model/QualityProject.java b/examples/Chapter8/jpqlExamples/src/model/examples/model/QualityProject.java new file mode 100644 index 0000000..78d2361 --- /dev/null +++ b/examples/Chapter8/jpqlExamples/src/model/examples/model/QualityProject.java @@ -0,0 +1,9 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.DiscriminatorValue; + +@Entity +@DiscriminatorValue("QP") +public class QualityProject extends Project { +} diff --git a/examples/Chapter8/jpqlExamples/src/servlet/examples/servlet/ClientServlet.java b/examples/Chapter8/jpqlExamples/src/servlet/examples/servlet/ClientServlet.java new file mode 100644 index 0000000..d955cca --- /dev/null +++ b/examples/Chapter8/jpqlExamples/src/servlet/examples/servlet/ClientServlet.java @@ -0,0 +1,353 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Arrays; +import java.util.List; + +import javax.annotation.Resource; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.PersistenceUnit; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.transaction.UserTransaction; + +public class ClientServlet extends HttpServlet { + + private final String TITLE = + "Chapter 8: Query Language"; + + //@PersistenceContext(unitName="jpqlExamples") + //private EntityManager em; + @PersistenceUnit(unitName="jpqlExamples") + private EntityManagerFactory emf; + + @Resource + private UserTransaction tx; + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + + // check the requested query type and execute + String query = request.getParameter("query"); + if (query.equals("dynamic")) { + String queryString = request.getParameter("queryString"); + executeAndPrintQuery(queryString, out); + } else if (query.equals("SELECT1")) { + executeAndPrintQuery("SELECT e " + + "FROM Employee e", out); + } else if (query.equals("SELECT2")) { + executeAndPrintQuery("SELECT d " + + "FROM Department d", out); + } else if (query.equals("SELECT3")) { + executeAndPrintQuery("SELECT OBJECT(d) " + + "FROM Department d", out); + } else if (query.equals("SELECT4")) { + executeAndPrintQuery("SELECT e.name " + + "FROM Employee e", out); + } else if (query.equals("SELECT5")) { + executeAndPrintQuery("SELECT e.department " + + "FROM Employee e", out); + } else if (query.equals("SELECT6")) { + executeAndPrintQuery("SELECT DISTINCT e.department " + + "FROM Employee e", out); + } else if (query.equals("SELECT7")) { + executeAndPrintQuery("SELECT d.employees " + + "FROM Department d", out); + } else if (query.equals("SELECT8")) { + executeAndPrintQuery("SELECT e.name, e.salary " + + "FROM Employee e", out); + } else if (query.equals("SELECT9")) { + executeAndPrintQuery("SELECT NEW examples.model.EmployeeDetails(e.name, e.salary, e.department.name) " + + "FROM Employee e", out); + } else if (query.equals("SELECT10")) { + executeAndPrintQuery("SELECT p " + + "FROM Project p " + + "WHERE p.employees IS NOT EMPTY", out); + } else if (query.equals("FROM1")) { + executeAndPrintQuery("SELECT p " + + "FROM Employee e JOIN e.phones p", out); + } else if (query.equals("FROM2")) { + executeAndPrintQuery("SELECT DISTINCT p " + + "FROM Employee e, IN(e.phones) p", out); + } else if (query.equals("FROM3")) { + executeAndPrintQuery("SELECT p.number " + + "FROM Employee e JOIN e.phones p", out); + } else if (query.equals("FROM4")) { + executeAndPrintQuery("SELECT d " + + "FROM Employee e JOIN e.department d", out); + } else if (query.equals("FROM5")) { + executeAndPrintQuery("SELECT e.department " + + "FROM Employee e", out); + } else if (query.equals("FROM6")) { + executeAndPrintQuery("SELECT DISTINCT e.department " + + "FROM Project p JOIN p.employees e " + + "WHERE p.name = 'Release1' AND e.address.state = 'CA'", out); + } else if (query.equals("FROM7")) { + executeAndPrintQuery("SELECT DISTINCT d " + + "FROM Project p JOIN p.employees e JOIN e.department d JOIN e.address a WHERE p.name = 'Release1' AND a.state = 'CA'", out); + } else if (query.equals("FROM8")) { + executeAndPrintQuery("SELECT DISTINCT d " + + "FROM Department d, Employee e " + + "WHERE d = e.department", out); + } else if (query.equals("FROM9")) { + executeAndPrintQuery("SELECT d, m " + + "FROM Department d, Employee m " + + "WHERE d = m.department AND m.directs IS NOT EMPTY", out); + } else if (query.equals("FROM10")) { + executeAndPrintQuery("SELECT DISTINCT p " + + "FROM Department d JOIN d.employees e JOIN e.projects p", out); + } else if (query.equals("FROM11")) { + executeAndPrintQuery("SELECT e, d " + + "FROM Employee e LEFT JOIN e.department d", out); + } else if (query.equals("FROM12")) { + executeAndPrintQuery("SELECT e " + + "FROM Employee e JOIN FETCH e.address", out); + } else if (query.equals("FROM13")) { + executeAndPrintQuery("SELECT e, a " + + "FROM Employee e JOIN e.address a", out); + } else if (query.equals("FROM14")) { + executeAndPrintQuery("SELECT d " + + "FROM Department d LEFT JOIN FETCH d.employees", out); + } else if (query.equals("FROM15")) { + executeAndPrintQuery("SELECT d, e " + + "FROM Department d LEFT JOIN d.employees e", out); + } else if (query.equals("WHERE1")) { + executeAndPrintQuery("SELECT e " + + "FROM Employee e " + + "WHERE e.salary BETWEEN 40000 AND 45000", out); + } else if (query.equals("WHERE2")) { + executeAndPrintQuery("SELECT e " + + "FROM Employee e " + + "WHERE e.salary >= 40000 AND e.salary <= 45000", out); + } else if (query.equals("WHERE3")) { + executeAndPrintQuery("SELECT d " + + "FROM Department d " + + "WHERE d.name LIKE '__Eng%'", out); + } else if (query.equals("WHERE4")) { + executeAndPrintQuery("SELECT d " + + "FROM Department d " + + "WHERE d.name LIKE 'QA\\_%' ESCAPE '\\'", out); + } else if (query.equals("WHERE5")) { + executeAndPrintQuery("SELECT e " + + "FROM Employee e " + + "WHERE e.salary = (SELECT MAX(e2.salary) FROM Employee e2)", out); + } else if (query.equals("WHERE6")) { + executeAndPrintQuery("SELECT e " + + "FROM Employee e " + + "WHERE EXISTS (SELECT p FROM Phone p WHERE p.employee = e AND p.type = 'Cell')", out); + } else if (query.equals("WHERE7")) { + executeAndPrintQuery("SELECT e " + + "FROM Employee e " + + "WHERE EXISTS (SELECT p FROM e.phones p WHERE p.type = 'Cell')", out); + } else if (query.equals("WHERE8")) { + executeAndPrintQuery("SELECT e " + + "FROM Employee e " + + "WHERE e.address.state IN ('NY', 'CA')", out); + } else if (query.equals("WHERE9")) { + executeAndPrintQuery("SELECT e " + + "FROM Employee e " + + "WHERE e.department IN (SELECT DISTINCT d " + + "FROM Department d JOIN d.employees de JOIN de.projects p " + + "WHERE p.name LIKE 'QA%')", out); + } else if (query.equals("WHERE10")) { + executeAndPrintQuery("SELECT p " + + "FROM Phone p " + + "WHERE p.type NOT IN ('Office', 'Home')", out); + } else if (query.equals("WHERE11")) { + executeAndPrintQuery("SELECT e " + + "FROM Employee e " + + "WHERE e.directs IS NOT EMPTY", out); + } else if (query.equals("WHERE12")) { + executeAndPrintQuery("SELECT m " + + "FROM Employee m " + + "WHERE (SELECT COUNT(e) " + + "FROM Employee e " + + "WHERE e.manager = m) > 0", out); + } else if (query.equals("WHERE13")) { + executeAndPrintQuery("SELECT e " + + "FROM Employee e " + + "WHERE e MEMBER OF e.directs", out); + } else if (query.equals("WHERE14")) { + executeAndPrintQuery("SELECT e " + + "FROM Employee e " + + "WHERE NOT EXISTS (SELECT p " + + "FROM e.phones p " + + "WHERE p.type = 'Cell')", out); + } else if (query.equals("WHERE15")) { + executeAndPrintQuery("SELECT e " + + "FROM Employee e " + + "WHERE e.directs IS NOT EMPTY AND " + + "e.salary < ALL (SELECT d.salary " + + "FROM e.directs d)", out); + } else if (query.equals("WHERE16")) { + executeAndPrintQuery("SELECT e " + + "FROM Employee e " + + "WHERE e.department = ANY (SELECT DISTINCT d FROM Department d JOIN d.employees de JOIN de.projects p " + + "WHERE p.name LIKE 'QA%')", out); + } else if (query.equals("WHERE17")) { + executeAndPrintQuery("SELECT d " + + "FROM Department d " + + "WHERE SIZE(d.employees) = 2", out); + } else if (query.equals("WHERE18")) { + executeAndPrintQuery("SELECT d " + + "FROM Department d " + + "WHERE (SELECT COUNT(e) " + + "FROM d.employees e) = 2", out); + } else if (query.equals("ORDERBY1")) { + executeAndPrintQuery("SELECT e " + + "FROM Employee e " + + "ORDER BY e.name DESC", out); + } else if (query.equals("ORDERBY2")) { + executeAndPrintQuery("SELECT e " + + "FROM Employee e JOIN e.department d " + + "ORDER BY d.name, e.name DESC", out); + } else if (query.equals("ORDERBY3")) { + executeAndPrintQuery("SELECT e.name " + + "FROM Employee e " + + "ORDER BY e.salary DESC", out); + } else if (query.equals("Agg1")) { + executeAndPrintQuery("SELECT AVG(e.salary) " + + "FROM Employee e", out); + } else if (query.equals("Agg2")) { + executeAndPrintQuery("SELECT d.name, AVG(e.salary) " + + "FROM Department d JOIN d.employees e " + + "GROUP BY d.name", out); + } else if (query.equals("Agg3")) { + executeAndPrintQuery("SELECT d.name, AVG(e.salary) " + + "FROM Department d JOIN d.employees e " + + "WHERE e.directs IS EMPTY " + + "GROUP BY d.name", out); + } else if (query.equals("Agg4")) { + executeAndPrintQuery("SELECT d.name, AVG(e.salary) " + + "FROM Department d JOIN d.employees e " + + "WHERE e.directs IS EMPTY " + + "GROUP BY d.name " + + "HAVING AVG(e.salary) > 50000", out); + } else if (query.equals("Agg5")) { + executeAndPrintQuery("SELECT d.name, e.salary " + + "FROM Department d JOIN d.employees e " + + "WHERE e.directs IS EMPTY", out); + } else if (query.equals("Agg6")) { + executeAndPrintQuery("SELECT e, COUNT(p), COUNT(DISTINCT p.type) " + + "FROM Employee e JOIN e.phones p " + + "GROUP BY e", out); + } else if (query.equals("GROUPBY1")) { + executeAndPrintQuery("SELECT d.name, COUNT(e) " + + "FROM Department d JOIN d.employees e " + + "GROUP BY d.name", out); + } else if (query.equals("GROUPBY2")) { + executeAndPrintQuery("SELECT d.name, COUNT(e), AVG(e.salary) " + + "FROM Department d JOIN d.employees e " + + "GROUP BY d.name", out); + } else if (query.equals("GROUPBY3")) { + executeAndPrintQuery("SELECT d.name, e.salary, COUNT(p) " + + "FROM Department d JOIN d.employees e JOIN e.projects p " + + "GROUP BY d.name, e.salary", out); + } else if (query.equals("GROUPBY4")) { + executeAndPrintQuery("SELECT COUNT(e), AVG(e.salary) " + + "FROM Employee e", out); + } else if (query.equals("HAVING")) { + executeAndPrintQuery("SELECT e, COUNT(p) " + + "FROM Employee e JOIN e.projects p " + + "GROUP BY e " + + "HAVING COUNT(p) >= 2", out); + } else if (query.equals("UPDATE1")) { + executeBulkQuery("UPDATE Employee e " + + "SET e.salary = 60000 " + + "WHERE e.salary = 55000", out); + } else if (query.equals("UPDATE2")) { + executeBulkQuery("UPDATE Employee e " + + "SET e.salary = e.salary + 5000 " + + "WHERE EXISTS (SELECT p " + + "FROM e.projects p " + + "WHERE p.name = 'Release1')", out); + } else if (query.equals("UPDATE3")) { + executeBulkQuery("UPDATE Phone p " + + "SET p.number = CONCAT('288', SUBSTRING(p.number, LOCATE(p.number, '-'), 4)), " + + "p.type = 'Business' " + + "WHERE p.employee.address.city = 'New York' AND p.type = 'Office'", out); + } else if (query.equals("DELETE")) { + executeBulkQuery("DELETE FROM Employee e " + + "WHERE e.department IS NULL", out); + } + + printHtmlFooter(out); + } + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doGet(request, response); + } + + private void executeAndPrintQuery(String queryString, PrintWriter out) { + EntityManager em = emf.createEntityManager(); + try { + Query query = em.createQuery(queryString); + printQueryResult(queryString, query.getResultList(), out); + } finally { + em.close(); + } + } + + private void executeBulkQuery(String queryString, PrintWriter out) { + EntityManager em = emf.createEntityManager(); + try { + tx.begin(); + em.createQuery(queryString).executeUpdate(); + tx.commit(); + out.println("EJB QL: " + queryString + "
Done."); + } catch (Exception e) { + throw new RuntimeException(e); + } finally { + em.close(); + } + } + + + private void printQueryResult(String queryString, List result, PrintWriter out) { + out.println(""); + out.println(""); + out.println(""); + if (result.isEmpty()) { + out.println(""); + } else { + for (Object o : result) { + out.println(""); + } + } + out.println("
EJB QL: " + queryString + "
Result:
No results Found
" + resultAsString(o) + "
"); + } + + + private String resultAsString(Object o) { + if (o instanceof Object[]) { + return Arrays.asList((Object[])o).toString(); + } else { + return String.valueOf(o); + } + } + + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println("
"); + out.println("Back"); + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter8/jpqlExamples/undeploy.bat b/examples/Chapter8/jpqlExamples/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter8/jpqlExamples/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter9/01-employeeSearchService/build.xml b/examples/Chapter9/01-employeeSearchService/build.xml new file mode 100644 index 0000000..882c4ee --- /dev/null +++ b/examples/Chapter9/01-employeeSearchService/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter9/01-employeeSearchService/deploy.bat b/examples/Chapter9/01-employeeSearchService/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter9/01-employeeSearchService/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter9/01-employeeSearchService/etc/persistence/META-INF/persistence.xml b/examples/Chapter9/01-employeeSearchService/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..b49f95b --- /dev/null +++ b/examples/Chapter9/01-employeeSearchService/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,11 @@ + + + jdbc/employeeSearchService + + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/01-employeeSearchService/etc/sql/db.sql b/examples/Chapter9/01-employeeSearchService/etc/sql/db.sql new file mode 100644 index 0000000..4434224 --- /dev/null +++ b/examples/Chapter9/01-employeeSearchService/etc/sql/db.sql @@ -0,0 +1,95 @@ +DROP TABLE DEPARTMENT; +DROP TABLE PROJECT; +DROP TABLE PROJECT_EMPLOYEE; +DROP TABLE EMPLOYEE; +DROP TABLE PHONE; +DROP TABLE ADDRESS; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE PROJECT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE PROJECT_EMPLOYEE (EMPLOYEES_ID INTEGER, PROJECTS_ID INTEGER); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, STARTDATE DATE, ADDRESS_ID INTEGER, DEPT_ID INTEGER, MANAGER_ID INTEGER, PRIMARY KEY (ID)); +CREATE TABLE PHONE (ID BIGINT NOT NULL, NUMBER VARCHAR(255), TYPE VARCHAR(255), EMPLOYEE_ID INTEGER, PRIMARY KEY (ID)); +CREATE TABLE ADDRESS (ID INTEGER NOT NULL, CITY VARCHAR(255), STATE VARCHAR(255), STREET VARCHAR(255), ZIP VARCHAR(255), PRIMARY KEY (ID)); + + +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (1, 'New York', 'NY', '123 Apple Tree Cr.', '10001'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (2, 'Manhattan', 'NY', '654 Stanton Way.', '10003'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (3, 'New York', 'NY', '99 Queen St.', '10001'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (4, 'Redwood Shores', 'CA', '445 McDonell Cr.', '90123'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (5, 'San Jose', 'CA', '624 Hamilton Dr.', '90123'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (6, 'San Jose', 'CA', '724 Coventry Rd.', '90123'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (7, 'San Francisco', 'CA', '77 Manchester Blvd.', '90123'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (8, 'Moorestown', 'NJ', '53 King St.', '08057'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (9, 'New York', 'NY', '14 Industrial Ave.', '10001'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (10, 'Redwood Shores', 'CA', '777 High Tech Ln.', '90123'); + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'QA'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'Accounting'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (4, 'CAEngOtt'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (5, 'USEngCal'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (6, 'CADocOtt'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (7, 'QA_East'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (8, 'QANorth'); + +INSERT INTO PROJECT (ID, NAME) VALUES (1, 'Design Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (2, 'Release1'); +INSERT INTO PROJECT (ID, NAME) VALUES (3, 'Test Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (4, 'Implement Release3'); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (1, 'John', 55000, {d '2001-01-01'}, 1, 2, 9); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (2, 'Rob', 53000, {d '2001-05-23'}, 2, 2, 9); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (3, 'Peter', 40000, {d '2002-08-06'}, 3, 2, 9); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (4, 'Frank', 41000, {d '2003-02-17'}, 4, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (5, 'Scott', 60000, {d '2004-11-14'}, 5, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (6, 'Sue', 62000, {d '2005-08-18'}, 6, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (7, 'Stephanie', 54000, {d '2006-06-07'}, 7, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (8, 'Jennifer', 45000, {d '1999-08-11'}, 8, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (9, 'Sarah', 52000, {d '2002-04-26'}, 9, 2, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (10, 'Joan', 59000, {d '2003-04-16'}, 10, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (11, 'Marcus', 35000, {d '1995-07-22'}, NULL, NULL, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (12, 'Joe', 36000, {d '1995-07-22'}, NULL, 3, 11); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (13, 'Jack', 43000, {d '1995-07-22'}, NULL, 3, NULL); + +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (1, '(212)555-1234', 'Office', 1); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (2, '(212)555-9843', 'Home', 1); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (3, '(315)555-6253', 'Office', 2); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (4, '(516)555-9837', 'Office', 3); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (5, '(516)555-2034', 'Cell', 3); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (6, '(650)555-7583', 'Office', 4); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (7, '(650)555-5345', 'Home', 4); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (8, '(650)555-9386', 'Office', 5); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (9, '(650)555-4885', 'Cell', 5); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (10, '(650)555-3836', 'Office', 6); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (11, '(650)555-0985', 'Home', 6); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (12, '(650)555-1946', 'Cell', 6); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (13, '(650)555-4759', 'Office', 7); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (14, '(650)555-4757', 'Home', 7); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (15, '(650)555-6753', 'Office', 8); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (16, '(585)555-0693', 'Office', 9); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (17, '(585)555-3098', 'Home', 9); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (18, '(585)555-1457', 'Cell', 9); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (19, '(650)555-9838', 'Office', 10); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (20, '(650)555-2346', 'Home', 10); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (21, '(650)555-9874', 'Cell', 10); + +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (1, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (4, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (7, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 3); \ No newline at end of file diff --git a/examples/Chapter9/01-employeeSearchService/etc/web/WEB-INF/web.xml b/examples/Chapter9/01-employeeSearchService/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..9eebc68 --- /dev/null +++ b/examples/Chapter9/01-employeeSearchService/etc/web/WEB-INF/web.xml @@ -0,0 +1,16 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + + \ No newline at end of file diff --git a/examples/Chapter9/01-employeeSearchService/src/model/examples/model/Address.java b/examples/Chapter9/01-employeeSearchService/src/model/examples/model/Address.java new file mode 100644 index 0000000..c1cad79 --- /dev/null +++ b/examples/Chapter9/01-employeeSearchService/src/model/examples/model/Address.java @@ -0,0 +1,64 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Address { + @Id + private int id; + private String street; + private String city; + private String state; + private String zip; + + public Address() {} + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getStreet() { + return street; + } + + public void setStreet(String address) { + this.street = address; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getZip() { + return zip; + } + + public void setZip(String zip) { + this.zip = zip; + } + public String toString() { + return "Address id: " + getId() + + ", street: " + getStreet() + + ", city: " + getCity() + + ", state: " + getState() + + ", zip: " + getZip(); + } + +} diff --git a/examples/Chapter9/01-employeeSearchService/src/model/examples/model/Department.java b/examples/Chapter9/01-employeeSearchService/src/model/examples/model/Department.java new file mode 100644 index 0000000..3deeac5 --- /dev/null +++ b/examples/Chapter9/01-employeeSearchService/src/model/examples/model/Department.java @@ -0,0 +1,44 @@ +package examples.model; + +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="dept") + private Set employees = new HashSet(); + + public Department() {} + + public int getId() { + return id; + } + + public void setId(int deptNo) { + this.id = deptNo; + } + + public String getName() { + return name; + } + + public void setName(String deptName) { + this.name = deptName; + } + + public Set getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter9/01-employeeSearchService/src/model/examples/model/Employee.java b/examples/Chapter9/01-employeeSearchService/src/model/examples/model/Employee.java new file mode 100644 index 0000000..77985f0 --- /dev/null +++ b/examples/Chapter9/01-employeeSearchService/src/model/examples/model/Employee.java @@ -0,0 +1,163 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToMany; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.OneToOne; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + @Temporal(TemporalType.DATE) + private Date startDate; + + @OneToOne + private Address address; + + @OneToMany(mappedBy="employee") + private Collection phones = new ArrayList(); + + @ManyToOne + private Department dept; + + @ManyToOne + private Employee manager; + + @OneToMany(mappedBy="manager") + private Collection directs = new ArrayList(); + + @ManyToMany(mappedBy="employees") + private Collection projects = new ArrayList(); + //private Project project; + + public Employee() {} + + public Employee(int id) { + this.id = id; + } + + public int getId() { + return id; + } + + public void setId(int empNo) { + this.id = empNo; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public Collection getPhones() { + return phones; + } + + public void addPhone(Phone phone) { + if (!getPhones().contains(phone)) { + getPhones().add(phone); + if (phone.getEmployee() != null) { + phone.getEmployee().getPhones().remove(phone); + } + phone.setEmployee(this); + } + } + + public Department getDept() { + return dept; + } + + public void setDept(Department dept) { + if (this.dept != null) { + this.dept.getEmployees().remove(this); + } + this.dept = dept; + this.dept.getEmployees().add(this); + } + + public Collection getDirects() { + return directs; + } + + public void addDirect(Employee employee) { + if (!getDirects().contains(employee)) { + getDirects().add(employee); + if (employee.getManager() != null) { + employee.getManager().getDirects().remove(employee); + } + employee.setManager(this); + } + } + + public Employee getManager() { + return manager; + } + + public void setManager(Employee manager) { + this.manager = manager; + } + + public Collection getProjects() { + return projects; + } + + public void addProject(Project project) { + if (!getProjects().contains(project)) { + getProjects().add(project); + } + if (!project.getEmployees().contains(this)) { + project.getEmployees().add(this); + } + } + + +// public Project getProject() { return project; } +// public void setProject(Project aProject) { project = aProject; } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary() + + ", city: " + ((getAddress() == null) ? null : getAddress().getCity()) + + ", deptName: " + ((getDept() == null) ? null : getDept().getName()); + } + +} diff --git a/examples/Chapter9/01-employeeSearchService/src/model/examples/model/Phone.java b/examples/Chapter9/01-employeeSearchService/src/model/examples/model/Phone.java new file mode 100644 index 0000000..8269374 --- /dev/null +++ b/examples/Chapter9/01-employeeSearchService/src/model/examples/model/Phone.java @@ -0,0 +1,54 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToOne; + +@Entity +public class Phone { + @Id + private long id; + private String number; + private String type; + @OneToOne Employee employee; + + public Phone() {} + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getNumber() { + return number; + } + + public void setNumber(String phoneNo) { + this.number = phoneNo; + } + + public String getType() { + return type; + } + + public void setType(String phoneType) { + this.type = phoneType; + } + + public Employee getEmployee() { + return employee; + } + + public void setEmployee(Employee employee) { + this.employee = employee; + } + + public String toString() { + return "Phone id: " + getId() + + ", no: " + getNumber() + + ", type: " + getType(); + } +} diff --git a/examples/Chapter9/01-employeeSearchService/src/model/examples/model/Project.java b/examples/Chapter9/01-employeeSearchService/src/model/examples/model/Project.java new file mode 100644 index 0000000..7a34761 --- /dev/null +++ b/examples/Chapter9/01-employeeSearchService/src/model/examples/model/Project.java @@ -0,0 +1,54 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToMany; + +@Entity +public class Project { + @Id + protected int id; + protected String name; + @ManyToMany + protected Collection employees = new ArrayList(); + + public Project() {} + + public int getId() { + return id; + } + + public void setId(int projectNo) { + this.id = projectNo; + } + + public String getName() { + return name; + } + + public void setName(String projectName) { + this.name = projectName; + } + + public Collection getEmployees() { + return employees; + } + + public void addEmployee(Employee employee) { + if (!getEmployees().contains(employee)) { + getEmployees().add(employee); + } + if (!employee.getProjects().contains(this)) { + employee.getProjects().add(this); + } + } + + public String toString() { + return getClass().getName().substring(getClass().getName().lastIndexOf('.')+1) + + " no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter9/01-employeeSearchService/src/model/examples/stateless/SearchService.java b/examples/Chapter9/01-employeeSearchService/src/model/examples/stateless/SearchService.java new file mode 100644 index 0000000..1b4c8aa --- /dev/null +++ b/examples/Chapter9/01-employeeSearchService/src/model/examples/stateless/SearchService.java @@ -0,0 +1,108 @@ +package examples.stateless; + +import examples.model.Employee; +import examples.model.Project; +import java.util.ArrayList; +import java.util.List; +import java.io.PrintWriter; +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Join; +import javax.persistence.criteria.JoinType; +import javax.persistence.criteria.ParameterExpression; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; +import javax.persistence.Query; +import java.util.Collection; + + +@Stateless +public class SearchService { + @PersistenceContext(unitName="EmployeeHR") + EntityManager em; + + public EntityManager getEntityManager() { + return em; + } + + public Employee createEmployee(int id, String name, long salary) { + Employee emp = new Employee(id); + emp.setName(name); + emp.setSalary(salary); + getEntityManager().persist(emp); + return emp; + } + + public void removeEmployee(int id) { + Employee emp = findEmployee(id); + if (emp != null) { + getEntityManager().remove(emp); + } + } + + public Employee changeEmployeeSalary(int id, long newSalary) { + Employee emp = findEmployee(id); + if (emp != null) { + emp.setSalary(newSalary); + } + return emp; + } + + public Employee findEmployee(int id) { + return getEntityManager().find(Employee.class, id); + } + + public Collection findAllEmployees() { + Query query = getEntityManager().createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } + + public List findEmployees(String name, String deptName, + String projectName, String city, PrintWriter out) { + + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery c = cb.createQuery(Employee.class); + Root emp = c.from(Employee.class); + c.select(emp); + c.distinct(true); + Join project = emp.join("projects", JoinType.LEFT); + + List criteria = new ArrayList(); + if (name != null) { + ParameterExpression p = cb.parameter(String.class, "name"); + criteria.add(cb.equal(emp.get("name"), p)); + } + if (deptName != null) { + ParameterExpression p = cb.parameter(String.class, "dept"); + criteria.add(cb.equal(emp.get("dept").get("name"), p)); + } + if (projectName != null) { + ParameterExpression p = cb.parameter(String.class, "project"); + criteria.add(cb.equal(project.get("name"), p)); + } + if (city != null) { + ParameterExpression p = cb.parameter(String.class, "city"); + criteria.add(cb.equal(emp.get("address").get("city"), p)); + } + + if (criteria.size() == 0) { + throw new RuntimeException("no criteria"); + } else if (criteria.size() == 1) { + c.where(criteria.get(0)); + } else { + c.where(cb.and(criteria.toArray(new Predicate[0]))); + } + + TypedQuery q = em.createQuery(c); + out.println(c); + if (name != null) { q.setParameter("name", name); } + if (deptName != null) { q.setParameter("dept", deptName); } + if (project != null) { q.setParameter("project", projectName); } + if (city != null) { q.setParameter("city", city); } + return q.getResultList(); + } +} diff --git a/examples/Chapter9/01-employeeSearchService/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter9/01-employeeSearchService/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..a195ee7 --- /dev/null +++ b/examples/Chapter9/01-employeeSearchService/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,120 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.model.Project; +import examples.stateless.SearchService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 9: Employee Search Service using Criteria API Example"; + + private final String DESCRIPTION = + "This example allows you to search for employees using one or more query criteria."; + + + // inject a reference to the SearchService slsb + @EJB SearchService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("FindEmployees")) { + out.println("CriteriaQuery: "); + String name = request.getParameter("name"); + if (name.equals("")) name = null; + String dept = request.getParameter("dept"); + if (dept.equals("")) dept = null; + String project = request.getParameter("project"); + if (project.equals("")) project = null; + String city = request.getParameter("city"); + if (city.equals("")) city = null; + + Collection emps = service.findEmployees(name, dept, project, city, out); + + if (emps.isEmpty()) { + out.println("
No Employees found "); + } else { + out.println("
Found Employees:
"); + for (Employee emp : emps) { + out.print(emp + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + + // form to find Employees + out.println("

Find Employees

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("" + + ""); + out.println("
Name:(String)
DeptName:(String)
ProjectName:(String)
City:(String)
"); + + // show all Employees + out.println("
"); + out.println("
Employees: "); + Collection emps = service.findAllEmployees(); + for (Employee emp : emps) { + out.println("
" + emp); + } + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter9/01-employeeSearchService/undeploy.bat b/examples/Chapter9/01-employeeSearchService/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter9/01-employeeSearchService/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter9/02-predicateConjunction/build.xml b/examples/Chapter9/02-predicateConjunction/build.xml new file mode 100644 index 0000000..4648464 --- /dev/null +++ b/examples/Chapter9/02-predicateConjunction/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter9/02-predicateConjunction/deploy.bat b/examples/Chapter9/02-predicateConjunction/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter9/02-predicateConjunction/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter9/02-predicateConjunction/etc/persistence/META-INF/persistence.xml b/examples/Chapter9/02-predicateConjunction/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..877ba22 --- /dev/null +++ b/examples/Chapter9/02-predicateConjunction/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,11 @@ + + + jdbc/predicateConjunction + + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/02-predicateConjunction/etc/sql/db.sql b/examples/Chapter9/02-predicateConjunction/etc/sql/db.sql new file mode 100644 index 0000000..4434224 --- /dev/null +++ b/examples/Chapter9/02-predicateConjunction/etc/sql/db.sql @@ -0,0 +1,95 @@ +DROP TABLE DEPARTMENT; +DROP TABLE PROJECT; +DROP TABLE PROJECT_EMPLOYEE; +DROP TABLE EMPLOYEE; +DROP TABLE PHONE; +DROP TABLE ADDRESS; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE PROJECT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE PROJECT_EMPLOYEE (EMPLOYEES_ID INTEGER, PROJECTS_ID INTEGER); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, STARTDATE DATE, ADDRESS_ID INTEGER, DEPT_ID INTEGER, MANAGER_ID INTEGER, PRIMARY KEY (ID)); +CREATE TABLE PHONE (ID BIGINT NOT NULL, NUMBER VARCHAR(255), TYPE VARCHAR(255), EMPLOYEE_ID INTEGER, PRIMARY KEY (ID)); +CREATE TABLE ADDRESS (ID INTEGER NOT NULL, CITY VARCHAR(255), STATE VARCHAR(255), STREET VARCHAR(255), ZIP VARCHAR(255), PRIMARY KEY (ID)); + + +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (1, 'New York', 'NY', '123 Apple Tree Cr.', '10001'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (2, 'Manhattan', 'NY', '654 Stanton Way.', '10003'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (3, 'New York', 'NY', '99 Queen St.', '10001'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (4, 'Redwood Shores', 'CA', '445 McDonell Cr.', '90123'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (5, 'San Jose', 'CA', '624 Hamilton Dr.', '90123'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (6, 'San Jose', 'CA', '724 Coventry Rd.', '90123'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (7, 'San Francisco', 'CA', '77 Manchester Blvd.', '90123'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (8, 'Moorestown', 'NJ', '53 King St.', '08057'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (9, 'New York', 'NY', '14 Industrial Ave.', '10001'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (10, 'Redwood Shores', 'CA', '777 High Tech Ln.', '90123'); + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'QA'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'Accounting'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (4, 'CAEngOtt'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (5, 'USEngCal'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (6, 'CADocOtt'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (7, 'QA_East'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (8, 'QANorth'); + +INSERT INTO PROJECT (ID, NAME) VALUES (1, 'Design Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (2, 'Release1'); +INSERT INTO PROJECT (ID, NAME) VALUES (3, 'Test Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (4, 'Implement Release3'); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (1, 'John', 55000, {d '2001-01-01'}, 1, 2, 9); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (2, 'Rob', 53000, {d '2001-05-23'}, 2, 2, 9); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (3, 'Peter', 40000, {d '2002-08-06'}, 3, 2, 9); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (4, 'Frank', 41000, {d '2003-02-17'}, 4, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (5, 'Scott', 60000, {d '2004-11-14'}, 5, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (6, 'Sue', 62000, {d '2005-08-18'}, 6, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (7, 'Stephanie', 54000, {d '2006-06-07'}, 7, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (8, 'Jennifer', 45000, {d '1999-08-11'}, 8, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (9, 'Sarah', 52000, {d '2002-04-26'}, 9, 2, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (10, 'Joan', 59000, {d '2003-04-16'}, 10, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (11, 'Marcus', 35000, {d '1995-07-22'}, NULL, NULL, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (12, 'Joe', 36000, {d '1995-07-22'}, NULL, 3, 11); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (13, 'Jack', 43000, {d '1995-07-22'}, NULL, 3, NULL); + +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (1, '(212)555-1234', 'Office', 1); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (2, '(212)555-9843', 'Home', 1); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (3, '(315)555-6253', 'Office', 2); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (4, '(516)555-9837', 'Office', 3); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (5, '(516)555-2034', 'Cell', 3); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (6, '(650)555-7583', 'Office', 4); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (7, '(650)555-5345', 'Home', 4); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (8, '(650)555-9386', 'Office', 5); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (9, '(650)555-4885', 'Cell', 5); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (10, '(650)555-3836', 'Office', 6); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (11, '(650)555-0985', 'Home', 6); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (12, '(650)555-1946', 'Cell', 6); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (13, '(650)555-4759', 'Office', 7); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (14, '(650)555-4757', 'Home', 7); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (15, '(650)555-6753', 'Office', 8); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (16, '(585)555-0693', 'Office', 9); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (17, '(585)555-3098', 'Home', 9); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (18, '(585)555-1457', 'Cell', 9); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (19, '(650)555-9838', 'Office', 10); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (20, '(650)555-2346', 'Home', 10); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (21, '(650)555-9874', 'Cell', 10); + +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (1, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (4, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (7, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 3); \ No newline at end of file diff --git a/examples/Chapter9/02-predicateConjunction/etc/web/WEB-INF/web.xml b/examples/Chapter9/02-predicateConjunction/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..9eebc68 --- /dev/null +++ b/examples/Chapter9/02-predicateConjunction/etc/web/WEB-INF/web.xml @@ -0,0 +1,16 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + + \ No newline at end of file diff --git a/examples/Chapter9/02-predicateConjunction/src/model/examples/model/Address.java b/examples/Chapter9/02-predicateConjunction/src/model/examples/model/Address.java new file mode 100644 index 0000000..c1cad79 --- /dev/null +++ b/examples/Chapter9/02-predicateConjunction/src/model/examples/model/Address.java @@ -0,0 +1,64 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Address { + @Id + private int id; + private String street; + private String city; + private String state; + private String zip; + + public Address() {} + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getStreet() { + return street; + } + + public void setStreet(String address) { + this.street = address; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getZip() { + return zip; + } + + public void setZip(String zip) { + this.zip = zip; + } + public String toString() { + return "Address id: " + getId() + + ", street: " + getStreet() + + ", city: " + getCity() + + ", state: " + getState() + + ", zip: " + getZip(); + } + +} diff --git a/examples/Chapter9/02-predicateConjunction/src/model/examples/model/Department.java b/examples/Chapter9/02-predicateConjunction/src/model/examples/model/Department.java new file mode 100644 index 0000000..3deeac5 --- /dev/null +++ b/examples/Chapter9/02-predicateConjunction/src/model/examples/model/Department.java @@ -0,0 +1,44 @@ +package examples.model; + +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="dept") + private Set employees = new HashSet(); + + public Department() {} + + public int getId() { + return id; + } + + public void setId(int deptNo) { + this.id = deptNo; + } + + public String getName() { + return name; + } + + public void setName(String deptName) { + this.name = deptName; + } + + public Set getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter9/02-predicateConjunction/src/model/examples/model/Employee.java b/examples/Chapter9/02-predicateConjunction/src/model/examples/model/Employee.java new file mode 100644 index 0000000..77985f0 --- /dev/null +++ b/examples/Chapter9/02-predicateConjunction/src/model/examples/model/Employee.java @@ -0,0 +1,163 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToMany; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.OneToOne; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + @Temporal(TemporalType.DATE) + private Date startDate; + + @OneToOne + private Address address; + + @OneToMany(mappedBy="employee") + private Collection phones = new ArrayList(); + + @ManyToOne + private Department dept; + + @ManyToOne + private Employee manager; + + @OneToMany(mappedBy="manager") + private Collection directs = new ArrayList(); + + @ManyToMany(mappedBy="employees") + private Collection projects = new ArrayList(); + //private Project project; + + public Employee() {} + + public Employee(int id) { + this.id = id; + } + + public int getId() { + return id; + } + + public void setId(int empNo) { + this.id = empNo; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public Collection getPhones() { + return phones; + } + + public void addPhone(Phone phone) { + if (!getPhones().contains(phone)) { + getPhones().add(phone); + if (phone.getEmployee() != null) { + phone.getEmployee().getPhones().remove(phone); + } + phone.setEmployee(this); + } + } + + public Department getDept() { + return dept; + } + + public void setDept(Department dept) { + if (this.dept != null) { + this.dept.getEmployees().remove(this); + } + this.dept = dept; + this.dept.getEmployees().add(this); + } + + public Collection getDirects() { + return directs; + } + + public void addDirect(Employee employee) { + if (!getDirects().contains(employee)) { + getDirects().add(employee); + if (employee.getManager() != null) { + employee.getManager().getDirects().remove(employee); + } + employee.setManager(this); + } + } + + public Employee getManager() { + return manager; + } + + public void setManager(Employee manager) { + this.manager = manager; + } + + public Collection getProjects() { + return projects; + } + + public void addProject(Project project) { + if (!getProjects().contains(project)) { + getProjects().add(project); + } + if (!project.getEmployees().contains(this)) { + project.getEmployees().add(this); + } + } + + +// public Project getProject() { return project; } +// public void setProject(Project aProject) { project = aProject; } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary() + + ", city: " + ((getAddress() == null) ? null : getAddress().getCity()) + + ", deptName: " + ((getDept() == null) ? null : getDept().getName()); + } + +} diff --git a/examples/Chapter9/02-predicateConjunction/src/model/examples/model/Phone.java b/examples/Chapter9/02-predicateConjunction/src/model/examples/model/Phone.java new file mode 100644 index 0000000..8269374 --- /dev/null +++ b/examples/Chapter9/02-predicateConjunction/src/model/examples/model/Phone.java @@ -0,0 +1,54 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToOne; + +@Entity +public class Phone { + @Id + private long id; + private String number; + private String type; + @OneToOne Employee employee; + + public Phone() {} + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getNumber() { + return number; + } + + public void setNumber(String phoneNo) { + this.number = phoneNo; + } + + public String getType() { + return type; + } + + public void setType(String phoneType) { + this.type = phoneType; + } + + public Employee getEmployee() { + return employee; + } + + public void setEmployee(Employee employee) { + this.employee = employee; + } + + public String toString() { + return "Phone id: " + getId() + + ", no: " + getNumber() + + ", type: " + getType(); + } +} diff --git a/examples/Chapter9/02-predicateConjunction/src/model/examples/model/Project.java b/examples/Chapter9/02-predicateConjunction/src/model/examples/model/Project.java new file mode 100644 index 0000000..43b8c47 --- /dev/null +++ b/examples/Chapter9/02-predicateConjunction/src/model/examples/model/Project.java @@ -0,0 +1,55 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.ManyToMany; + +@Entity +public class Project { + @Id + protected int id; + protected String name; + @ManyToMany + protected Collection employees = new ArrayList(); + + public Project() {} + + public int getId() { + return id; + } + + public void setId(int projectNo) { + this.id = projectNo; + } + + public String getName() { + return name; + } + + public void setName(String projectName) { + this.name = projectName; + } + + public Collection getEmployees() { + return employees; + } + + public void addEmployee(Employee employee) { + if (!getEmployees().contains(employee)) { + getEmployees().add(employee); + } + if (!employee.getProjects().contains(this)) { + employee.getProjects().add(this); + } + } + + public String toString() { + return getClass().getName().substring(getClass().getName().lastIndexOf('.')+1) + + " no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter9/02-predicateConjunction/src/model/examples/stateless/SearchService.java b/examples/Chapter9/02-predicateConjunction/src/model/examples/stateless/SearchService.java new file mode 100644 index 0000000..701b793 --- /dev/null +++ b/examples/Chapter9/02-predicateConjunction/src/model/examples/stateless/SearchService.java @@ -0,0 +1,102 @@ +package examples.stateless; + +import examples.model.Employee; +import examples.model.Project; +import java.util.ArrayList; +import java.util.List; +import java.io.PrintWriter; +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Join; +import javax.persistence.criteria.JoinType; +import javax.persistence.criteria.ParameterExpression; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; +import javax.persistence.Query; +import java.util.Collection; + + +@Stateless +public class SearchService { + @PersistenceContext(unitName="EmployeeHR") + EntityManager em; + + public EntityManager getEntityManager() { + return em; + } + + public Employee createEmployee(int id, String name, long salary) { + Employee emp = new Employee(id); + emp.setName(name); + emp.setSalary(salary); + getEntityManager().persist(emp); + return emp; + } + + public void removeEmployee(int id) { + Employee emp = findEmployee(id); + if (emp != null) { + getEntityManager().remove(emp); + } + } + + public Employee changeEmployeeSalary(int id, long newSalary) { + Employee emp = findEmployee(id); + if (emp != null) { + emp.setSalary(newSalary); + } + return emp; + } + + public Employee findEmployee(int id) { + return getEntityManager().find(Employee.class, id); + } + + public Collection findAllEmployees() { + Query query = getEntityManager().createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } + + public List findEmployees(String name, String deptName, + String projectName, String city, PrintWriter out) { + + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery c = cb.createQuery(Employee.class); + Root emp = c.from(Employee.class); + c.select(emp); + c.distinct(true); + Join project = emp.join("projects", JoinType.LEFT); + + Predicate criteria = cb.conjunction(); + if (name != null) { + ParameterExpression p = cb.parameter(String.class, "name"); + criteria = cb.and(criteria, cb.equal(emp.get("name"), p)); + } + if (deptName != null) { + ParameterExpression p = cb.parameter(String.class, "dept"); + criteria = cb.and(criteria, cb.equal(emp.get("dept").get("name"), p)); + } + if (projectName != null) { + ParameterExpression p = cb.parameter(String.class, "project"); + criteria = cb.and(criteria, cb.equal(project.get("name"), p)); + } + if (city != null) { + ParameterExpression p = cb.parameter(String.class, "city"); + criteria = cb.and(criteria, cb.equal(emp.get("address").get("city"), p)); + } + c.where(criteria); + + TypedQuery q = em.createQuery(c); + out.println(c); + if (name != null) { q.setParameter("name", name); } + if (deptName != null) { q.setParameter("dept", deptName); } + if (project != null) { q.setParameter("project", projectName); } + if (city != null) { q.setParameter("city", city); } + return q.getResultList(); + } + +} diff --git a/examples/Chapter9/02-predicateConjunction/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter9/02-predicateConjunction/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..de3f4e9 --- /dev/null +++ b/examples/Chapter9/02-predicateConjunction/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,120 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.model.Project; +import examples.stateless.SearchService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 9: Employee Search Service using Criteria Predicate Conjunction"; + + private final String DESCRIPTION = + "This example allows you to search for employees using one or more query criteria."; + + + // inject a reference to the SearchService slsb + @EJB SearchService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("FindEmployees")) { + out.println("CriteriaQuery: "); + String name = request.getParameter("name"); + if (name.equals("")) name = null; + String dept = request.getParameter("dept"); + if (dept.equals("")) dept = null; + String project = request.getParameter("project"); + if (project.equals("")) project = null; + String city = request.getParameter("city"); + if (city.equals("")) city = null; + + Collection emps = service.findEmployees(name, dept, project, city, out); + + if (emps.isEmpty()) { + out.println("
No Employees found "); + } else { + out.println("
Found Employees:
"); + for (Employee emp : emps) { + out.print(emp + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println(""); + + // form to find Employees + out.println("

Find Employees

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("" + + ""); + out.println("
Name:(String)
DeptName:(String)
ProjectName:(String)
City:(String)
"); + + // show all Employees + out.println("
"); + out.println("
Employees: "); + Collection emps = service.findAllEmployees(); + for (Employee emp : emps) { + out.println("
" + emp); + } + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter9/02-predicateConjunction/undeploy.bat b/examples/Chapter9/02-predicateConjunction/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter9/02-predicateConjunction/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter9/03-empSearchSubQuery/build.xml b/examples/Chapter9/03-empSearchSubQuery/build.xml new file mode 100644 index 0000000..8b61343 --- /dev/null +++ b/examples/Chapter9/03-empSearchSubQuery/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter9/03-empSearchSubQuery/deploy.bat b/examples/Chapter9/03-empSearchSubQuery/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter9/03-empSearchSubQuery/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter9/03-empSearchSubQuery/etc/persistence/META-INF/persistence.xml b/examples/Chapter9/03-empSearchSubQuery/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..89802e0 --- /dev/null +++ b/examples/Chapter9/03-empSearchSubQuery/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,11 @@ + + + jdbc/empSearchSubquery + + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/03-empSearchSubQuery/etc/sql/db.sql b/examples/Chapter9/03-empSearchSubQuery/etc/sql/db.sql new file mode 100644 index 0000000..4434224 --- /dev/null +++ b/examples/Chapter9/03-empSearchSubQuery/etc/sql/db.sql @@ -0,0 +1,95 @@ +DROP TABLE DEPARTMENT; +DROP TABLE PROJECT; +DROP TABLE PROJECT_EMPLOYEE; +DROP TABLE EMPLOYEE; +DROP TABLE PHONE; +DROP TABLE ADDRESS; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE PROJECT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE PROJECT_EMPLOYEE (EMPLOYEES_ID INTEGER, PROJECTS_ID INTEGER); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, STARTDATE DATE, ADDRESS_ID INTEGER, DEPT_ID INTEGER, MANAGER_ID INTEGER, PRIMARY KEY (ID)); +CREATE TABLE PHONE (ID BIGINT NOT NULL, NUMBER VARCHAR(255), TYPE VARCHAR(255), EMPLOYEE_ID INTEGER, PRIMARY KEY (ID)); +CREATE TABLE ADDRESS (ID INTEGER NOT NULL, CITY VARCHAR(255), STATE VARCHAR(255), STREET VARCHAR(255), ZIP VARCHAR(255), PRIMARY KEY (ID)); + + +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (1, 'New York', 'NY', '123 Apple Tree Cr.', '10001'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (2, 'Manhattan', 'NY', '654 Stanton Way.', '10003'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (3, 'New York', 'NY', '99 Queen St.', '10001'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (4, 'Redwood Shores', 'CA', '445 McDonell Cr.', '90123'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (5, 'San Jose', 'CA', '624 Hamilton Dr.', '90123'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (6, 'San Jose', 'CA', '724 Coventry Rd.', '90123'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (7, 'San Francisco', 'CA', '77 Manchester Blvd.', '90123'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (8, 'Moorestown', 'NJ', '53 King St.', '08057'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (9, 'New York', 'NY', '14 Industrial Ave.', '10001'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (10, 'Redwood Shores', 'CA', '777 High Tech Ln.', '90123'); + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'QA'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'Accounting'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (4, 'CAEngOtt'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (5, 'USEngCal'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (6, 'CADocOtt'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (7, 'QA_East'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (8, 'QANorth'); + +INSERT INTO PROJECT (ID, NAME) VALUES (1, 'Design Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (2, 'Release1'); +INSERT INTO PROJECT (ID, NAME) VALUES (3, 'Test Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (4, 'Implement Release3'); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (1, 'John', 55000, {d '2001-01-01'}, 1, 2, 9); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (2, 'Rob', 53000, {d '2001-05-23'}, 2, 2, 9); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (3, 'Peter', 40000, {d '2002-08-06'}, 3, 2, 9); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (4, 'Frank', 41000, {d '2003-02-17'}, 4, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (5, 'Scott', 60000, {d '2004-11-14'}, 5, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (6, 'Sue', 62000, {d '2005-08-18'}, 6, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (7, 'Stephanie', 54000, {d '2006-06-07'}, 7, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (8, 'Jennifer', 45000, {d '1999-08-11'}, 8, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (9, 'Sarah', 52000, {d '2002-04-26'}, 9, 2, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (10, 'Joan', 59000, {d '2003-04-16'}, 10, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (11, 'Marcus', 35000, {d '1995-07-22'}, NULL, NULL, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (12, 'Joe', 36000, {d '1995-07-22'}, NULL, 3, 11); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (13, 'Jack', 43000, {d '1995-07-22'}, NULL, 3, NULL); + +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (1, '(212)555-1234', 'Office', 1); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (2, '(212)555-9843', 'Home', 1); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (3, '(315)555-6253', 'Office', 2); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (4, '(516)555-9837', 'Office', 3); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (5, '(516)555-2034', 'Cell', 3); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (6, '(650)555-7583', 'Office', 4); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (7, '(650)555-5345', 'Home', 4); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (8, '(650)555-9386', 'Office', 5); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (9, '(650)555-4885', 'Cell', 5); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (10, '(650)555-3836', 'Office', 6); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (11, '(650)555-0985', 'Home', 6); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (12, '(650)555-1946', 'Cell', 6); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (13, '(650)555-4759', 'Office', 7); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (14, '(650)555-4757', 'Home', 7); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (15, '(650)555-6753', 'Office', 8); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (16, '(585)555-0693', 'Office', 9); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (17, '(585)555-3098', 'Home', 9); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (18, '(585)555-1457', 'Cell', 9); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (19, '(650)555-9838', 'Office', 10); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (20, '(650)555-2346', 'Home', 10); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (21, '(650)555-9874', 'Cell', 10); + +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (1, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (4, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (7, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 3); \ No newline at end of file diff --git a/examples/Chapter9/03-empSearchSubQuery/etc/web/WEB-INF/web.xml b/examples/Chapter9/03-empSearchSubQuery/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..9eebc68 --- /dev/null +++ b/examples/Chapter9/03-empSearchSubQuery/etc/web/WEB-INF/web.xml @@ -0,0 +1,16 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + + \ No newline at end of file diff --git a/examples/Chapter9/03-empSearchSubQuery/src/model/examples/model/Address.java b/examples/Chapter9/03-empSearchSubQuery/src/model/examples/model/Address.java new file mode 100644 index 0000000..c1cad79 --- /dev/null +++ b/examples/Chapter9/03-empSearchSubQuery/src/model/examples/model/Address.java @@ -0,0 +1,64 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Address { + @Id + private int id; + private String street; + private String city; + private String state; + private String zip; + + public Address() {} + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getStreet() { + return street; + } + + public void setStreet(String address) { + this.street = address; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getZip() { + return zip; + } + + public void setZip(String zip) { + this.zip = zip; + } + public String toString() { + return "Address id: " + getId() + + ", street: " + getStreet() + + ", city: " + getCity() + + ", state: " + getState() + + ", zip: " + getZip(); + } + +} diff --git a/examples/Chapter9/03-empSearchSubQuery/src/model/examples/model/Department.java b/examples/Chapter9/03-empSearchSubQuery/src/model/examples/model/Department.java new file mode 100644 index 0000000..3deeac5 --- /dev/null +++ b/examples/Chapter9/03-empSearchSubQuery/src/model/examples/model/Department.java @@ -0,0 +1,44 @@ +package examples.model; + +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="dept") + private Set employees = new HashSet(); + + public Department() {} + + public int getId() { + return id; + } + + public void setId(int deptNo) { + this.id = deptNo; + } + + public String getName() { + return name; + } + + public void setName(String deptName) { + this.name = deptName; + } + + public Set getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter9/03-empSearchSubQuery/src/model/examples/model/Employee.java b/examples/Chapter9/03-empSearchSubQuery/src/model/examples/model/Employee.java new file mode 100644 index 0000000..0e98b9c --- /dev/null +++ b/examples/Chapter9/03-empSearchSubQuery/src/model/examples/model/Employee.java @@ -0,0 +1,170 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.Id; +import javax.persistence.ManyToMany; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.OneToOne; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + @Temporal(TemporalType.DATE) + private Date startDate; + + @OneToOne + private Address address; + + @OneToMany(mappedBy="employee") + private Collection phones = new ArrayList(); + + @ManyToOne + private Department dept; + + @ManyToOne + private Employee manager; + + @OneToMany(mappedBy="manager") + private Collection directs = new ArrayList(); + + @ManyToMany(mappedBy="employees", fetch=FetchType.EAGER) + private Collection projects = new ArrayList(); + + public Employee() {} + + public Employee(int id) { + this.id = id; + } + + public int getId() { + return id; + } + + public void setId(int empNo) { + this.id = empNo; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public Collection getPhones() { + return phones; + } + + public void addPhone(Phone phone) { + if (!getPhones().contains(phone)) { + getPhones().add(phone); + if (phone.getEmployee() != null) { + phone.getEmployee().getPhones().remove(phone); + } + phone.setEmployee(this); + } + } + + public Department getDept() { + return dept; + } + + public void setDept(Department dept) { + if (this.dept != null) { + this.dept.getEmployees().remove(this); + } + this.dept = dept; + this.dept.getEmployees().add(this); + } + + public Collection getDirects() { + return directs; + } + + public void addDirect(Employee employee) { + if (!getDirects().contains(employee)) { + getDirects().add(employee); + if (employee.getManager() != null) { + employee.getManager().getDirects().remove(employee); + } + employee.setManager(this); + } + } + + public Employee getManager() { + return manager; + } + + public void setManager(Employee manager) { + this.manager = manager; + } + + public Collection getProjects() { + return projects; + } + + Collection getProjectNames() { + Collection names = new ArrayList(); + if (projects != null) { + for (Project p : projects) { + names.add(p.getName()); + } + } + return names; + } + + public void addProject(Project project) { + if (!getProjects().contains(project)) { + getProjects().add(project); + } + if (!project.getEmployees().contains(this)) { + project.getEmployees().add(this); + } + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary() + + ", city: " + ((getAddress() == null) ? null : getAddress().getCity()) + + ", deptName: " + ((getDept() == null) ? null : getDept().getName()) + + ", projects: " + getProjectNames(); + } + +} diff --git a/examples/Chapter9/03-empSearchSubQuery/src/model/examples/model/Phone.java b/examples/Chapter9/03-empSearchSubQuery/src/model/examples/model/Phone.java new file mode 100644 index 0000000..8269374 --- /dev/null +++ b/examples/Chapter9/03-empSearchSubQuery/src/model/examples/model/Phone.java @@ -0,0 +1,54 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToOne; + +@Entity +public class Phone { + @Id + private long id; + private String number; + private String type; + @OneToOne Employee employee; + + public Phone() {} + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getNumber() { + return number; + } + + public void setNumber(String phoneNo) { + this.number = phoneNo; + } + + public String getType() { + return type; + } + + public void setType(String phoneType) { + this.type = phoneType; + } + + public Employee getEmployee() { + return employee; + } + + public void setEmployee(Employee employee) { + this.employee = employee; + } + + public String toString() { + return "Phone id: " + getId() + + ", no: " + getNumber() + + ", type: " + getType(); + } +} diff --git a/examples/Chapter9/03-empSearchSubQuery/src/model/examples/model/Project.java b/examples/Chapter9/03-empSearchSubQuery/src/model/examples/model/Project.java new file mode 100644 index 0000000..43b8c47 --- /dev/null +++ b/examples/Chapter9/03-empSearchSubQuery/src/model/examples/model/Project.java @@ -0,0 +1,55 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.ManyToMany; + +@Entity +public class Project { + @Id + protected int id; + protected String name; + @ManyToMany + protected Collection employees = new ArrayList(); + + public Project() {} + + public int getId() { + return id; + } + + public void setId(int projectNo) { + this.id = projectNo; + } + + public String getName() { + return name; + } + + public void setName(String projectName) { + this.name = projectName; + } + + public Collection getEmployees() { + return employees; + } + + public void addEmployee(Employee employee) { + if (!getEmployees().contains(employee)) { + getEmployees().add(employee); + } + if (!employee.getProjects().contains(this)) { + employee.getProjects().add(this); + } + } + + public String toString() { + return getClass().getName().substring(getClass().getName().lastIndexOf('.')+1) + + " no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter9/03-empSearchSubQuery/src/model/examples/stateless/SearchService.java b/examples/Chapter9/03-empSearchSubQuery/src/model/examples/stateless/SearchService.java new file mode 100644 index 0000000..ff28369 --- /dev/null +++ b/examples/Chapter9/03-empSearchSubQuery/src/model/examples/stateless/SearchService.java @@ -0,0 +1,112 @@ +package examples.stateless; + +import examples.model.Employee; +import examples.model.Project; +import java.util.ArrayList; +import java.util.List; +import java.io.PrintWriter; +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Join; +import javax.persistence.criteria.JoinType; +import javax.persistence.criteria.ParameterExpression; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; +import javax.persistence.criteria.Subquery; +import javax.persistence.Query; +import java.util.Collection; + +@Stateless +public class SearchService { + + @PersistenceContext(unitName="EmployeeHR") + EntityManager em; + + public EntityManager getEntityManager() { + return em; + } + public Employee createEmployee(int id, String name, long salary) { + Employee emp = new Employee(id); + emp.setName(name); + emp.setSalary(salary); + getEntityManager().persist(emp); + return emp; + } + + public void removeEmployee(int id) { + Employee emp = findEmployee(id); + if (emp != null) { + getEntityManager().remove(emp); + } + } + + public Employee changeEmployeeSalary(int id, long newSalary) { + Employee emp = findEmployee(id); + if (emp != null) { + emp.setSalary(newSalary); + } + return emp; + } + + public Employee findEmployee(int id) { + return getEntityManager().find(Employee.class, id); + } + + public Collection findAllEmployees() { + Query query = getEntityManager().createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } + + public List findEmployees(String name, String deptName, + String projectName, String city, PrintWriter out) { + + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery c = cb.createQuery(Employee.class); + Root emp = c.from(Employee.class); + c.select(emp); + //c.distinct(true); + //Join project = emp.join("projects", JoinType.LEFT); + List criteria = new ArrayList(); + if (name != null) { + ParameterExpression p = + cb.parameter(String.class, "name"); + criteria.add(cb.equal(emp.get("name"), p)); + } + if (deptName != null) { + ParameterExpression p = + cb.parameter(String.class, "dept"); + criteria.add(cb.equal(emp.get("dept").get("name"), p)); + } + if (projectName != null) { + Subquery sq = c.subquery(Integer.class); + Root project = sq.from(Project.class); + Join sqEmp = project.join("employees"); + sq.select(sqEmp.get("id")) + .where(cb.equal(project.get("name"), + cb.parameter(String.class, "project"))); + criteria.add(cb.in(emp.get("id")).value(sq)); + } + if (city != null) { + ParameterExpression p = + cb.parameter(String.class, "city"); + criteria.add(cb.equal(emp.get("address").get("city"), p)); + } + if (criteria.size() == 1) { + c.where(criteria.get(0)); + } else { + c.where(cb.and(criteria.toArray(new Predicate[0]))); + } + + TypedQuery q = em.createQuery(c); + out.println(c); + if (name != null) { q.setParameter("name", name); } + if (deptName != null) { q.setParameter("dept", deptName); } + if (projectName != null) { q.setParameter("project", projectName); } + if (city != null) { q.setParameter("city", city); } + return q.getResultList(); + } +} \ No newline at end of file diff --git a/examples/Chapter9/03-empSearchSubQuery/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter9/03-empSearchSubQuery/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..009e8c8 --- /dev/null +++ b/examples/Chapter9/03-empSearchSubQuery/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,121 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; +import examples.model.Project; +import examples.stateless.SearchService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 9: Employee Search Service using Criteria Subquery Example"; + + private final String DESCRIPTION = + "This example allows you to search for employees using one or more query criteria." + + " The project criterium uses a subquery."; + + + // inject a reference to the SearchService slsb + @EJB SearchService service; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("FindEmployees")) { + out.println("CriteriaQuery: "); + String name = request.getParameter("name"); + if (name.equals("")) name = null; + String dept = request.getParameter("dept"); + if (dept.equals("")) dept = null; + String project = request.getParameter("project"); + if (project.equals("")) project = null; + String city = request.getParameter("city"); + if (city.equals("")) city = null; + + Collection emps = service.findEmployees(name, dept, project, city, out); + + if (emps.isEmpty()) { + out.println("
No Employees found "); + } else { + out.println("
Found Employees:
"); + for (Employee emp : emps) { + out.print(emp + "
"); + } + } + } + + printHtmlFooter(out); + } + + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println(""); + + // form to find Employees + out.println("

Find Employees

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("" + + ""); + out.println("
Name:(String)
DeptName:(String)
ProjectName:(String)
City:(String)
"); + + // show all Employees + out.println("
"); + out.println("
Employees: "); + Collection emps = service.findAllEmployees(); + for (Employee emp : emps) { + out.println("
" + emp); + } + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter9/03-empSearchSubQuery/undeploy.bat b/examples/Chapter9/03-empSearchSubQuery/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter9/03-empSearchSubQuery/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter9/04-metamodelStronglyTyped/build.xml b/examples/Chapter9/04-metamodelStronglyTyped/build.xml new file mode 100644 index 0000000..c20a730 --- /dev/null +++ b/examples/Chapter9/04-metamodelStronglyTyped/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter9/04-metamodelStronglyTyped/deploy.bat b/examples/Chapter9/04-metamodelStronglyTyped/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter9/04-metamodelStronglyTyped/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter9/04-metamodelStronglyTyped/etc/persistence/META-INF/persistence.xml b/examples/Chapter9/04-metamodelStronglyTyped/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..82b61f9 --- /dev/null +++ b/examples/Chapter9/04-metamodelStronglyTyped/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,11 @@ + + + jdbc/metamodelStronglyTyped + + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/04-metamodelStronglyTyped/etc/sql/db.sql b/examples/Chapter9/04-metamodelStronglyTyped/etc/sql/db.sql new file mode 100644 index 0000000..4434224 --- /dev/null +++ b/examples/Chapter9/04-metamodelStronglyTyped/etc/sql/db.sql @@ -0,0 +1,95 @@ +DROP TABLE DEPARTMENT; +DROP TABLE PROJECT; +DROP TABLE PROJECT_EMPLOYEE; +DROP TABLE EMPLOYEE; +DROP TABLE PHONE; +DROP TABLE ADDRESS; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE PROJECT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE PROJECT_EMPLOYEE (EMPLOYEES_ID INTEGER, PROJECTS_ID INTEGER); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, STARTDATE DATE, ADDRESS_ID INTEGER, DEPT_ID INTEGER, MANAGER_ID INTEGER, PRIMARY KEY (ID)); +CREATE TABLE PHONE (ID BIGINT NOT NULL, NUMBER VARCHAR(255), TYPE VARCHAR(255), EMPLOYEE_ID INTEGER, PRIMARY KEY (ID)); +CREATE TABLE ADDRESS (ID INTEGER NOT NULL, CITY VARCHAR(255), STATE VARCHAR(255), STREET VARCHAR(255), ZIP VARCHAR(255), PRIMARY KEY (ID)); + + +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (1, 'New York', 'NY', '123 Apple Tree Cr.', '10001'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (2, 'Manhattan', 'NY', '654 Stanton Way.', '10003'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (3, 'New York', 'NY', '99 Queen St.', '10001'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (4, 'Redwood Shores', 'CA', '445 McDonell Cr.', '90123'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (5, 'San Jose', 'CA', '624 Hamilton Dr.', '90123'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (6, 'San Jose', 'CA', '724 Coventry Rd.', '90123'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (7, 'San Francisco', 'CA', '77 Manchester Blvd.', '90123'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (8, 'Moorestown', 'NJ', '53 King St.', '08057'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (9, 'New York', 'NY', '14 Industrial Ave.', '10001'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (10, 'Redwood Shores', 'CA', '777 High Tech Ln.', '90123'); + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'QA'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'Accounting'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (4, 'CAEngOtt'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (5, 'USEngCal'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (6, 'CADocOtt'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (7, 'QA_East'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (8, 'QANorth'); + +INSERT INTO PROJECT (ID, NAME) VALUES (1, 'Design Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (2, 'Release1'); +INSERT INTO PROJECT (ID, NAME) VALUES (3, 'Test Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (4, 'Implement Release3'); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (1, 'John', 55000, {d '2001-01-01'}, 1, 2, 9); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (2, 'Rob', 53000, {d '2001-05-23'}, 2, 2, 9); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (3, 'Peter', 40000, {d '2002-08-06'}, 3, 2, 9); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (4, 'Frank', 41000, {d '2003-02-17'}, 4, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (5, 'Scott', 60000, {d '2004-11-14'}, 5, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (6, 'Sue', 62000, {d '2005-08-18'}, 6, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (7, 'Stephanie', 54000, {d '2006-06-07'}, 7, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (8, 'Jennifer', 45000, {d '1999-08-11'}, 8, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (9, 'Sarah', 52000, {d '2002-04-26'}, 9, 2, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (10, 'Joan', 59000, {d '2003-04-16'}, 10, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (11, 'Marcus', 35000, {d '1995-07-22'}, NULL, NULL, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (12, 'Joe', 36000, {d '1995-07-22'}, NULL, 3, 11); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (13, 'Jack', 43000, {d '1995-07-22'}, NULL, 3, NULL); + +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (1, '(212)555-1234', 'Office', 1); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (2, '(212)555-9843', 'Home', 1); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (3, '(315)555-6253', 'Office', 2); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (4, '(516)555-9837', 'Office', 3); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (5, '(516)555-2034', 'Cell', 3); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (6, '(650)555-7583', 'Office', 4); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (7, '(650)555-5345', 'Home', 4); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (8, '(650)555-9386', 'Office', 5); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (9, '(650)555-4885', 'Cell', 5); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (10, '(650)555-3836', 'Office', 6); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (11, '(650)555-0985', 'Home', 6); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (12, '(650)555-1946', 'Cell', 6); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (13, '(650)555-4759', 'Office', 7); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (14, '(650)555-4757', 'Home', 7); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (15, '(650)555-6753', 'Office', 8); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (16, '(585)555-0693', 'Office', 9); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (17, '(585)555-3098', 'Home', 9); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (18, '(585)555-1457', 'Cell', 9); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (19, '(650)555-9838', 'Office', 10); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (20, '(650)555-2346', 'Home', 10); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (21, '(650)555-9874', 'Cell', 10); + +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (1, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (4, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (7, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 3); \ No newline at end of file diff --git a/examples/Chapter9/04-metamodelStronglyTyped/etc/web/WEB-INF/web.xml b/examples/Chapter9/04-metamodelStronglyTyped/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..9eebc68 --- /dev/null +++ b/examples/Chapter9/04-metamodelStronglyTyped/etc/web/WEB-INF/web.xml @@ -0,0 +1,16 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + + \ No newline at end of file diff --git a/examples/Chapter9/04-metamodelStronglyTyped/src/model/examples/model/Address.java b/examples/Chapter9/04-metamodelStronglyTyped/src/model/examples/model/Address.java new file mode 100644 index 0000000..c1cad79 --- /dev/null +++ b/examples/Chapter9/04-metamodelStronglyTyped/src/model/examples/model/Address.java @@ -0,0 +1,64 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Address { + @Id + private int id; + private String street; + private String city; + private String state; + private String zip; + + public Address() {} + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getStreet() { + return street; + } + + public void setStreet(String address) { + this.street = address; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getZip() { + return zip; + } + + public void setZip(String zip) { + this.zip = zip; + } + public String toString() { + return "Address id: " + getId() + + ", street: " + getStreet() + + ", city: " + getCity() + + ", state: " + getState() + + ", zip: " + getZip(); + } + +} diff --git a/examples/Chapter9/04-metamodelStronglyTyped/src/model/examples/model/Department.java b/examples/Chapter9/04-metamodelStronglyTyped/src/model/examples/model/Department.java new file mode 100644 index 0000000..3deeac5 --- /dev/null +++ b/examples/Chapter9/04-metamodelStronglyTyped/src/model/examples/model/Department.java @@ -0,0 +1,44 @@ +package examples.model; + +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="dept") + private Set employees = new HashSet(); + + public Department() {} + + public int getId() { + return id; + } + + public void setId(int deptNo) { + this.id = deptNo; + } + + public String getName() { + return name; + } + + public void setName(String deptName) { + this.name = deptName; + } + + public Set getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter9/04-metamodelStronglyTyped/src/model/examples/model/Employee.java b/examples/Chapter9/04-metamodelStronglyTyped/src/model/examples/model/Employee.java new file mode 100644 index 0000000..932e033 --- /dev/null +++ b/examples/Chapter9/04-metamodelStronglyTyped/src/model/examples/model/Employee.java @@ -0,0 +1,162 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToMany; +import javax.persistence.ManyToOne; +import javax.persistence.MapKey; +import javax.persistence.OneToMany; +import javax.persistence.OneToOne; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + @Temporal(TemporalType.DATE) + private Date startDate; + + @OneToOne + private Address address; + + @OneToMany(mappedBy="employee") + @MapKey(name="type") + private Map phones = new HashMap(); + + @ManyToOne + private Department dept; + + @ManyToOne + private Employee manager; + + @OneToMany(mappedBy="manager") + private Collection directs = new ArrayList(); + + @ManyToMany(mappedBy="employees") + private Collection projects = new ArrayList(); + + public Employee() {} + + public Employee(int id) { + this.id = id; + } + + public int getId() { + return id; + } + + public void setId(int empNo) { + this.id = empNo; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public Map getPhones() { + return phones; + } + + public void addPhone(String key, Phone phone) { + if (!getPhones().containsKey(phone)) { + getPhones().put(key, phone); + if (phone.getEmployee() != null) { + phone.getEmployee().getPhones().remove(phone); + } + phone.setEmployee(this); + } + } + + public Department getDept() { + return dept; + } + + public void setDept(Department dept) { + if (this.dept != null) { + this.dept.getEmployees().remove(this); + } + this.dept = dept; + this.dept.getEmployees().add(this); + } + + public Collection getDirects() { + return directs; + } + + public void addDirect(Employee employee) { + if (!getDirects().contains(employee)) { + getDirects().add(employee); + if (employee.getManager() != null) { + employee.getManager().getDirects().remove(employee); + } + employee.setManager(this); + } + } + + public Employee getManager() { + return manager; + } + + public void setManager(Employee manager) { + this.manager = manager; + } + + public Collection getProjects() { + return projects; + } + + public void addProject(Project project) { + if (!getProjects().contains(project)) { + getProjects().add(project); + } + if (!project.getEmployees().contains(this)) { + project.getEmployees().add(this); + } + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary() + + ", managerNo: " + ((getManager() == null) ? null : getManager().getId()) + + ", deptNo: " + ((getDept() == null) ? null : getDept().getId()); + } + +} diff --git a/examples/Chapter9/04-metamodelStronglyTyped/src/model/examples/model/Phone.java b/examples/Chapter9/04-metamodelStronglyTyped/src/model/examples/model/Phone.java new file mode 100644 index 0000000..8269374 --- /dev/null +++ b/examples/Chapter9/04-metamodelStronglyTyped/src/model/examples/model/Phone.java @@ -0,0 +1,54 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToOne; + +@Entity +public class Phone { + @Id + private long id; + private String number; + private String type; + @OneToOne Employee employee; + + public Phone() {} + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getNumber() { + return number; + } + + public void setNumber(String phoneNo) { + this.number = phoneNo; + } + + public String getType() { + return type; + } + + public void setType(String phoneType) { + this.type = phoneType; + } + + public Employee getEmployee() { + return employee; + } + + public void setEmployee(Employee employee) { + this.employee = employee; + } + + public String toString() { + return "Phone id: " + getId() + + ", no: " + getNumber() + + ", type: " + getType(); + } +} diff --git a/examples/Chapter9/04-metamodelStronglyTyped/src/model/examples/model/Project.java b/examples/Chapter9/04-metamodelStronglyTyped/src/model/examples/model/Project.java new file mode 100644 index 0000000..43b8c47 --- /dev/null +++ b/examples/Chapter9/04-metamodelStronglyTyped/src/model/examples/model/Project.java @@ -0,0 +1,55 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.ManyToMany; + +@Entity +public class Project { + @Id + protected int id; + protected String name; + @ManyToMany + protected Collection employees = new ArrayList(); + + public Project() {} + + public int getId() { + return id; + } + + public void setId(int projectNo) { + this.id = projectNo; + } + + public String getName() { + return name; + } + + public void setName(String projectName) { + this.name = projectName; + } + + public Collection getEmployees() { + return employees; + } + + public void addEmployee(Employee employee) { + if (!getEmployees().contains(employee)) { + getEmployees().add(employee); + } + if (!employee.getProjects().contains(this)) { + employee.getProjects().add(this); + } + } + + public String toString() { + return getClass().getName().substring(getClass().getName().lastIndexOf('.')+1) + + " no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter9/04-metamodelStronglyTyped/src/model/examples/stateless/SearchService.java b/examples/Chapter9/04-metamodelStronglyTyped/src/model/examples/stateless/SearchService.java new file mode 100644 index 0000000..25adbf1 --- /dev/null +++ b/examples/Chapter9/04-metamodelStronglyTyped/src/model/examples/stateless/SearchService.java @@ -0,0 +1,46 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.MapJoin; +import javax.persistence.criteria.Root; +import javax.persistence.metamodel.EntityType; +import javax.persistence.metamodel.Metamodel; + +import examples.model.Employee; +import examples.model.Phone; + + +@Stateless +public class SearchService { + @PersistenceContext(unitName="EmployeeHR") + EntityManager em; + + public EntityManager getEntityManager() { + return em; + } + + public Collection executeQueryUsingMetamodel() { + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery c = cb.createQuery(); + Root emp = c.from(Employee.class); + EntityType emp_ = emp.getModel(); + MapJoin phone = + emp.join(emp_.getMap("phones", String.class, Phone.class)); + c.multiselect(emp.get(emp_.getSingularAttribute("name", String.class)), + phone.key(), + phone.value()); + TypedQuery q = em.createQuery(c); + return q.getResultList(); + } + + public Metamodel getMetamodel() { + return em.getMetamodel(); + } +} diff --git a/examples/Chapter9/04-metamodelStronglyTyped/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter9/04-metamodelStronglyTyped/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..cae35db --- /dev/null +++ b/examples/Chapter9/04-metamodelStronglyTyped/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,111 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.persistence.metamodel.Metamodel; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateless.SearchService; +import examples.model.Phone; + +public class EmployeeServlet extends HttpServlet { + + private static final long serialVersionUID = -3522516457354939873L; + + private final String TITLE = + "Chapter 9: Metamodel Strongly Typed API Example"; + + private final String DESCRIPTION = + "This example pulls together much of what was learned in this chapter " + + "and relates it to our earlier EmployeeService example.
" + + "The example allows you to use the Metamodel for a query, and print a " + + "summary of the metamodel of the persistence unit."; + + + // inject a reference to the SearchService slsb + @EJB SearchService service; + + @Override + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("ExecuteQuery")) { + Collection results = service.executeQueryUsingMetamodel(); + out.println("Results:
"); + for (Object o : results) { + Object[] entry = (Object[])o; + out.println(entry[0] + ", " + + entry[1] + ", " + + (Phone)entry[2] + "
"); + } + } else if (action.equals("Metamodel")) { + Metamodel metamodel = service.getMetamodel(); + out.println("Metamodel: " + metamodel); + } + + printHtmlFooter(out); + } + + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println(""); + // form to execute query + out.println("

Execute Query Using Metamodel

"); + out.println(""); + out.println(""); + out.println("
"); + out.println("
"); + // form print out metamodel summary + out.println("

Get Metamodel Summary

"); + out.println(""); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter9/04-metamodelStronglyTyped/undeploy.bat b/examples/Chapter9/04-metamodelStronglyTyped/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter9/04-metamodelStronglyTyped/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/Chapter9/05-canonicalMetamodel/META-INF/persistence.xml b/examples/Chapter9/05-canonicalMetamodel/META-INF/persistence.xml new file mode 100644 index 0000000..41dbf06 --- /dev/null +++ b/examples/Chapter9/05-canonicalMetamodel/META-INF/persistence.xml @@ -0,0 +1,11 @@ + + + jdbc/canonicalMetamodel + + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/05-canonicalMetamodel/build.xml b/examples/Chapter9/05-canonicalMetamodel/build.xml new file mode 100644 index 0000000..b6ae622 --- /dev/null +++ b/examples/Chapter9/05-canonicalMetamodel/build.xml @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Chapter9/05-canonicalMetamodel/generate.bat b/examples/Chapter9/05-canonicalMetamodel/generate.bat new file mode 100644 index 0000000..75f3bc2 --- /dev/null +++ b/examples/Chapter9/05-canonicalMetamodel/generate.bat @@ -0,0 +1,2 @@ +call ../../../config/ant generate +pause \ No newline at end of file diff --git a/examples/Chapter9/05-canonicalMetamodel/generateAndCompile.bat b/examples/Chapter9/05-canonicalMetamodel/generateAndCompile.bat new file mode 100644 index 0000000..c49380e --- /dev/null +++ b/examples/Chapter9/05-canonicalMetamodel/generateAndCompile.bat @@ -0,0 +1,2 @@ +call ../../../config/ant generateAndCompile +pause \ No newline at end of file diff --git a/examples/Chapter9/05-canonicalMetamodel/src/model/examples/model/Address.java b/examples/Chapter9/05-canonicalMetamodel/src/model/examples/model/Address.java new file mode 100644 index 0000000..c1cad79 --- /dev/null +++ b/examples/Chapter9/05-canonicalMetamodel/src/model/examples/model/Address.java @@ -0,0 +1,64 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Address { + @Id + private int id; + private String street; + private String city; + private String state; + private String zip; + + public Address() {} + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getStreet() { + return street; + } + + public void setStreet(String address) { + this.street = address; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getZip() { + return zip; + } + + public void setZip(String zip) { + this.zip = zip; + } + public String toString() { + return "Address id: " + getId() + + ", street: " + getStreet() + + ", city: " + getCity() + + ", state: " + getState() + + ", zip: " + getZip(); + } + +} diff --git a/examples/Chapter9/05-canonicalMetamodel/src/model/examples/model/Department.java b/examples/Chapter9/05-canonicalMetamodel/src/model/examples/model/Department.java new file mode 100644 index 0000000..3deeac5 --- /dev/null +++ b/examples/Chapter9/05-canonicalMetamodel/src/model/examples/model/Department.java @@ -0,0 +1,44 @@ +package examples.model; + +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="dept") + private Set employees = new HashSet(); + + public Department() {} + + public int getId() { + return id; + } + + public void setId(int deptNo) { + this.id = deptNo; + } + + public String getName() { + return name; + } + + public void setName(String deptName) { + this.name = deptName; + } + + public Set getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter9/05-canonicalMetamodel/src/model/examples/model/Employee.java b/examples/Chapter9/05-canonicalMetamodel/src/model/examples/model/Employee.java new file mode 100644 index 0000000..3998b20 --- /dev/null +++ b/examples/Chapter9/05-canonicalMetamodel/src/model/examples/model/Employee.java @@ -0,0 +1,169 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToMany; +import javax.persistence.ManyToOne; +import javax.persistence.MapKey; +import javax.persistence.OneToMany; +import javax.persistence.OneToOne; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + @Temporal(TemporalType.DATE) + private Date startDate; + + @OneToOne + private Address address; + + @OneToMany(mappedBy="employee") + @MapKey(name="type") + private Map phones = new HashMap(); + + @ManyToOne + private Department dept; + + @ManyToOne + private Employee manager; + + @OneToMany(mappedBy="manager") + private Collection directs = new ArrayList(); + + @ManyToMany(mappedBy="employees") + private Collection projects = new ArrayList(); + //private Project project; + + public Employee() {} + + public Employee(int id) { + this.id = id; + } + + public int getId() { + return id; + } + + public void setId(int empNo) { + this.id = empNo; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public Map getPhones() { + return phones; + } + + public void addPhone(String key, Phone phone) { + if (!getPhones().containsKey(phone)) { + getPhones().put(key, phone); + if (phone.getEmployee() != null) { + phone.getEmployee().getPhones().remove(phone); + } + phone.setEmployee(this); + } + } + + public Department getDept() { + return dept; + } + + public void setDept(Department dept) { + if (this.dept != null) { + this.dept.getEmployees().remove(this); + } + this.dept = dept; + this.dept.getEmployees().add(this); + } + + public Collection getDirects() { + return directs; + } + + public void addDirect(Employee employee) { + if (!getDirects().contains(employee)) { + getDirects().add(employee); + if (employee.getManager() != null) { + employee.getManager().getDirects().remove(employee); + } + employee.setManager(this); + } + } + + public Employee getManager() { + return manager; + } + + public void setManager(Employee manager) { + this.manager = manager; + } + + public Collection getProjects() { + return projects; + } + + public void addProject(Project project) { + if (!getProjects().contains(project)) { + getProjects().add(project); + } + if (!project.getEmployees().contains(this)) { + project.getEmployees().add(this); + } + } + + +// public Project getProject() { return project; } +// public void setProject(Project aProject) { project = aProject; } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary() + + //", phones: " + getPhones() + + ", phones: " + getPhones() + + ", managerNo: " + ((getManager() == null) ? null : getManager().getId()) + + ", deptNo: " + ((getDept() == null) ? null : getDept().getId()); + } + +} diff --git a/examples/Chapter9/05-canonicalMetamodel/src/model/examples/model/Phone.java b/examples/Chapter9/05-canonicalMetamodel/src/model/examples/model/Phone.java new file mode 100644 index 0000000..8269374 --- /dev/null +++ b/examples/Chapter9/05-canonicalMetamodel/src/model/examples/model/Phone.java @@ -0,0 +1,54 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToOne; + +@Entity +public class Phone { + @Id + private long id; + private String number; + private String type; + @OneToOne Employee employee; + + public Phone() {} + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getNumber() { + return number; + } + + public void setNumber(String phoneNo) { + this.number = phoneNo; + } + + public String getType() { + return type; + } + + public void setType(String phoneType) { + this.type = phoneType; + } + + public Employee getEmployee() { + return employee; + } + + public void setEmployee(Employee employee) { + this.employee = employee; + } + + public String toString() { + return "Phone id: " + getId() + + ", no: " + getNumber() + + ", type: " + getType(); + } +} diff --git a/examples/Chapter9/05-canonicalMetamodel/src/model/examples/model/Project.java b/examples/Chapter9/05-canonicalMetamodel/src/model/examples/model/Project.java new file mode 100644 index 0000000..cc3914c --- /dev/null +++ b/examples/Chapter9/05-canonicalMetamodel/src/model/examples/model/Project.java @@ -0,0 +1,56 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.ManyToMany; + +@Entity +@Inheritance +public class Project { + @Id + protected int id; + protected String name; + @ManyToMany + protected Collection employees = new ArrayList(); + + public Project() {} + + public int getId() { + return id; + } + + public void setId(int projectNo) { + this.id = projectNo; + } + + public String getName() { + return name; + } + + public void setName(String projectName) { + this.name = projectName; + } + + public Collection getEmployees() { + return employees; + } + + public void addEmployee(Employee employee) { + if (!getEmployees().contains(employee)) { + getEmployees().add(employee); + } + if (!employee.getProjects().contains(this)) { + employee.getProjects().add(this); + } + } + + public String toString() { + return getClass().getName().substring(getClass().getName().lastIndexOf('.')+1) + + " no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter9/06-canonicalMetamodelQuery/META-INF/persistence.xml b/examples/Chapter9/06-canonicalMetamodelQuery/META-INF/persistence.xml new file mode 100644 index 0000000..400ef44 --- /dev/null +++ b/examples/Chapter9/06-canonicalMetamodelQuery/META-INF/persistence.xml @@ -0,0 +1,11 @@ + + + jdbc/canonicalMetamodelQuery + + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/06-canonicalMetamodelQuery/build.xml b/examples/Chapter9/06-canonicalMetamodelQuery/build.xml new file mode 100644 index 0000000..2ad658e --- /dev/null +++ b/examples/Chapter9/06-canonicalMetamodelQuery/build.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Chapter9/06-canonicalMetamodelQuery/deploy.bat b/examples/Chapter9/06-canonicalMetamodelQuery/deploy.bat new file mode 100644 index 0000000..7ac9674 --- /dev/null +++ b/examples/Chapter9/06-canonicalMetamodelQuery/deploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant deploy +pause \ No newline at end of file diff --git a/examples/Chapter9/06-canonicalMetamodelQuery/etc/persistence/META-INF/persistence.xml b/examples/Chapter9/06-canonicalMetamodelQuery/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..400ef44 --- /dev/null +++ b/examples/Chapter9/06-canonicalMetamodelQuery/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,11 @@ + + + jdbc/canonicalMetamodelQuery + + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/06-canonicalMetamodelQuery/etc/sql/db.sql b/examples/Chapter9/06-canonicalMetamodelQuery/etc/sql/db.sql new file mode 100644 index 0000000..00f2564 --- /dev/null +++ b/examples/Chapter9/06-canonicalMetamodelQuery/etc/sql/db.sql @@ -0,0 +1,95 @@ +DROP TABLE DEPARTMENT; +DROP TABLE PROJECT; +DROP TABLE PROJECT_EMPLOYEE; +DROP TABLE EMPLOYEE; +DROP TABLE PHONE; +DROP TABLE ADDRESS; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE PROJECT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE PROJECT_EMPLOYEE (EMPLOYEES_ID INTEGER, PROJECTS_ID INTEGER); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, STARTDATE DATE, ADDRESS_ID INTEGER, DEPT_ID INTEGER, MANAGER_ID INTEGER, PRIMARY KEY (ID)); +CREATE TABLE PHONE (ID BIGINT NOT NULL, NUMBER VARCHAR(255), TYPE VARCHAR(255), EMPLOYEE_ID INTEGER, PRIMARY KEY (ID)); +CREATE TABLE ADDRESS (ID INTEGER NOT NULL, CITY VARCHAR(255), STATE VARCHAR(255), STREET VARCHAR(255), ZIP VARCHAR(255), PRIMARY KEY (ID)); + + +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (1, 'New York', 'NY', '123 Apple Tree Cr.', '10001'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (2, 'Manhattan', 'NY', '654 Stanton Way.', '10003'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (3, 'New York', 'NY', '99 Queen St.', '10001'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (4, 'Redwood Shores', 'CA', '445 McDonell Cr.', '90123'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (5, 'San Jose', 'CA', '624 Hamilton Dr.', '90123'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (6, 'San Jose', 'CA', '724 Coventry Rd.', '90123'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (7, 'San Francisco', 'CA', '77 Manchester Blvd.', '90123'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (8, 'Moorestown', 'NJ', '53 King St.', '08057'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (9, 'New York', 'NY', '14 Industrial Ave.', '10001'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (10, 'Redwood Shores', 'CA', '777 High Tech Ln.', '90123'); + +INSERT INTO DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (2, 'QA'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'Accounting'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (4, 'CAEngOtt'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (5, 'USEngCal'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (6, 'CADocOtt'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (7, 'QA_East'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (8, 'QANorth'); + +INSERT INTO PROJECT (ID, NAME) VALUES (1, 'Design Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (2, 'QA Test Release1'); +INSERT INTO PROJECT (ID, NAME) VALUES (3, 'QA Test Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (4, 'Implement Release3'); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (1, 'John', 55000, {d '2001-01-01'}, 1, 2, 9); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (2, 'Rob', 53000, {d '2001-05-23'}, 2, 2, 9); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (3, 'Peter', 40000, {d '2002-08-06'}, 3, 2, 9); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (4, 'Frank', 41000, {d '2003-02-17'}, 4, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (5, 'Scott', 60000, {d '2004-11-14'}, 5, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (6, 'Sue', 62000, {d '2005-08-18'}, 6, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (7, 'Stephanie', 54000, {d '2006-06-07'}, 7, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (8, 'Jennifer', 45000, {d '1999-08-11'}, 8, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (9, 'Sarah', 52000, {d '2002-04-26'}, 9, 2, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (10, 'Joan', 59000, {d '2003-04-16'}, 10, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (11, 'Marcus', 35000, {d '1995-07-22'}, NULL, NULL, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (12, 'Joe', 36000, {d '1995-07-22'}, NULL, 3, 11); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (13, 'Jack', 43000, {d '1995-07-22'}, NULL, 3, NULL); + +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (1, '(212)555-1234', 'Office', 1); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (2, '(212)555-9843', 'Home', 1); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (3, '(315)555-6253', 'Office', 2); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (4, '(516)555-9837', 'Office', 3); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (5, '(516)555-2034', 'Cell', 3); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (6, '(650)555-7583', 'Office', 4); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (7, '(650)555-5345', 'Home', 4); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (8, '(650)555-9386', 'Office', 5); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (9, '(650)555-4885', 'Cell', 5); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (10, '(650)555-3836', 'Office', 6); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (11, '(650)555-0985', 'Home', 6); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (12, '(650)555-1946', 'Cell', 6); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (13, '(650)555-4759', 'Office', 7); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (14, '(650)555-4757', 'Home', 7); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (15, '(650)555-6753', 'Office', 8); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (16, '(585)555-0693', 'Office', 9); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (17, '(585)555-3098', 'Home', 9); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (18, '(585)555-1457', 'Cell', 9); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (19, '(650)555-9838', 'Office', 10); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (20, '(650)555-2346', 'Home', 10); +INSERT INTO PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (21, '(650)555-9874', 'Cell', 10); + +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (1, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (4, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (7, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 3); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 1); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 2); +INSERT INTO PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 3); \ No newline at end of file diff --git a/examples/Chapter9/06-canonicalMetamodelQuery/etc/web/WEB-INF/web.xml b/examples/Chapter9/06-canonicalMetamodelQuery/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..9eebc68 --- /dev/null +++ b/examples/Chapter9/06-canonicalMetamodelQuery/etc/web/WEB-INF/web.xml @@ -0,0 +1,16 @@ + + + + EmployeeServlet + examples.servlet.EmployeeServlet + + + + EmployeeServlet + /EmployeeServlet + + + \ No newline at end of file diff --git a/examples/Chapter9/06-canonicalMetamodelQuery/src/model/examples/model/Address.java b/examples/Chapter9/06-canonicalMetamodelQuery/src/model/examples/model/Address.java new file mode 100644 index 0000000..c1cad79 --- /dev/null +++ b/examples/Chapter9/06-canonicalMetamodelQuery/src/model/examples/model/Address.java @@ -0,0 +1,64 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Address { + @Id + private int id; + private String street; + private String city; + private String state; + private String zip; + + public Address() {} + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getStreet() { + return street; + } + + public void setStreet(String address) { + this.street = address; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getZip() { + return zip; + } + + public void setZip(String zip) { + this.zip = zip; + } + public String toString() { + return "Address id: " + getId() + + ", street: " + getStreet() + + ", city: " + getCity() + + ", state: " + getState() + + ", zip: " + getZip(); + } + +} diff --git a/examples/Chapter9/06-canonicalMetamodelQuery/src/model/examples/model/Department.java b/examples/Chapter9/06-canonicalMetamodelQuery/src/model/examples/model/Department.java new file mode 100644 index 0000000..3deeac5 --- /dev/null +++ b/examples/Chapter9/06-canonicalMetamodelQuery/src/model/examples/model/Department.java @@ -0,0 +1,44 @@ +package examples.model; + +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; + +@Entity +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy="dept") + private Set employees = new HashSet(); + + public Department() {} + + public int getId() { + return id; + } + + public void setId(int deptNo) { + this.id = deptNo; + } + + public String getName() { + return name; + } + + public void setName(String deptName) { + this.name = deptName; + } + + public Set getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter9/06-canonicalMetamodelQuery/src/model/examples/model/Employee.java b/examples/Chapter9/06-canonicalMetamodelQuery/src/model/examples/model/Employee.java new file mode 100644 index 0000000..14ed723 --- /dev/null +++ b/examples/Chapter9/06-canonicalMetamodelQuery/src/model/examples/model/Employee.java @@ -0,0 +1,172 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.FetchType; +import javax.persistence.ManyToMany; +import javax.persistence.ManyToOne; +import javax.persistence.MapKey; +import javax.persistence.OneToMany; +import javax.persistence.OneToOne; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + @Temporal(TemporalType.DATE) + private Date startDate; + + @OneToOne + private Address address; + + @OneToMany(mappedBy="employee") + @MapKey(name="type") + private Map phones = new HashMap(); + + @ManyToOne + private Department dept; + + @ManyToOne + private Employee manager; + + @OneToMany(mappedBy="manager") + private Collection directs = new ArrayList(); + + @ManyToMany(mappedBy="employees", fetch=FetchType.EAGER) + private Collection projects = new ArrayList(); + + public Employee() {} + + public Employee(int id) { + this.id = id; + } + + public int getId() { + return id; + } + + public void setId(int empNo) { + this.id = empNo; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public Map getPhones() { + return phones; + } + + public void addPhone(String key, Phone phone) { + if (!getPhones().containsKey(phone)) { + getPhones().put(key, phone); + if (phone.getEmployee() != null) { + phone.getEmployee().getPhones().remove(phone); + } + phone.setEmployee(this); + } + } + + public Department getDept() { + return dept; + } + + public void setDept(Department dept) { + if (this.dept != null) { + this.dept.getEmployees().remove(this); + } + this.dept = dept; + this.dept.getEmployees().add(this); + } + + public Collection getDirects() { + return directs; + } + + public void addDirect(Employee employee) { + if (!getDirects().contains(employee)) { + getDirects().add(employee); + if (employee.getManager() != null) { + employee.getManager().getDirects().remove(employee); + } + employee.setManager(this); + } + } + + public Employee getManager() { + return manager; + } + + public void setManager(Employee manager) { + this.manager = manager; + } + + public Collection getProjects() { + return projects; + } + + Collection getProjectNames() { + Collection names = new ArrayList(); + if (projects != null) { + for (Project p : projects) { + names.add(p.getName()); + } + } + return names; + } + + public void addProject(Project project) { + if (!getProjects().contains(project)) { + getProjects().add(project); + } + if (!project.getEmployees().contains(this)) { + project.getEmployees().add(this); + } + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public String toString() { + return "Employee " + getId() + + ": name: " + getName() + + ", salary: " + getSalary() + + ", projects: " + getProjectNames(); + } + +} diff --git a/examples/Chapter9/06-canonicalMetamodelQuery/src/model/examples/model/Phone.java b/examples/Chapter9/06-canonicalMetamodelQuery/src/model/examples/model/Phone.java new file mode 100644 index 0000000..8269374 --- /dev/null +++ b/examples/Chapter9/06-canonicalMetamodelQuery/src/model/examples/model/Phone.java @@ -0,0 +1,54 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToOne; + +@Entity +public class Phone { + @Id + private long id; + private String number; + private String type; + @OneToOne Employee employee; + + public Phone() {} + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getNumber() { + return number; + } + + public void setNumber(String phoneNo) { + this.number = phoneNo; + } + + public String getType() { + return type; + } + + public void setType(String phoneType) { + this.type = phoneType; + } + + public Employee getEmployee() { + return employee; + } + + public void setEmployee(Employee employee) { + this.employee = employee; + } + + public String toString() { + return "Phone id: " + getId() + + ", no: " + getNumber() + + ", type: " + getType(); + } +} diff --git a/examples/Chapter9/06-canonicalMetamodelQuery/src/model/examples/model/Project.java b/examples/Chapter9/06-canonicalMetamodelQuery/src/model/examples/model/Project.java new file mode 100644 index 0000000..43b8c47 --- /dev/null +++ b/examples/Chapter9/06-canonicalMetamodelQuery/src/model/examples/model/Project.java @@ -0,0 +1,55 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.ManyToMany; + +@Entity +public class Project { + @Id + protected int id; + protected String name; + @ManyToMany + protected Collection employees = new ArrayList(); + + public Project() {} + + public int getId() { + return id; + } + + public void setId(int projectNo) { + this.id = projectNo; + } + + public String getName() { + return name; + } + + public void setName(String projectName) { + this.name = projectName; + } + + public Collection getEmployees() { + return employees; + } + + public void addEmployee(Employee employee) { + if (!getEmployees().contains(employee)) { + getEmployees().add(employee); + } + if (!employee.getProjects().contains(this)) { + employee.getProjects().add(this); + } + } + + public String toString() { + return getClass().getName().substring(getClass().getName().lastIndexOf('.')+1) + + " no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter9/06-canonicalMetamodelQuery/src/model/examples/stateless/SearchService.java b/examples/Chapter9/06-canonicalMetamodelQuery/src/model/examples/stateless/SearchService.java new file mode 100644 index 0000000..b2d1f43 --- /dev/null +++ b/examples/Chapter9/06-canonicalMetamodelQuery/src/model/examples/stateless/SearchService.java @@ -0,0 +1,76 @@ +package examples.stateless; + +import java.util.List; + +import javax.ejb.Stateless; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.TypedQuery; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Subquery; +import javax.persistence.criteria.Join; +import javax.persistence.criteria.Root; + +import examples.model.*; + +@Stateless +public class SearchService { + @PersistenceContext(unitName="EmployeeHR") + EntityManager em; + + public EntityManager getEntityManager() { + return em; + } + + public List getEmployeesUsingJpqlQuery() { + + String qString = + "SELECT e FROM Employee e WHERE e.dept.id IN " + + "(SELECT DISTINCT d.id FROM Department d JOIN d.employees emp JOIN emp.projects empProj " + + " WHERE empProj.name LIKE \"QA%\")"; + + TypedQuery q = em.createQuery(qString, Employee.class); + return q.getResultList(); + } + + public List getEmployeesUsingStringBasedQuery() { + + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery c = cb.createQuery(Employee.class); + Root emp = c.from(Employee.class); + Subquery sq = c.subquery(Integer.class); + Root dept = sq.from(Department.class); + Join project = + dept.join("employees").join("projects"); + sq.select(dept.get("id")) + .distinct(true) + .where(cb.like(project.get("name"), "QA%")); + c.select(emp) + .where(cb.in(emp.get("dept").get("id")).value(sq)); + + TypedQuery q = em.createQuery(c); + return q.getResultList(); + } + + public List getEmployeesUsingCanonicalMetamodelQuery() { + + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery c = cb.createQuery(Employee.class); + Root emp = c.from(Employee.class); + Subquery sq = c.subquery(Integer.class); + Root dept = sq.from(Department.class); + Join project = + dept.join(Department_.employees).join(Employee_.projects); + sq.select(dept.get(Department_.id)) + .distinct(true) + .where(cb.like(project.get(Project_.name), "QA%")); + c.select(emp) + .where(cb.in(emp.get(Employee_.dept).get(Department_.id)).value(sq)); + + TypedQuery q = em.createQuery(c); + return q.getResultList(); + } +} diff --git a/examples/Chapter9/06-canonicalMetamodelQuery/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter9/06-canonicalMetamodelQuery/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..ec187bb --- /dev/null +++ b/examples/Chapter9/06-canonicalMetamodelQuery/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,119 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.List; + +import javax.ejb.EJB; +import javax.persistence.metamodel.Metamodel; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.stateless.SearchService; +import examples.model.Employee; + +public class EmployeeServlet extends HttpServlet { + + private static final long serialVersionUID = -3522516457354939873L; + + private final String TITLE = + "Chapter 9: Metamodel-based Strongly Typed Query Example"; + + private final String DESCRIPTION = + "This example pulls together much of what was learned in this chapter " + + "and relates it to our earlier EmployeeService example.
" + + "The example allows you to use the generated canonical metamodel for a query, " + + "and compares it with using a JP QL or string-based query."; + + + // inject a reference to the SearchService slsb + @EJB SearchService service; + + @Override + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + List emps = null; + + printHtmlHeader(out); + + // process request + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else { + if (action.equals("ExecuteJPQLBasedQuery")) { + emps = service.getEmployeesUsingJpqlQuery(); + out.println("JP QL query results:
"); + } else if (action.equals("ExecuteStringBasedQuery")) { + emps = service.getEmployeesUsingStringBasedQuery(); + out.println("String-based query results:
"); + } else if (action.equals("ExecuteMetamodelBasedQuery")) { + emps = service.getEmployeesUsingCanonicalMetamodelQuery(); + out.println("Canonical Metamodel-based query results:
"); + } + for (Employee emp : emps) { + out.println(emp + "
"); + } + } + printHtmlFooter(out); + } + + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + private int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + private long parseLong(String longString) { + try { + return Long.parseLong(longString); + } catch (NumberFormatException e) { + return 0; + } + } + + private void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println(""); + // form to execute query + out.println("

Execute Query Using JP QL

"); + out.println(""); + out.println(""); + out.println("
"); + out.println("
"); + // form to execute query + out.println("

Execute String-based Query

"); + out.println(""); + out.println(""); + out.println("
"); + out.println("
"); + // form to execute query + out.println("

Execute Query Using Canonical Metamodel

"); + out.println(""); + out.println(""); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter9/06-canonicalMetamodelQuery/undeploy.bat b/examples/Chapter9/06-canonicalMetamodelQuery/undeploy.bat new file mode 100644 index 0000000..8f6dc8f --- /dev/null +++ b/examples/Chapter9/06-canonicalMetamodelQuery/undeploy.bat @@ -0,0 +1,2 @@ +call ../../../config/ant undeploy +pause \ No newline at end of file diff --git a/examples/examplesHome.html b/examples/examplesHome.html new file mode 100644 index 0000000..0a7d50c --- /dev/null +++ b/examples/examplesHome.html @@ -0,0 +1,166 @@ + + Pro JPA 2: Mastering the Java Persistence API - Examples + +

Pro JPA 2: Mastering the Java Persistence API

+

Examples

+

Java SE Examples

+The SE examples (e.g. Chapter 2) do not require a running application server, only the db. +
+

Java EE Examples

+The other examples require a running application server. Go to the 'bin' folder and start +the Glassfish application server using the batch file (startservers.bat). Once started, go +to the desired chapter's example folder and build/deploy the application using the deploy.bat +batch file. Once that is done, come back to this page and click on the link of the desired +example. This will provide you with a web client to run the example. + + + diff --git a/lib/eclipselink-jpa-modelgen_2.1.0.qualifier.jar b/lib/eclipselink-jpa-modelgen_2.1.0.qualifier.jar new file mode 100644 index 0000000..146f82d Binary files /dev/null and b/lib/eclipselink-jpa-modelgen_2.1.0.qualifier.jar differ diff --git a/lib/org.eclipse.persistence.jpa.modelgen_2.1.0.qualifier.jar b/lib/org.eclipse.persistence.jpa.modelgen_2.1.0.qualifier.jar new file mode 100644 index 0000000..eebfe7a Binary files /dev/null and b/lib/org.eclipse.persistence.jpa.modelgen_2.1.0.qualifier.jar differ diff --git a/lib/readme.txt b/lib/readme.txt new file mode 100644 index 0000000..8239b38 --- /dev/null +++ b/lib/readme.txt @@ -0,0 +1,2 @@ +These libraries are needed by some of the examples in Chapters 9 and 13. +They are automatically copied to the necessary location by the deploy script or referenced in the classpath. \ No newline at end of file