diff --git a/2806.pdf b/2806.pdf new file mode 100644 index 0000000..ee82ce5 Binary files /dev/null and b/2806.pdf differ diff --git a/2807.pdf b/2807.pdf new file mode 100644 index 0000000..9a08aaf Binary files /dev/null and b/2807.pdf differ diff --git a/9781590596456.jpg b/9781590596456.jpg new file mode 100644 index 0000000..940b6fa Binary files /dev/null and b/9781590596456.jpg differ diff --git a/GettingStarted.txt b/GettingStarted.txt new file mode 100644 index 0000000..37ce76b --- /dev/null +++ b/GettingStarted.txt @@ -0,0 +1,13 @@ +- Assume you've downloaded the examples and unzipped them to . + +- download a copy of glassfish from https://glassfish.dev.java.net/public/downloadsindex.html + +- copy the downloaded .jar file to + +- edit /config/setenv.bat to point to your JDK 5.0 directory. The JDK is available for download at http://java.sun.com/j2se/1.5.0/download.jsp + +- edit /config/common.properties and set the EXAMPLES_HOME variable (location where you unzipped the examples jar). NOTE: make sure you use '/' and NOT '\' + +- run /bin/installserver.bat to install glassfish. Read and accept the licensing agreement that pops up. + +- you can now run the examples. Double-click /examples/examples.html to get started \ No newline at end of file diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..449c6f2 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,27 @@ +Freeware License, some rights reserved + +Copyright (c) 2006 Mike Keith and Merrick Schincariol + +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..59fe278 --- /dev/null +++ b/README.md @@ -0,0 +1,15 @@ +#Apress Source Code + +This repository accompanies [*Pro EJB 3*](http://www.apress.com/9781590596456) by Mike Keith and Merrick Schincariol (Apress, 2006). + +![Cover image](9781590596456.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/installserver.bat b/bin/installserver.bat new file mode 100644 index 0000000..eeace5a --- /dev/null +++ b/bin/installserver.bat @@ -0,0 +1,10 @@ +call ../config/setenv + +cd .. +%JAVA_HOME%/bin/java -Xmx256m -jar glassfish-installer*.jar + +cd glassfish +xcopy ..\lib\junit-4.0.jar ..\glassfish\lib\ant\lib +call ../glassfish/lib/ant/bin/ant -f setup.xml + +pause diff --git a/bin/startserver.bat b/bin/startserver.bat new file mode 100644 index 0000000..a3d46d3 --- /dev/null +++ b/bin/startserver.bat @@ -0,0 +1,6 @@ +call ../config/setenv + +call ../glassfish/lib/ant/bin/ant -f ../config/common.xml start_db +call ../glassfish/lib/ant/bin/ant -f ../config/common.xml start_server + +pause diff --git a/bin/stopserver.bat b/bin/stopserver.bat new file mode 100644 index 0000000..36f0c7f --- /dev/null +++ b/bin/stopserver.bat @@ -0,0 +1,6 @@ +call ../config/setenv + +call ../glassfish/lib/ant/bin/ant -f ../config/common.xml stop_server +call ../glassfish/lib/ant/bin/ant -f ../config/common.xml stop_db + +pause diff --git a/config/common.properties b/config/common.properties new file mode 100644 index 0000000..47f8aa5 --- /dev/null +++ b/config/common.properties @@ -0,0 +1,26 @@ +EXAMPLES_HOME=d:/book/examples + +################################################## +# properties for the Glassfish application server +################################################## +SERVER_HOME=${EXAMPLES_HOME}/glassfish +ADMIN_USER=admin +PASSWORD_FILE="${EXAMPLES_HOME}/config/password.txt" + +################################################## +# properties for the Derby Database +################################################## +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 + + + +ESSENTIALS_CLASSPATH=${SERVER_HOME}/lib/toplink-essentials.jar +SPRING_CLASSPATH=${EXAMPLES_HOME}/lib/spring.jar;${EXAMPLES_HOME}/lib/commons-logging.jar +J2EE_CLASSPATH=${SERVER_HOME}/lib/javaee.jar +CLIENT_CLASSPATH="${ESSENTIALS_CLASSPATH};${J2EE_CLASSPATH};${DERBY_CLASSPATH} diff --git a/config/common.xml b/config/common.xml new file mode 100644 index 0000000..16ecc57 --- /dev/null +++ b/config/common.xml @@ -0,0 +1,142 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ 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..4b2a171 --- /dev/null +++ b/config/setenv.bat @@ -0,0 +1 @@ +set JAVA_HOME=c:\jdk1.5.0 \ No newline at end of file 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/examples/Chapter10/xmlMappings/build.xml b/examples/Chapter10/xmlMappings/build.xml new file mode 100644 index 0000000..3b35646 --- /dev/null +++ b/examples/Chapter10/xmlMappings/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter10/xmlMappings/deploy.bat b/examples/Chapter10/xmlMappings/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter10/xmlMappings/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter10/xmlMappings/etc/persistence/META-INF/orm.xml b/examples/Chapter10/xmlMappings/etc/persistence/META-INF/orm.xml new file mode 100644 index 0000000..983b71a --- /dev/null +++ b/examples/Chapter10/xmlMappings/etc/persistence/META-INF/orm.xml @@ -0,0 +1,136 @@ + + + + + + + + FIELD + + + + examples.model + + + + + SELECT e FROM Employee e + + + + + + + + + + + + + + + + + + + + + + + + DATE + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + FT + + + + + + + + PT + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter10/xmlMappings/etc/persistence/META-INF/persistence.xml b/examples/Chapter10/xmlMappings/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..2bb948b --- /dev/null +++ b/examples/Chapter10/xmlMappings/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/xmlMappings + + + + + + \ No newline at end of file diff --git a/examples/Chapter10/xmlMappings/etc/sql/db.sql b/examples/Chapter10/xmlMappings/etc/sql/db.sql new file mode 100644 index 0000000..cf3a96c --- /dev/null +++ b/examples/Chapter10/xmlMappings/etc/sql/db.sql @@ -0,0 +1,80 @@ +DROP TABLE EMP_PRJ; +DROP TABLE EMP; +DROP TABLE EMP_ADDRESS; +DROP TABLE DEPARTMENT; +DROP TABLE ID_GEN; +DROP TABLE PARKINGSPACE; +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 DEPARTMENT (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE PARKINGSPACE (ID INTEGER NOT NULL, LOT INTEGER, LOCATION VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMP (ID INTEGER NOT NULL, NAME VARCHAR(255), STARTDATE DATE, + HOURLYRATE FLOAT, SALARY BIGINT, PENSION BIGINT, TYPE VARCHAR(32), + STREET VARCHAR(255), CITY VARCHAR(255), PROV VARCHAR(255), PCODE VARCHAR(255), + MGR INTEGER, DEPARTMENT_ID INTEGER, + CONSTRAINT MGR_FK FOREIGN KEY (MGR) REFERENCES EMP(ID), + CONSTRAINT DEPARTMENT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT(ID), + PRIMARY KEY (ID)); +CREATE TABLE EMP_ADDRESS (EMP_ID INTEGER NOT NULL, STREET VARCHAR(255), + CITY VARCHAR(255), PROV VARCHAR(255), PCODE VARCHAR(255), PRIMARY KEY (EMP_ID)); +CREATE TABLE EMP_PRJ(PROJ_ID INTEGER NOT NULL, EMP_ID INTEGER NOT NULL, + CONSTRAINT PROJECTS_FK FOREIGN KEY (PROJ_ID) REFERENCES PROJECT (ID), + CONSTRAINT EMPLOYEES_FK FOREIGN KEY (EMP_ID) REFERENCES EMP (ID), + PRIMARY KEY (PROJ_ID, EMP_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', 10); + +INSERT INTO PARKINGSPACE (ID, LOT, LOCATION) VALUES (1, 1, 'East Lot'); +INSERT INTO PARKINGSPACE (ID, LOT, LOCATION) VALUES (2, 2, 'West Lot'); +INSERT INTO PARKINGSPACE (ID, LOT, LOCATION) VALUES (5, 3, 'North Lot'); +INSERT INTO PARKINGSPACE (ID, LOT, LOCATION) VALUES (6, 4, 'South Lot'); + +INSERT INTO DEPARTMENT (NAME) VALUES ('Engineering'); +INSERT INTO DEPARTMENT (NAME) VALUES ('QA'); +INSERT INTO DEPARTMENT (NAME) VALUES ('Accounting'); + +INSERT INTO PROJECT (NAME) VALUES ('Design Release2'); +INSERT INTO PROJECT (NAME) VALUES ('Release1'); +INSERT INTO PROJECT (NAME) VALUES ('Test Release2'); + +INSERT INTO EMP (ID, NAME, STARTDATE, HOURLYRATE, PENSION, SALARY, TYPE, MGR, DEPARTMENT_ID) + VALUES (1, 'Patrick', {d '2004-07-01'}, NULL, 55000, 100000, 'FT', NULL, 1); +INSERT INTO EMP_ADDRESS (EMP_ID, CITY, PROV, STREET, PCODE) + VALUES (1, 'New York', 'NY', '123 Apple Tree Cr.', '10001'); +INSERT INTO EMP (ID, NAME, STARTDATE, HOURLYRATE, PENSION, SALARY, TYPE, MGR, DEPARTMENT_ID) + VALUES (2, 'Joan', {d '2003-09-09'}, NULL, 59000, 200000, 'FT', 1, 2); +INSERT INTO EMP_ADDRESS (EMP_ID, CITY, PROV, STREET, PCODE) + VALUES (2, 'Manhattan', 'NY', '654 Stanton Way.', '10003'); +INSERT INTO EMP (ID, NAME, STARTDATE, HOURLYRATE, PENSION, SALARY, TYPE, MGR, DEPARTMENT_ID) + VALUES (3, 'Samantha', {d '2000-03-12'}, NULL, 60000, 450000, 'FT', 1, 3); +INSERT INTO EMP_ADDRESS (EMP_ID, CITY, PROV, STREET, PCODE) + VALUES (3, 'New York', 'NY', '99 Queen St.', '10001'); +INSERT INTO EMP (ID, NAME, STARTDATE, HOURLYRATE, PENSION, SALARY, TYPE, MGR, DEPARTMENT_ID) + VALUES (4, 'Samantha', {d '2000-03-12'}, NULL, 60000, 450000, 'FT', 1, 1); +INSERT INTO EMP_ADDRESS (EMP_ID, CITY, PROV, STREET, PCODE) + VALUES (4, 'Redwood Shores', 'CA', '445 McDonell Cr.', '10001'); + +INSERT INTO EMP (ID, NAME, STARTDATE, HOURLYRATE, PENSION, SALARY, TYPE, MGR, DEPARTMENT_ID) + VALUES (5, 'Mark', {d '2004-11-01'}, 17.0, NULL, NULL, 'PT', NULL, 2); +INSERT INTO EMP_ADDRESS (EMP_ID, CITY, PROV, STREET, PCODE) + VALUES (5, 'San Jose', 'CA', '624 Hamilton Dr.', '90123'); +INSERT INTO EMP (ID, NAME, STARTDATE, HOURLYRATE, PENSION, SALARY, TYPE, MGR, DEPARTMENT_ID) + VALUES (6, 'Ryan', {d '2005-12-05'}, 16.0, NULL, NULL, 'PT', 5, 3); +INSERT INTO EMP_ADDRESS (EMP_ID, CITY, PROV, STREET, PCODE) + VALUES (6, 'San Jose', 'CA', '724 Coventry Rd.', '90123'); +INSERT INTO EMP (ID, NAME, STARTDATE, HOURLYRATE, PENSION, SALARY, TYPE, MGR, DEPARTMENT_ID) + VALUES (7, 'Jackie', {d '2006-01-03'}, 15.0, NULL, NULL, 'PT', 5, 1); +INSERT INTO EMP_ADDRESS (EMP_ID, CITY, PROV, STREET, PCODE) + VALUES (7, 'San Francisco', 'CA', '77 Manchester Blvd.', '90123'); +INSERT INTO EMP (ID, NAME, STARTDATE, HOURLYRATE, PENSION, SALARY, TYPE, MGR, DEPARTMENT_ID) + VALUES (8, 'Jackie', {d '2006-01-03'}, 15.0, NULL, NULL, 'PT', 5, 2); +INSERT INTO EMP_ADDRESS (EMP_ID, CITY, PROV, STREET, PCODE) + VALUES (8, 'San Jose', 'CA', '624 High Tech Ave.', '90123'); + +INSERT INTO EMP_PRJ (PROJ_ID, EMP_ID) VALUES (1, 1); + diff --git a/examples/Chapter10/xmlMappings/etc/web/WEB-INF/web.xml b/examples/Chapter10/xmlMappings/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter10/xmlMappings/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/Chapter10/xmlMappings/src/model/examples/model/Address.java b/examples/Chapter10/xmlMappings/src/model/examples/model/Address.java new file mode 100644 index 0000000..9c28f20 --- /dev/null +++ b/examples/Chapter10/xmlMappings/src/model/examples/model/Address.java @@ -0,0 +1,45 @@ +package examples.model; + +public class Address { + private String street; + private String city; + private String state; + private String zip; + + 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 getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getZip() { + return zip; + } + + public void setZip(String zip) { + this.zip = zip; + } + + public String toString() { + return "Address street: " + getStreet() + " city: " + getCity() + + ", state: " + getState(); + } +} diff --git a/examples/Chapter10/xmlMappings/src/model/examples/model/CompanyEmployee.java b/examples/Chapter10/xmlMappings/src/model/examples/model/CompanyEmployee.java new file mode 100644 index 0000000..a68fd16 --- /dev/null +++ b/examples/Chapter10/xmlMappings/src/model/examples/model/CompanyEmployee.java @@ -0,0 +1,13 @@ +package examples.model; + +public abstract class CompanyEmployee extends Employee { + private int vacation; + + public int getVacation() { + return vacation; + } + + public void setVacation(int vacation) { + this.vacation = vacation; + } +} diff --git a/examples/Chapter10/xmlMappings/src/model/examples/model/ContractEmployee.java b/examples/Chapter10/xmlMappings/src/model/examples/model/ContractEmployee.java new file mode 100644 index 0000000..8e84c71 --- /dev/null +++ b/examples/Chapter10/xmlMappings/src/model/examples/model/ContractEmployee.java @@ -0,0 +1,26 @@ +package examples.model; + +public class ContractEmployee extends Employee { + private int dailyRate; + private int term; + + public int getDailyRate() { + return dailyRate; + } + + public void setDailyRate(int dailyRate) { + this.dailyRate = dailyRate; + } + + public int getTerm() { + return term; + } + + public void setTerm(int term) { + this.term = term; + } + + public String toString() { + return "ContractEmployee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter10/xmlMappings/src/model/examples/model/Department.java b/examples/Chapter10/xmlMappings/src/model/examples/model/Department.java new file mode 100644 index 0000000..466b731 --- /dev/null +++ b/examples/Chapter10/xmlMappings/src/model/examples/model/Department.java @@ -0,0 +1,49 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +public class Department { + private int id; + private String name; + 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/Chapter10/xmlMappings/src/model/examples/model/Employee.java b/examples/Chapter10/xmlMappings/src/model/examples/model/Employee.java new file mode 100644 index 0000000..bf2fdab --- /dev/null +++ b/examples/Chapter10/xmlMappings/src/model/examples/model/Employee.java @@ -0,0 +1,77 @@ +package examples.model; + +import java.util.Date; +import java.util.Collection; + +public abstract class Employee { + private int id; + private String name; + private Date startDate; + private Address address; + private ParkingSpace parkingSpace; + private Employee manager; + private Department department; + private Collection projects; + private Collection directs; + + 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 getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public ParkingSpace getParkingSpace() { + return parkingSpace; + } + + public Address getAddress() { + return address; + } + + public Department getDepartment() { + return department; + } + + public Employee getManager() { + return manager; + } + + public void setDepartment(Department department) { + this.department = department; + } + + 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 String toString() { + return "Employee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter10/xmlMappings/src/model/examples/model/FullTimeEmployee.java b/examples/Chapter10/xmlMappings/src/model/examples/model/FullTimeEmployee.java new file mode 100644 index 0000000..59dcbf7 --- /dev/null +++ b/examples/Chapter10/xmlMappings/src/model/examples/model/FullTimeEmployee.java @@ -0,0 +1,26 @@ +package examples.model; + +public class FullTimeEmployee extends CompanyEmployee { + private long salary; + private long pension; + + public long getPension() { + return pension; + } + + public void setPension(long pension) { + this.pension = pension; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public String toString() { + return "FullTimeEmployee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter10/xmlMappings/src/model/examples/model/ParkingSpace.java b/examples/Chapter10/xmlMappings/src/model/examples/model/ParkingSpace.java new file mode 100644 index 0000000..577a406 --- /dev/null +++ b/examples/Chapter10/xmlMappings/src/model/examples/model/ParkingSpace.java @@ -0,0 +1,46 @@ +package examples.model; + + +public class ParkingSpace { + private int id; + private int lot; + private String location; + 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/Chapter10/xmlMappings/src/model/examples/model/PartTimeEmployee.java b/examples/Chapter10/xmlMappings/src/model/examples/model/PartTimeEmployee.java new file mode 100644 index 0000000..c4f8e88 --- /dev/null +++ b/examples/Chapter10/xmlMappings/src/model/examples/model/PartTimeEmployee.java @@ -0,0 +1,17 @@ +package examples.model; + +public class PartTimeEmployee extends CompanyEmployee { + private float hourlyRate; + + public float getHourlyRate() { + return hourlyRate; + } + + public void setHourlyRate(float hourlyRate) { + this.hourlyRate = hourlyRate; + } + + public String toString() { + return "PartTimeEmployee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter10/xmlMappings/src/model/examples/model/Project.java b/examples/Chapter10/xmlMappings/src/model/examples/model/Project.java new file mode 100644 index 0000000..f387095 --- /dev/null +++ b/examples/Chapter10/xmlMappings/src/model/examples/model/Project.java @@ -0,0 +1,48 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +public class Project { + protected int id; + protected String name; + 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/Chapter10/xmlMappings/src/model/examples/stateless/EmployeeService.java b/examples/Chapter10/xmlMappings/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..938e90d --- /dev/null +++ b/examples/Chapter10/xmlMappings/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/Chapter10/xmlMappings/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter10/xmlMappings/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..24219c6 --- /dev/null +++ b/examples/Chapter10/xmlMappings/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,21 @@ +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 Collection findAllEmployees() { + Query query = em.createNamedQuery("Employee.findAll"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter10/xmlMappings/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter10/xmlMappings/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..39f06b2 --- /dev/null +++ b/examples/Chapter10/xmlMappings/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,81 @@ +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 10: XML Mappings"; + + private final String DESCRIPTION = + "This example demonstrates the basics of xml mappings."; + + + @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("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("    " + emp.getAddress() + "
"); + out.println("    " + emp.getParkingSpace() + "
"); + out.println("    Manager: " + emp.getManager() + "
"); + out.println("    " + emp.getDepartment() + "
"); + out.println("
"); + } + } + } + + 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 to find all + out.println("

Find all

"); + out.println(""); + out.println(""); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter10/xmlMappings/undeploy.bat b/examples/Chapter10/xmlMappings/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter10/xmlMappings/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter11/01-ejbJarPackaging/build.xml b/examples/Chapter11/01-ejbJarPackaging/build.xml new file mode 100644 index 0000000..5384578 --- /dev/null +++ b/examples/Chapter11/01-ejbJarPackaging/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter11/01-ejbJarPackaging/deploy.bat b/examples/Chapter11/01-ejbJarPackaging/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter11/01-ejbJarPackaging/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter11/01-ejbJarPackaging/etc/persistence/META-INF/orm.xml b/examples/Chapter11/01-ejbJarPackaging/etc/persistence/META-INF/orm.xml new file mode 100644 index 0000000..17336e1 --- /dev/null +++ b/examples/Chapter11/01-ejbJarPackaging/etc/persistence/META-INF/orm.xml @@ -0,0 +1,17 @@ + + + + + + HR + + + + + SELECT e FROM Employee e + + + \ No newline at end of file diff --git a/examples/Chapter11/01-ejbJarPackaging/etc/persistence/META-INF/persistence.xml b/examples/Chapter11/01-ejbJarPackaging/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..6b672a9 --- /dev/null +++ b/examples/Chapter11/01-ejbJarPackaging/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,14 @@ + + + jdbc/ejbJarPackaging + + + + + + \ No newline at end of file diff --git a/examples/Chapter11/01-ejbJarPackaging/etc/sql/db.sql b/examples/Chapter11/01-ejbJarPackaging/etc/sql/db.sql new file mode 100644 index 0000000..c83f7bb --- /dev/null +++ b/examples/Chapter11/01-ejbJarPackaging/etc/sql/db.sql @@ -0,0 +1,95 @@ +DROP TABLE HR.DEPARTMENT; +DROP TABLE HR.PROJECT; +DROP TABLE HR.PROJECT_EMPLOYEE; +DROP TABLE HR.EMPLOYEE; +DROP TABLE HR.PHONE; +DROP TABLE HR.ADDRESS; + +CREATE TABLE HR.DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE HR.PROJECT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE HR.PROJECT_EMPLOYEE (EMPLOYEES_ID INTEGER, PROJECTS_ID INTEGER); +CREATE TABLE HR.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 HR.PHONE (ID BIGINT NOT NULL, NUMBER VARCHAR(255), TYPE VARCHAR(255), EMPLOYEE_ID INTEGER, PRIMARY KEY (ID)); +CREATE TABLE HR.ADDRESS (ID INTEGER NOT NULL, CITY VARCHAR(255), STATE VARCHAR(255), STREET VARCHAR(255), ZIP VARCHAR(255), PRIMARY KEY (ID)); + + +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (1, 'New York', 'NY', '123 Apple Tree Cr.', '10001'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (2, 'Manhattan', 'NY', '654 Stanton Way.', '10003'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (3, 'New York', 'NY', '99 Queen St.', '10001'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (4, 'Redwood Shores', 'CA', '445 McDonell Cr.', '90123'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (5, 'San Jose', 'CA', '624 Hamilton Dr.', '90123'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (6, 'San Jose', 'CA', '724 Coventry Rd.', '90123'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (7, 'San Francisco', 'CA', '77 Manchester Blvd.', '90123'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (8, 'Moorestown', 'NJ', '53 King St.', '08057'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (9, 'New York', 'NY', '14 Industrial Ave.', '10001'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (10, 'Redwood Shores', 'CA', '777 High Tech Ln.', '90123'); + +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (2, 'QA'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (3, 'Accounting'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (4, 'CAEngOtt'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (5, 'USEngCal'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (6, 'CADocOtt'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (7, 'QA_East'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (8, 'QANorth'); + +INSERT INTO HR.PROJECT (ID, NAME) VALUES (1, 'Design Release2'); +INSERT INTO HR.PROJECT (ID, NAME) VALUES (2, 'Release1'); +INSERT INTO HR.PROJECT (ID, NAME) VALUES (3, 'Test Release2'); +INSERT INTO HR.PROJECT (ID, NAME) VALUES (4, 'Implement Release3'); + +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (1, 'John', 55000, {d '2001-01-01'}, 1, 2, 9); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (2, 'Rob', 53000, {d '2001-05-23'}, 2, 2, 9); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (3, 'Peter', 40000, {d '2002-08-06'}, 3, 2, 9); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (4, 'Frank', 41000, {d '2003-02-17'}, 4, 1, 10); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (5, 'Scott', 60000, {d '2004-11-14'}, 5, 1, 10); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (6, 'Sue', 62000, {d '2005-08-18'}, 6, 1, 10); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (7, 'Stephanie', 54000, {d '2006-06-07'}, 7, 1, 10); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (8, 'Jennifer', 45000, {d '1999-08-11'}, 8, 1, NULL); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (9, 'Sarah', 52000, {d '2002-04-26'}, 9, 2, 10); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (10, 'Joan', 59000, {d '2003-04-16'}, 10, 1, NULL); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (11, 'Marcus', 35000, {d '1995-07-22'}, NULL, NULL, NULL); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (12, 'Joe', 36000, {d '1995-07-22'}, NULL, 3, 11); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (13, 'Jack', 43000, {d '1995-07-22'}, NULL, 3, NULL); + +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (1, '(212)555-1234', 'Office', 1); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (2, '(212)555-9843', 'Home', 1); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (3, '(315)555-6253', 'Office', 2); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (4, '(516)555-9837', 'Office', 3); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (5, '(516)555-2034', 'Cell', 3); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (6, '(650)555-7583', 'Office', 4); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (7, '(650)555-5345', 'Home', 4); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (8, '(650)555-9386', 'Office', 5); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (9, '(650)555-4885', 'Cell', 5); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (10, '(650)555-3836', 'Office', 6); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (11, '(650)555-0985', 'Home', 6); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (12, '(650)555-1946', 'Cell', 6); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (13, '(650)555-4759', 'Office', 7); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (14, '(650)555-4757', 'Home', 7); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (15, '(650)555-6753', 'Office', 8); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (16, '(585)555-0693', 'Office', 9); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (17, '(585)555-3098', 'Home', 9); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (18, '(585)555-1457', 'Cell', 9); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (19, '(650)555-9838', 'Office', 10); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (20, '(650)555-2346', 'Home', 10); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (21, '(650)555-9874', 'Cell', 10); + +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (1, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 2); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 3); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 2); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 3); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (4, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 2); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 3); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 2); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (7, 3); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 2); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 3); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 2); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 3); \ No newline at end of file diff --git a/examples/Chapter11/01-ejbJarPackaging/etc/web/WEB-INF/web.xml b/examples/Chapter11/01-ejbJarPackaging/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter11/01-ejbJarPackaging/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/Chapter11/01-ejbJarPackaging/src/model/examples/model/Address.java b/examples/Chapter11/01-ejbJarPackaging/src/model/examples/model/Address.java new file mode 100644 index 0000000..e18406b --- /dev/null +++ b/examples/Chapter11/01-ejbJarPackaging/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/Chapter11/01-ejbJarPackaging/src/model/examples/model/Department.java b/examples/Chapter11/01-ejbJarPackaging/src/model/examples/model/Department.java new file mode 100644 index 0000000..a1ac11c --- /dev/null +++ b/examples/Chapter11/01-ejbJarPackaging/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/Chapter11/01-ejbJarPackaging/src/model/examples/model/Employee.java b/examples/Chapter11/01-ejbJarPackaging/src/model/examples/model/Employee.java new file mode 100644 index 0000000..806ef9f --- /dev/null +++ b/examples/Chapter11/01-ejbJarPackaging/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/Chapter11/01-ejbJarPackaging/src/model/examples/model/Phone.java b/examples/Chapter11/01-ejbJarPackaging/src/model/examples/model/Phone.java new file mode 100644 index 0000000..afa5419 --- /dev/null +++ b/examples/Chapter11/01-ejbJarPackaging/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/Chapter11/01-ejbJarPackaging/src/model/examples/model/Project.java b/examples/Chapter11/01-ejbJarPackaging/src/model/examples/model/Project.java new file mode 100644 index 0000000..6b56951 --- /dev/null +++ b/examples/Chapter11/01-ejbJarPackaging/src/model/examples/model/Project.java @@ -0,0 +1,52 @@ +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 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/Chapter11/01-ejbJarPackaging/src/model/examples/stateless/EmployeeService.java b/examples/Chapter11/01-ejbJarPackaging/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..938e90d --- /dev/null +++ b/examples/Chapter11/01-ejbJarPackaging/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/Chapter11/01-ejbJarPackaging/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter11/01-ejbJarPackaging/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..24219c6 --- /dev/null +++ b/examples/Chapter11/01-ejbJarPackaging/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,21 @@ +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 Collection findAllEmployees() { + Query query = em.createNamedQuery("Employee.findAll"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter11/01-ejbJarPackaging/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter11/01-ejbJarPackaging/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..8a23263 --- /dev/null +++ b/examples/Chapter11/01-ejbJarPackaging/src/servlet/examples/servlet/EmployeeServlet.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.model.Employee; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 11: Entities Packaged in an EJB JAR"; + + private final String DESCRIPTION = + "This example demonstrates how to package entities in an ejb jar."; + + + @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("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("    " + emp.getAddress() + "
"); + out.println("    " + emp.getDepartment() + "
"); + out.println("    Phones: " + emp.getPhones() + "
"); + out.println("
"); + } + } + } + + 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 to find all + out.println("

Find all

"); + out.println(""); + out.println(""); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter11/01-ejbJarPackaging/undeploy.bat b/examples/Chapter11/01-ejbJarPackaging/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter11/01-ejbJarPackaging/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter11/02-externalJarPackaging/build.xml b/examples/Chapter11/02-externalJarPackaging/build.xml new file mode 100644 index 0000000..a448358 --- /dev/null +++ b/examples/Chapter11/02-externalJarPackaging/build.xml @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Chapter11/02-externalJarPackaging/deploy.bat b/examples/Chapter11/02-externalJarPackaging/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter11/02-externalJarPackaging/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter11/02-externalJarPackaging/etc/emp-classes/META-INF/emp-mappings.xml b/examples/Chapter11/02-externalJarPackaging/etc/emp-classes/META-INF/emp-mappings.xml new file mode 100644 index 0000000..ef9f13d --- /dev/null +++ b/examples/Chapter11/02-externalJarPackaging/etc/emp-classes/META-INF/emp-mappings.xml @@ -0,0 +1,11 @@ + + + + + SELECT e FROM Employee e + + + \ No newline at end of file diff --git a/examples/Chapter11/02-externalJarPackaging/etc/emp-classes/META-INF/orm.xml b/examples/Chapter11/02-externalJarPackaging/etc/emp-classes/META-INF/orm.xml new file mode 100644 index 0000000..66b19de --- /dev/null +++ b/examples/Chapter11/02-externalJarPackaging/etc/emp-classes/META-INF/orm.xml @@ -0,0 +1,12 @@ + + + + + + HR + + + \ No newline at end of file diff --git a/examples/Chapter11/02-externalJarPackaging/etc/persistence/META-INF/MANIFEST.MF b/examples/Chapter11/02-externalJarPackaging/etc/persistence/META-INF/MANIFEST.MF new file mode 100644 index 0000000..2fa7e8e --- /dev/null +++ b/examples/Chapter11/02-externalJarPackaging/etc/persistence/META-INF/MANIFEST.MF @@ -0,0 +1,2 @@ +Manifest-Version: 1.0 +Class-Path: emp-classes.jar diff --git a/examples/Chapter11/02-externalJarPackaging/etc/persistence/META-INF/persistence.xml b/examples/Chapter11/02-externalJarPackaging/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..15e2e1c --- /dev/null +++ b/examples/Chapter11/02-externalJarPackaging/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,16 @@ + + + jdbc/externalJarPackaging + META-INF/emp-mappings.xml + emp-classes.jar + + + + + + \ No newline at end of file diff --git a/examples/Chapter11/02-externalJarPackaging/etc/sql/db.sql b/examples/Chapter11/02-externalJarPackaging/etc/sql/db.sql new file mode 100644 index 0000000..c83f7bb --- /dev/null +++ b/examples/Chapter11/02-externalJarPackaging/etc/sql/db.sql @@ -0,0 +1,95 @@ +DROP TABLE HR.DEPARTMENT; +DROP TABLE HR.PROJECT; +DROP TABLE HR.PROJECT_EMPLOYEE; +DROP TABLE HR.EMPLOYEE; +DROP TABLE HR.PHONE; +DROP TABLE HR.ADDRESS; + +CREATE TABLE HR.DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE HR.PROJECT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE HR.PROJECT_EMPLOYEE (EMPLOYEES_ID INTEGER, PROJECTS_ID INTEGER); +CREATE TABLE HR.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 HR.PHONE (ID BIGINT NOT NULL, NUMBER VARCHAR(255), TYPE VARCHAR(255), EMPLOYEE_ID INTEGER, PRIMARY KEY (ID)); +CREATE TABLE HR.ADDRESS (ID INTEGER NOT NULL, CITY VARCHAR(255), STATE VARCHAR(255), STREET VARCHAR(255), ZIP VARCHAR(255), PRIMARY KEY (ID)); + + +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (1, 'New York', 'NY', '123 Apple Tree Cr.', '10001'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (2, 'Manhattan', 'NY', '654 Stanton Way.', '10003'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (3, 'New York', 'NY', '99 Queen St.', '10001'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (4, 'Redwood Shores', 'CA', '445 McDonell Cr.', '90123'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (5, 'San Jose', 'CA', '624 Hamilton Dr.', '90123'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (6, 'San Jose', 'CA', '724 Coventry Rd.', '90123'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (7, 'San Francisco', 'CA', '77 Manchester Blvd.', '90123'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (8, 'Moorestown', 'NJ', '53 King St.', '08057'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (9, 'New York', 'NY', '14 Industrial Ave.', '10001'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (10, 'Redwood Shores', 'CA', '777 High Tech Ln.', '90123'); + +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (2, 'QA'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (3, 'Accounting'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (4, 'CAEngOtt'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (5, 'USEngCal'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (6, 'CADocOtt'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (7, 'QA_East'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (8, 'QANorth'); + +INSERT INTO HR.PROJECT (ID, NAME) VALUES (1, 'Design Release2'); +INSERT INTO HR.PROJECT (ID, NAME) VALUES (2, 'Release1'); +INSERT INTO HR.PROJECT (ID, NAME) VALUES (3, 'Test Release2'); +INSERT INTO HR.PROJECT (ID, NAME) VALUES (4, 'Implement Release3'); + +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (1, 'John', 55000, {d '2001-01-01'}, 1, 2, 9); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (2, 'Rob', 53000, {d '2001-05-23'}, 2, 2, 9); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (3, 'Peter', 40000, {d '2002-08-06'}, 3, 2, 9); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (4, 'Frank', 41000, {d '2003-02-17'}, 4, 1, 10); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (5, 'Scott', 60000, {d '2004-11-14'}, 5, 1, 10); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (6, 'Sue', 62000, {d '2005-08-18'}, 6, 1, 10); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (7, 'Stephanie', 54000, {d '2006-06-07'}, 7, 1, 10); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (8, 'Jennifer', 45000, {d '1999-08-11'}, 8, 1, NULL); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (9, 'Sarah', 52000, {d '2002-04-26'}, 9, 2, 10); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (10, 'Joan', 59000, {d '2003-04-16'}, 10, 1, NULL); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (11, 'Marcus', 35000, {d '1995-07-22'}, NULL, NULL, NULL); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (12, 'Joe', 36000, {d '1995-07-22'}, NULL, 3, 11); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (13, 'Jack', 43000, {d '1995-07-22'}, NULL, 3, NULL); + +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (1, '(212)555-1234', 'Office', 1); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (2, '(212)555-9843', 'Home', 1); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (3, '(315)555-6253', 'Office', 2); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (4, '(516)555-9837', 'Office', 3); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (5, '(516)555-2034', 'Cell', 3); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (6, '(650)555-7583', 'Office', 4); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (7, '(650)555-5345', 'Home', 4); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (8, '(650)555-9386', 'Office', 5); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (9, '(650)555-4885', 'Cell', 5); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (10, '(650)555-3836', 'Office', 6); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (11, '(650)555-0985', 'Home', 6); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (12, '(650)555-1946', 'Cell', 6); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (13, '(650)555-4759', 'Office', 7); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (14, '(650)555-4757', 'Home', 7); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (15, '(650)555-6753', 'Office', 8); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (16, '(585)555-0693', 'Office', 9); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (17, '(585)555-3098', 'Home', 9); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (18, '(585)555-1457', 'Cell', 9); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (19, '(650)555-9838', 'Office', 10); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (20, '(650)555-2346', 'Home', 10); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (21, '(650)555-9874', 'Cell', 10); + +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (1, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 2); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 3); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 2); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 3); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (4, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 2); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 3); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 2); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (7, 3); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 2); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 3); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 2); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 3); \ No newline at end of file diff --git a/examples/Chapter11/02-externalJarPackaging/etc/web/WEB-INF/web.xml b/examples/Chapter11/02-externalJarPackaging/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter11/02-externalJarPackaging/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/Chapter11/02-externalJarPackaging/src/emp-classes/examples/model/Address.java b/examples/Chapter11/02-externalJarPackaging/src/emp-classes/examples/model/Address.java new file mode 100644 index 0000000..e18406b --- /dev/null +++ b/examples/Chapter11/02-externalJarPackaging/src/emp-classes/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/Chapter11/02-externalJarPackaging/src/emp-classes/examples/model/Department.java b/examples/Chapter11/02-externalJarPackaging/src/emp-classes/examples/model/Department.java new file mode 100644 index 0000000..a1ac11c --- /dev/null +++ b/examples/Chapter11/02-externalJarPackaging/src/emp-classes/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/Chapter11/02-externalJarPackaging/src/emp-classes/examples/model/Employee.java b/examples/Chapter11/02-externalJarPackaging/src/emp-classes/examples/model/Employee.java new file mode 100644 index 0000000..806ef9f --- /dev/null +++ b/examples/Chapter11/02-externalJarPackaging/src/emp-classes/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/Chapter11/02-externalJarPackaging/src/emp-classes/examples/model/Phone.java b/examples/Chapter11/02-externalJarPackaging/src/emp-classes/examples/model/Phone.java new file mode 100644 index 0000000..afa5419 --- /dev/null +++ b/examples/Chapter11/02-externalJarPackaging/src/emp-classes/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/Chapter11/02-externalJarPackaging/src/emp-classes/examples/model/Project.java b/examples/Chapter11/02-externalJarPackaging/src/emp-classes/examples/model/Project.java new file mode 100644 index 0000000..6b56951 --- /dev/null +++ b/examples/Chapter11/02-externalJarPackaging/src/emp-classes/examples/model/Project.java @@ -0,0 +1,52 @@ +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 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/Chapter11/02-externalJarPackaging/src/model/examples/stateless/EmployeeService.java b/examples/Chapter11/02-externalJarPackaging/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..938e90d --- /dev/null +++ b/examples/Chapter11/02-externalJarPackaging/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/Chapter11/02-externalJarPackaging/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter11/02-externalJarPackaging/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..24219c6 --- /dev/null +++ b/examples/Chapter11/02-externalJarPackaging/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,21 @@ +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 Collection findAllEmployees() { + Query query = em.createNamedQuery("Employee.findAll"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter11/02-externalJarPackaging/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter11/02-externalJarPackaging/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..713e8b0 --- /dev/null +++ b/examples/Chapter11/02-externalJarPackaging/src/servlet/examples/servlet/EmployeeServlet.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.model.Employee; +import examples.stateless.EmployeeService; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 11: Entities Packaged in an External JAR"; + + private final String DESCRIPTION = + "This example demonstrates how to package entities in an external jar."; + + + @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("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("    " + emp.getAddress() + "
"); + out.println("    " + emp.getDepartment() + "
"); + out.println("    Phones: " + emp.getPhones() + "
"); + out.println("
"); + } + } + } + + 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 to find all + out.println("

Find all

"); + out.println(""); + out.println(""); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter11/02-externalJarPackaging/undeploy.bat b/examples/Chapter11/02-externalJarPackaging/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter11/02-externalJarPackaging/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter11/03-webInfClassesPackaging/build.xml b/examples/Chapter11/03-webInfClassesPackaging/build.xml new file mode 100644 index 0000000..2b111e5 --- /dev/null +++ b/examples/Chapter11/03-webInfClassesPackaging/build.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Chapter11/03-webInfClassesPackaging/deploy.bat b/examples/Chapter11/03-webInfClassesPackaging/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter11/03-webInfClassesPackaging/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter11/03-webInfClassesPackaging/etc/persistence/META-INF/orm.xml b/examples/Chapter11/03-webInfClassesPackaging/etc/persistence/META-INF/orm.xml new file mode 100644 index 0000000..17336e1 --- /dev/null +++ b/examples/Chapter11/03-webInfClassesPackaging/etc/persistence/META-INF/orm.xml @@ -0,0 +1,17 @@ + + + + + + HR + + + + + SELECT e FROM Employee e + + + \ No newline at end of file diff --git a/examples/Chapter11/03-webInfClassesPackaging/etc/persistence/META-INF/persistence.xml b/examples/Chapter11/03-webInfClassesPackaging/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..3c79b7f --- /dev/null +++ b/examples/Chapter11/03-webInfClassesPackaging/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,14 @@ + + + jdbc/webInfClassesPackaging + + + + + + \ No newline at end of file diff --git a/examples/Chapter11/03-webInfClassesPackaging/etc/sql/db.sql b/examples/Chapter11/03-webInfClassesPackaging/etc/sql/db.sql new file mode 100644 index 0000000..c83f7bb --- /dev/null +++ b/examples/Chapter11/03-webInfClassesPackaging/etc/sql/db.sql @@ -0,0 +1,95 @@ +DROP TABLE HR.DEPARTMENT; +DROP TABLE HR.PROJECT; +DROP TABLE HR.PROJECT_EMPLOYEE; +DROP TABLE HR.EMPLOYEE; +DROP TABLE HR.PHONE; +DROP TABLE HR.ADDRESS; + +CREATE TABLE HR.DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE HR.PROJECT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE HR.PROJECT_EMPLOYEE (EMPLOYEES_ID INTEGER, PROJECTS_ID INTEGER); +CREATE TABLE HR.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 HR.PHONE (ID BIGINT NOT NULL, NUMBER VARCHAR(255), TYPE VARCHAR(255), EMPLOYEE_ID INTEGER, PRIMARY KEY (ID)); +CREATE TABLE HR.ADDRESS (ID INTEGER NOT NULL, CITY VARCHAR(255), STATE VARCHAR(255), STREET VARCHAR(255), ZIP VARCHAR(255), PRIMARY KEY (ID)); + + +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (1, 'New York', 'NY', '123 Apple Tree Cr.', '10001'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (2, 'Manhattan', 'NY', '654 Stanton Way.', '10003'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (3, 'New York', 'NY', '99 Queen St.', '10001'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (4, 'Redwood Shores', 'CA', '445 McDonell Cr.', '90123'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (5, 'San Jose', 'CA', '624 Hamilton Dr.', '90123'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (6, 'San Jose', 'CA', '724 Coventry Rd.', '90123'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (7, 'San Francisco', 'CA', '77 Manchester Blvd.', '90123'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (8, 'Moorestown', 'NJ', '53 King St.', '08057'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (9, 'New York', 'NY', '14 Industrial Ave.', '10001'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (10, 'Redwood Shores', 'CA', '777 High Tech Ln.', '90123'); + +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (2, 'QA'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (3, 'Accounting'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (4, 'CAEngOtt'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (5, 'USEngCal'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (6, 'CADocOtt'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (7, 'QA_East'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (8, 'QANorth'); + +INSERT INTO HR.PROJECT (ID, NAME) VALUES (1, 'Design Release2'); +INSERT INTO HR.PROJECT (ID, NAME) VALUES (2, 'Release1'); +INSERT INTO HR.PROJECT (ID, NAME) VALUES (3, 'Test Release2'); +INSERT INTO HR.PROJECT (ID, NAME) VALUES (4, 'Implement Release3'); + +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (1, 'John', 55000, {d '2001-01-01'}, 1, 2, 9); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (2, 'Rob', 53000, {d '2001-05-23'}, 2, 2, 9); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (3, 'Peter', 40000, {d '2002-08-06'}, 3, 2, 9); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (4, 'Frank', 41000, {d '2003-02-17'}, 4, 1, 10); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (5, 'Scott', 60000, {d '2004-11-14'}, 5, 1, 10); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (6, 'Sue', 62000, {d '2005-08-18'}, 6, 1, 10); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (7, 'Stephanie', 54000, {d '2006-06-07'}, 7, 1, 10); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (8, 'Jennifer', 45000, {d '1999-08-11'}, 8, 1, NULL); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (9, 'Sarah', 52000, {d '2002-04-26'}, 9, 2, 10); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (10, 'Joan', 59000, {d '2003-04-16'}, 10, 1, NULL); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (11, 'Marcus', 35000, {d '1995-07-22'}, NULL, NULL, NULL); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (12, 'Joe', 36000, {d '1995-07-22'}, NULL, 3, 11); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (13, 'Jack', 43000, {d '1995-07-22'}, NULL, 3, NULL); + +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (1, '(212)555-1234', 'Office', 1); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (2, '(212)555-9843', 'Home', 1); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (3, '(315)555-6253', 'Office', 2); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (4, '(516)555-9837', 'Office', 3); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (5, '(516)555-2034', 'Cell', 3); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (6, '(650)555-7583', 'Office', 4); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (7, '(650)555-5345', 'Home', 4); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (8, '(650)555-9386', 'Office', 5); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (9, '(650)555-4885', 'Cell', 5); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (10, '(650)555-3836', 'Office', 6); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (11, '(650)555-0985', 'Home', 6); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (12, '(650)555-1946', 'Cell', 6); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (13, '(650)555-4759', 'Office', 7); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (14, '(650)555-4757', 'Home', 7); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (15, '(650)555-6753', 'Office', 8); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (16, '(585)555-0693', 'Office', 9); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (17, '(585)555-3098', 'Home', 9); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (18, '(585)555-1457', 'Cell', 9); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (19, '(650)555-9838', 'Office', 10); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (20, '(650)555-2346', 'Home', 10); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (21, '(650)555-9874', 'Cell', 10); + +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (1, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 2); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 3); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 2); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 3); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (4, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 2); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 3); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 2); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (7, 3); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 2); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 3); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 2); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 3); \ No newline at end of file diff --git a/examples/Chapter11/03-webInfClassesPackaging/etc/web/WEB-INF/web.xml b/examples/Chapter11/03-webInfClassesPackaging/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter11/03-webInfClassesPackaging/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/Chapter11/03-webInfClassesPackaging/src/model/examples/model/Address.java b/examples/Chapter11/03-webInfClassesPackaging/src/model/examples/model/Address.java new file mode 100644 index 0000000..e18406b --- /dev/null +++ b/examples/Chapter11/03-webInfClassesPackaging/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/Chapter11/03-webInfClassesPackaging/src/model/examples/model/Department.java b/examples/Chapter11/03-webInfClassesPackaging/src/model/examples/model/Department.java new file mode 100644 index 0000000..a1ac11c --- /dev/null +++ b/examples/Chapter11/03-webInfClassesPackaging/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/Chapter11/03-webInfClassesPackaging/src/model/examples/model/Employee.java b/examples/Chapter11/03-webInfClassesPackaging/src/model/examples/model/Employee.java new file mode 100644 index 0000000..806ef9f --- /dev/null +++ b/examples/Chapter11/03-webInfClassesPackaging/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/Chapter11/03-webInfClassesPackaging/src/model/examples/model/Phone.java b/examples/Chapter11/03-webInfClassesPackaging/src/model/examples/model/Phone.java new file mode 100644 index 0000000..afa5419 --- /dev/null +++ b/examples/Chapter11/03-webInfClassesPackaging/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/Chapter11/03-webInfClassesPackaging/src/model/examples/model/Project.java b/examples/Chapter11/03-webInfClassesPackaging/src/model/examples/model/Project.java new file mode 100644 index 0000000..6b56951 --- /dev/null +++ b/examples/Chapter11/03-webInfClassesPackaging/src/model/examples/model/Project.java @@ -0,0 +1,52 @@ +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 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/Chapter11/03-webInfClassesPackaging/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter11/03-webInfClassesPackaging/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..9d3cb86 --- /dev/null +++ b/examples/Chapter11/03-webInfClassesPackaging/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,83 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.persistence.Query; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import examples.model.Employee; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 11: Entities Packaged in the WEB-INF/classes folder of a WAR"; + + private final String DESCRIPTION = + "This example demonstrates how to package entities in a WAR."; + + + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + 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("FindAll")) { + Query query = em.createNamedQuery("Employee.findAll"); + Collection emps = (Collection) query.getResultList(); + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + out.println("    " + emp.getAddress() + "
"); + out.println("    " + emp.getDepartment() + "
"); + out.println("    Phones: " + emp.getPhones() + "
"); + out.println("
"); + } + } + } + + 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 to find all + out.println("

Find all

"); + out.println(""); + out.println(""); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter11/03-webInfClassesPackaging/undeploy.bat b/examples/Chapter11/03-webInfClassesPackaging/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter11/03-webInfClassesPackaging/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter11/04-persistenceArchivePackaging/build.xml b/examples/Chapter11/04-persistenceArchivePackaging/build.xml new file mode 100644 index 0000000..4af3a5f --- /dev/null +++ b/examples/Chapter11/04-persistenceArchivePackaging/build.xml @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Chapter11/04-persistenceArchivePackaging/deploy.bat b/examples/Chapter11/04-persistenceArchivePackaging/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter11/04-persistenceArchivePackaging/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter11/04-persistenceArchivePackaging/etc/emp-persistence/META-INF/orm.xml b/examples/Chapter11/04-persistenceArchivePackaging/etc/emp-persistence/META-INF/orm.xml new file mode 100644 index 0000000..17336e1 --- /dev/null +++ b/examples/Chapter11/04-persistenceArchivePackaging/etc/emp-persistence/META-INF/orm.xml @@ -0,0 +1,17 @@ + + + + + + HR + + + + + SELECT e FROM Employee e + + + \ No newline at end of file diff --git a/examples/Chapter11/04-persistenceArchivePackaging/etc/emp-persistence/META-INF/persistence.xml b/examples/Chapter11/04-persistenceArchivePackaging/etc/emp-persistence/META-INF/persistence.xml new file mode 100644 index 0000000..3cbd0dd --- /dev/null +++ b/examples/Chapter11/04-persistenceArchivePackaging/etc/emp-persistence/META-INF/persistence.xml @@ -0,0 +1,14 @@ + + + jdbc/persistenceArchivePackaging + + + + + + \ No newline at end of file diff --git a/examples/Chapter11/04-persistenceArchivePackaging/etc/sql/db.sql b/examples/Chapter11/04-persistenceArchivePackaging/etc/sql/db.sql new file mode 100644 index 0000000..c83f7bb --- /dev/null +++ b/examples/Chapter11/04-persistenceArchivePackaging/etc/sql/db.sql @@ -0,0 +1,95 @@ +DROP TABLE HR.DEPARTMENT; +DROP TABLE HR.PROJECT; +DROP TABLE HR.PROJECT_EMPLOYEE; +DROP TABLE HR.EMPLOYEE; +DROP TABLE HR.PHONE; +DROP TABLE HR.ADDRESS; + +CREATE TABLE HR.DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE HR.PROJECT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE HR.PROJECT_EMPLOYEE (EMPLOYEES_ID INTEGER, PROJECTS_ID INTEGER); +CREATE TABLE HR.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 HR.PHONE (ID BIGINT NOT NULL, NUMBER VARCHAR(255), TYPE VARCHAR(255), EMPLOYEE_ID INTEGER, PRIMARY KEY (ID)); +CREATE TABLE HR.ADDRESS (ID INTEGER NOT NULL, CITY VARCHAR(255), STATE VARCHAR(255), STREET VARCHAR(255), ZIP VARCHAR(255), PRIMARY KEY (ID)); + + +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (1, 'New York', 'NY', '123 Apple Tree Cr.', '10001'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (2, 'Manhattan', 'NY', '654 Stanton Way.', '10003'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (3, 'New York', 'NY', '99 Queen St.', '10001'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (4, 'Redwood Shores', 'CA', '445 McDonell Cr.', '90123'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (5, 'San Jose', 'CA', '624 Hamilton Dr.', '90123'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (6, 'San Jose', 'CA', '724 Coventry Rd.', '90123'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (7, 'San Francisco', 'CA', '77 Manchester Blvd.', '90123'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (8, 'Moorestown', 'NJ', '53 King St.', '08057'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (9, 'New York', 'NY', '14 Industrial Ave.', '10001'); +INSERT INTO HR.ADDRESS (ID, CITY, STATE, STREET, ZIP) VALUES (10, 'Redwood Shores', 'CA', '777 High Tech Ln.', '90123'); + +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (2, 'QA'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (3, 'Accounting'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (4, 'CAEngOtt'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (5, 'USEngCal'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (6, 'CADocOtt'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (7, 'QA_East'); +INSERT INTO HR.DEPARTMENT (ID, NAME) VALUES (8, 'QANorth'); + +INSERT INTO HR.PROJECT (ID, NAME) VALUES (1, 'Design Release2'); +INSERT INTO HR.PROJECT (ID, NAME) VALUES (2, 'Release1'); +INSERT INTO HR.PROJECT (ID, NAME) VALUES (3, 'Test Release2'); +INSERT INTO HR.PROJECT (ID, NAME) VALUES (4, 'Implement Release3'); + +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (1, 'John', 55000, {d '2001-01-01'}, 1, 2, 9); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (2, 'Rob', 53000, {d '2001-05-23'}, 2, 2, 9); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (3, 'Peter', 40000, {d '2002-08-06'}, 3, 2, 9); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (4, 'Frank', 41000, {d '2003-02-17'}, 4, 1, 10); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (5, 'Scott', 60000, {d '2004-11-14'}, 5, 1, 10); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (6, 'Sue', 62000, {d '2005-08-18'}, 6, 1, 10); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (7, 'Stephanie', 54000, {d '2006-06-07'}, 7, 1, 10); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (8, 'Jennifer', 45000, {d '1999-08-11'}, 8, 1, NULL); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (9, 'Sarah', 52000, {d '2002-04-26'}, 9, 2, 10); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (10, 'Joan', 59000, {d '2003-04-16'}, 10, 1, NULL); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (11, 'Marcus', 35000, {d '1995-07-22'}, NULL, NULL, NULL); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (12, 'Joe', 36000, {d '1995-07-22'}, NULL, 3, 11); +INSERT INTO HR.EMPLOYEE (ID, NAME, SALARY, STARTDATE, ADDRESS_ID, DEPARTMENT_ID, MANAGER_ID) VALUES (13, 'Jack', 43000, {d '1995-07-22'}, NULL, 3, NULL); + +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (1, '(212)555-1234', 'Office', 1); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (2, '(212)555-9843', 'Home', 1); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (3, '(315)555-6253', 'Office', 2); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (4, '(516)555-9837', 'Office', 3); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (5, '(516)555-2034', 'Cell', 3); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (6, '(650)555-7583', 'Office', 4); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (7, '(650)555-5345', 'Home', 4); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (8, '(650)555-9386', 'Office', 5); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (9, '(650)555-4885', 'Cell', 5); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (10, '(650)555-3836', 'Office', 6); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (11, '(650)555-0985', 'Home', 6); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (12, '(650)555-1946', 'Cell', 6); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (13, '(650)555-4759', 'Office', 7); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (14, '(650)555-4757', 'Home', 7); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (15, '(650)555-6753', 'Office', 8); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (16, '(585)555-0693', 'Office', 9); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (17, '(585)555-3098', 'Home', 9); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (18, '(585)555-1457', 'Cell', 9); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (19, '(650)555-9838', 'Office', 10); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (20, '(650)555-2346', 'Home', 10); +INSERT INTO HR.PHONE (ID, NUMBER, TYPE, EMPLOYEE_ID) VALUES (21, '(650)555-9874', 'Cell', 10); + +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (1, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 2); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (2, 3); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 2); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (3, 3); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (4, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 2); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (5, 3); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (6, 2); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (7, 3); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (8, 2); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 3); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (9, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 1); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 2); +INSERT INTO HR.PROJECT_EMPLOYEE (EMPLOYEES_ID, PROJECTS_ID) VALUES (10, 3); \ No newline at end of file diff --git a/examples/Chapter11/04-persistenceArchivePackaging/etc/web/WEB-INF/web.xml b/examples/Chapter11/04-persistenceArchivePackaging/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter11/04-persistenceArchivePackaging/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/Chapter11/04-persistenceArchivePackaging/src/emp-persistence/examples/model/Address.java b/examples/Chapter11/04-persistenceArchivePackaging/src/emp-persistence/examples/model/Address.java new file mode 100644 index 0000000..e18406b --- /dev/null +++ b/examples/Chapter11/04-persistenceArchivePackaging/src/emp-persistence/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/Chapter11/04-persistenceArchivePackaging/src/emp-persistence/examples/model/Department.java b/examples/Chapter11/04-persistenceArchivePackaging/src/emp-persistence/examples/model/Department.java new file mode 100644 index 0000000..a1ac11c --- /dev/null +++ b/examples/Chapter11/04-persistenceArchivePackaging/src/emp-persistence/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/Chapter11/04-persistenceArchivePackaging/src/emp-persistence/examples/model/Employee.java b/examples/Chapter11/04-persistenceArchivePackaging/src/emp-persistence/examples/model/Employee.java new file mode 100644 index 0000000..806ef9f --- /dev/null +++ b/examples/Chapter11/04-persistenceArchivePackaging/src/emp-persistence/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/Chapter11/04-persistenceArchivePackaging/src/emp-persistence/examples/model/Phone.java b/examples/Chapter11/04-persistenceArchivePackaging/src/emp-persistence/examples/model/Phone.java new file mode 100644 index 0000000..afa5419 --- /dev/null +++ b/examples/Chapter11/04-persistenceArchivePackaging/src/emp-persistence/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/Chapter11/04-persistenceArchivePackaging/src/emp-persistence/examples/model/Project.java b/examples/Chapter11/04-persistenceArchivePackaging/src/emp-persistence/examples/model/Project.java new file mode 100644 index 0000000..6b56951 --- /dev/null +++ b/examples/Chapter11/04-persistenceArchivePackaging/src/emp-persistence/examples/model/Project.java @@ -0,0 +1,52 @@ +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 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/Chapter11/04-persistenceArchivePackaging/src/model/examples/stateless/EmployeeService.java b/examples/Chapter11/04-persistenceArchivePackaging/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..938e90d --- /dev/null +++ b/examples/Chapter11/04-persistenceArchivePackaging/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/Chapter11/04-persistenceArchivePackaging/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter11/04-persistenceArchivePackaging/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..24219c6 --- /dev/null +++ b/examples/Chapter11/04-persistenceArchivePackaging/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,21 @@ +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 Collection findAllEmployees() { + Query query = em.createNamedQuery("Employee.findAll"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter11/04-persistenceArchivePackaging/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter11/04-persistenceArchivePackaging/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..ad4452f --- /dev/null +++ b/examples/Chapter11/04-persistenceArchivePackaging/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,95 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; + +import javax.ejb.EJB; +import javax.persistence.Query; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +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 11: Entities Packaged in a Persistence Archive"; + + private final String DESCRIPTION = + "This example demonstrates how to package entities in a peristence archive and " + + "access it from different components."; + + + @EJB EmployeeService empService; + + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + 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 { + Collection emps = null; + if (action.equals("FindAllJar")) { + emps = empService.findAllEmployees(); + } else if (action.equals("FindAllWar")) { + Query query = em.createNamedQuery("Employee.findAll"); + emps = (Collection) query.getResultList(); + } + + if (emps.isEmpty()) { + out.println("No Employees found "); + } else { + out.println("Found Employees:
"); + for (Employee emp : emps) { + out.println(emp + "
"); + out.println("    " + emp.getAddress() + "
"); + out.println("    " + emp.getDepartment() + "
"); + out.println("    Phones: " + emp.getPhones() + "
"); + out.println("
"); + } + } + } + + 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 to find all + out.println("

Find all

"); + 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/Chapter11/04-persistenceArchivePackaging/undeploy.bat b/examples/Chapter11/04-persistenceArchivePackaging/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter11/04-persistenceArchivePackaging/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter12/01-testingEntities/build.xml b/examples/Chapter12/01-testingEntities/build.xml new file mode 100644 index 0000000..2925d4e --- /dev/null +++ b/examples/Chapter12/01-testingEntities/build.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Chapter12/01-testingEntities/run.bat b/examples/Chapter12/01-testingEntities/run.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter12/01-testingEntities/run.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter12/01-testingEntities/src/model/examples/model/Department.java b/examples/Chapter12/01-testingEntities/src/model/examples/model/Department.java new file mode 100644 index 0000000..e815329 --- /dev/null +++ b/examples/Chapter12/01-testingEntities/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 String id; + private String name; + @OneToMany(mappedBy = "department") + private Collection employees; + + + public Department() { + employees = new ArrayList(); + } + + public String getId() { + return id; + } + + public void setId(String id) { + if (id.length() != 4) { + throw new IllegalArgumentException("Department identifiers must be four characters in length"); + } + this.id = id.toUpperCase(); + } + + public String getName() { + return name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + ", name: " + getName(); + } +} diff --git a/examples/Chapter12/01-testingEntities/src/model/examples/model/Employee.java b/examples/Chapter12/01-testingEntities/src/model/examples/model/Employee.java new file mode 100644 index 0000000..9986768 --- /dev/null +++ b/examples/Chapter12/01-testingEntities/src/model/examples/model/Employee.java @@ -0,0 +1,52 @@ +package examples.model; + +import java.text.DateFormat; +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 String getName() { + return name; + } + + public long getSalary() { + return salary; + } + + public Date getStartDate() { + return startDate; + } + + public Department getDepartment() { + return department; + } + + 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/Chapter12/01-testingEntities/src/test/examples/stateless/DepartmentTest.java b/examples/Chapter12/01-testingEntities/src/test/examples/stateless/DepartmentTest.java new file mode 100644 index 0000000..4c7a766 --- /dev/null +++ b/examples/Chapter12/01-testingEntities/src/test/examples/stateless/DepartmentTest.java @@ -0,0 +1,28 @@ +package examples.stateless; + +import junit.framework.TestCase; +import examples.model.Department; + +public class DepartmentTest extends TestCase { + + public void testValidDepartmentId() throws Exception { + Department dept = new Department(); + dept.setId("NA65"); + assertEquals("NA65", dept.getId()); + } + + public void testDepartmentIdInvalidLength() throws Exception { + Department dept = new Department(); + try { + dept.setId("NA6"); + fail("Department identifiers must be four characters"); + } catch (IllegalArgumentException e) { + } + } + + public void testDepartmentIdCase() throws Exception { + Department dept = new Department(); + dept.setId("na65"); + assertEquals("NA65", dept.getId()); + } +} diff --git a/examples/Chapter12/02-testingEntitiesInComponents/build.xml b/examples/Chapter12/02-testingEntitiesInComponents/build.xml new file mode 100644 index 0000000..a476874 --- /dev/null +++ b/examples/Chapter12/02-testingEntitiesInComponents/build.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Chapter12/02-testingEntitiesInComponents/run.bat b/examples/Chapter12/02-testingEntitiesInComponents/run.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter12/02-testingEntitiesInComponents/run.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter12/02-testingEntitiesInComponents/src/model/examples/model/Department.java b/examples/Chapter12/02-testingEntitiesInComponents/src/model/examples/model/Department.java new file mode 100644 index 0000000..e815329 --- /dev/null +++ b/examples/Chapter12/02-testingEntitiesInComponents/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 String id; + private String name; + @OneToMany(mappedBy = "department") + private Collection employees; + + + public Department() { + employees = new ArrayList(); + } + + public String getId() { + return id; + } + + public void setId(String id) { + if (id.length() != 4) { + throw new IllegalArgumentException("Department identifiers must be four characters in length"); + } + this.id = id.toUpperCase(); + } + + public String getName() { + return name; + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Department no: " + getId() + ", name: " + getName(); + } +} diff --git a/examples/Chapter12/02-testingEntitiesInComponents/src/model/examples/model/Employee.java b/examples/Chapter12/02-testingEntitiesInComponents/src/model/examples/model/Employee.java new file mode 100644 index 0000000..e4aa905 --- /dev/null +++ b/examples/Chapter12/02-testingEntitiesInComponents/src/model/examples/model/Employee.java @@ -0,0 +1,68 @@ +package examples.model; + +import java.text.DateFormat; +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 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 Department getDepartment() { + return department; + } + + 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/Chapter12/02-testingEntitiesInComponents/src/model/examples/stateless/EmployeeService.java b/examples/Chapter12/02-testingEntitiesInComponents/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..83fa409 --- /dev/null +++ b/examples/Chapter12/02-testingEntitiesInComponents/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 createEmployee(int id, String name, long salary); + public void removeEmployee(int id); + public Employee findEmployee(int id); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter12/02-testingEntitiesInComponents/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter12/02-testingEntitiesInComponents/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..9640b1d --- /dev/null +++ b/examples/Chapter12/02-testingEntitiesInComponents/src/model/examples/stateless/EmployeeServiceBean.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.Query; + +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + EntityManager em; + + public EntityManager getEntityManager() { + return em; + } + + public Employee createEmployee(int id, String name, long salary) { + Employee emp = new Employee(); + emp.setId(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 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/Chapter12/02-testingEntitiesInComponents/src/model/examples/stateless/Vacation.java b/examples/Chapter12/02-testingEntitiesInComponents/src/model/examples/stateless/Vacation.java new file mode 100644 index 0000000..3a3a61f --- /dev/null +++ b/examples/Chapter12/02-testingEntitiesInComponents/src/model/examples/stateless/Vacation.java @@ -0,0 +1,5 @@ +package examples.stateless; + +public interface Vacation { + public int getYearsOfService(int empId); +} diff --git a/examples/Chapter12/02-testingEntitiesInComponents/src/model/examples/stateless/VacationBean.java b/examples/Chapter12/02-testingEntitiesInComponents/src/model/examples/stateless/VacationBean.java new file mode 100644 index 0000000..0d66687 --- /dev/null +++ b/examples/Chapter12/02-testingEntitiesInComponents/src/model/examples/stateless/VacationBean.java @@ -0,0 +1,21 @@ +package examples.stateless; + +import javax.ejb.EJB; +import javax.ejb.Stateless; + +import examples.model.Employee; + +@Stateless +public class VacationBean implements Vacation { + public static final long MILLIS_PER_YEAR = 1000 * 60 * 60 * 24 * 365; + @EJB + EmployeeService empService; + + public int getYearsOfService(int empId) { + Employee emp = empService.findEmployee(empId); + long current = System.currentTimeMillis(); + long start = emp.getStartDate().getTime(); + return (int)((current - start) / MILLIS_PER_YEAR); + } +} + diff --git a/examples/Chapter12/02-testingEntitiesInComponents/src/test/examples/stateless/VacationBeanTest.java b/examples/Chapter12/02-testingEntitiesInComponents/src/test/examples/stateless/VacationBeanTest.java new file mode 100644 index 0000000..c8f62bf --- /dev/null +++ b/examples/Chapter12/02-testingEntitiesInComponents/src/test/examples/stateless/VacationBeanTest.java @@ -0,0 +1,24 @@ +package examples.stateless; + +import java.sql.Time; + +import junit.framework.TestCase; +import examples.model.Employee; +import examples.stateless.EmployeeServiceBean; +import examples.stateless.VacationBean; + +public class VacationBeanTest extends TestCase { + public void testYearsOfService() throws Exception { + VacationBean bean = new VacationBean(); + bean.empService = new EmployeeServiceBean() { + public Employee findEmployee(int id) { + Employee emp = new Employee(); + emp.setStartDate(new Time(System.currentTimeMillis() - + VacationBean.MILLIS_PER_YEAR * 5)); + return emp; + } + }; + int yearsOfService = bean.getYearsOfService(0); + assertEquals(5, yearsOfService); + } +} diff --git a/examples/Chapter12/03-emTesting/build.xml b/examples/Chapter12/03-emTesting/build.xml new file mode 100644 index 0000000..4e0d333 --- /dev/null +++ b/examples/Chapter12/03-emTesting/build.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Chapter12/03-emTesting/etc/persistence/META-INF/persistence.xml b/examples/Chapter12/03-emTesting/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..b2c0a44 --- /dev/null +++ b/examples/Chapter12/03-emTesting/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,13 @@ + + + examples.model.User + + + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter12/03-emTesting/etc/sql/db.sql b/examples/Chapter12/03-emTesting/etc/sql/db.sql new file mode 100644 index 0000000..7b6fba7 --- /dev/null +++ b/examples/Chapter12/03-emTesting/etc/sql/db.sql @@ -0,0 +1,4 @@ +DROP TABLE USER_DB; + +CREATE TABLE USER_DB (NAME VARCHAR(255) NOT NULL, PASSWORD VARCHAR(255), PRIMARY KEY (NAME)); + diff --git a/examples/Chapter12/03-emTesting/run.bat b/examples/Chapter12/03-emTesting/run.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter12/03-emTesting/run.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter12/03-emTesting/src/model/examples/model/User.java b/examples/Chapter12/03-emTesting/src/model/examples/model/User.java new file mode 100644 index 0000000..2496354 --- /dev/null +++ b/examples/Chapter12/03-emTesting/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/Chapter12/03-emTesting/src/model/examples/stateless/UserService.java b/examples/Chapter12/03-emTesting/src/model/examples/stateless/UserService.java new file mode 100644 index 0000000..c458cde --- /dev/null +++ b/examples/Chapter12/03-emTesting/src/model/examples/stateless/UserService.java @@ -0,0 +1,7 @@ +package examples.stateless; + +import examples.model.User; + +public interface UserService { + public User authenticate(String userId, String password); +} diff --git a/examples/Chapter12/03-emTesting/src/model/examples/stateless/UserServiceBean.java b/examples/Chapter12/03-emTesting/src/model/examples/stateless/UserServiceBean.java new file mode 100644 index 0000000..a403693 --- /dev/null +++ b/examples/Chapter12/03-emTesting/src/model/examples/stateless/UserServiceBean.java @@ -0,0 +1,25 @@ +package examples.stateless; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.User; + +@Stateless +public class UserServiceBean implements UserService { + @PersistenceContext + EntityManager em; + + public User authenticate(String userId, String password) { + User user = findUser(userId); + // ... + return user; + } + + protected User findUser(String userId) { + return em.find(User.class, userId); + } +} + + diff --git a/examples/Chapter12/03-emTesting/src/test/examples/stateless/MockEntityManager.java b/examples/Chapter12/03-emTesting/src/test/examples/stateless/MockEntityManager.java new file mode 100644 index 0000000..1c2af0e --- /dev/null +++ b/examples/Chapter12/03-emTesting/src/test/examples/stateless/MockEntityManager.java @@ -0,0 +1,88 @@ +package examples.stateless; + +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; +import javax.persistence.FlushModeType; +import javax.persistence.LockModeType; +import javax.persistence.Query; + +public class MockEntityManager implements EntityManager { + public void persist(Object arg0) { + } + + public T merge(T arg0) { + return null; + } + + public void remove(Object arg0) { + } + + public T find(Class arg0, Object arg1) { + return null; + } + + public T getReference(Class arg0, Object arg1) { + return null; + } + + public void flush() { + } + + public void refresh(Object arg0) { + } + + public boolean contains(Object arg0) { + return false; + } + + public Query createQuery(String arg0) { + return null; + } + + public Query createNamedQuery(String arg0) { + return null; + } + + public Query createNativeQuery(String arg0) { + return null; + } + + public Query createNativeQuery(String arg0, Class arg1) { + return null; + } + + public Query createNativeQuery(String arg0, String arg1) { + return null; + } + + public void close() { + } + + public boolean isOpen() { + return false; + } + + public void lock(Object arg0, LockModeType arg1) { + } + + public void clear() { + } + + public Object getDelegate() { + return null; + } + + public EntityTransaction getTransaction() { + return null; + } + + public FlushModeType getFlushMode() { + return null; + } + + public void setFlushMode(FlushModeType arg0) { + } + + public void joinTransaction() { + } +} diff --git a/examples/Chapter12/03-emTesting/src/test/examples/stateless/UserServiceTest.java b/examples/Chapter12/03-emTesting/src/test/examples/stateless/UserServiceTest.java new file mode 100644 index 0000000..8df930b --- /dev/null +++ b/examples/Chapter12/03-emTesting/src/test/examples/stateless/UserServiceTest.java @@ -0,0 +1,42 @@ +package examples.stateless; + +import junit.framework.TestCase; +import examples.model.User; +import examples.stateless.UserServiceBean; + +public class UserServiceTest extends TestCase { + private static final String USER_ID = "test_id"; + private static final String PASSWORD = "test_password"; + private static final String INVALID_USER_ID = "test_user"; + + public void testAuthenticateValidUser() throws Exception { + TestUserService service = new TestUserService(); + User user = service.authenticate(USER_ID, PASSWORD); + assertNotNull(user); + assertEquals(USER_ID, user.getName()); + assertEquals(PASSWORD, user.getPassword()); + } + + public void testAuthenticateInvalidUser() throws Exception { + TestUserService service = new TestUserService(); + User user = service.authenticate(INVALID_USER_ID, PASSWORD); + assertNull(user); + } + + class TestUserService extends UserServiceBean { + private User user; + + public TestUserService() { + user = new User(); + user.setName(USER_ID); + user.setPassword(PASSWORD); + } + + protected User findUser(String userId) { + if (userId.equals(user.getName())) { + return user; + } + return null; + } + } +} diff --git a/examples/Chapter12/03-emTesting/src/test/examples/stateless/UserServiceTest2.java b/examples/Chapter12/03-emTesting/src/test/examples/stateless/UserServiceTest2.java new file mode 100644 index 0000000..faa5b25 --- /dev/null +++ b/examples/Chapter12/03-emTesting/src/test/examples/stateless/UserServiceTest2.java @@ -0,0 +1,45 @@ +package examples.stateless; + +import junit.framework.TestCase; +import examples.model.User; +import examples.stateless.UserServiceBean; + +public class UserServiceTest2 extends TestCase { + private static final String USER_ID = "test_id"; + private static final String PASSWORD = "test_password"; + private static final String INVALID_USER_ID = "test_user"; + + public void testAuthenticateValidUser() throws Exception { + UserServiceBean service = new UserServiceBean(); + service.em = new TestEntityManager(USER_ID, PASSWORD); + User user = service.authenticate(USER_ID, PASSWORD); + assertNotNull(user); + assertEquals(USER_ID, user.getName()); + assertEquals(PASSWORD, user.getPassword()); + } + + public void testAuthenticateInvalidUser() throws Exception { + UserServiceBean service = new UserServiceBean(); + service.em = new TestEntityManager(USER_ID, PASSWORD); + User user = service.authenticate(INVALID_USER_ID, PASSWORD); + assertNull(user); + } + + class TestEntityManager extends MockEntityManager { + private User user; + + public TestEntityManager(String user, String password) { + this.user = new User(); + this.user.setName(user); + this.user.setPassword(password); + } + + public T find(Class entityClass, Object pk) { + if (entityClass == User.class && ((String)pk).equals(user.getName())) { + return (T) user; + } + return null; + } + } +} + diff --git a/examples/Chapter12/03-emTesting/src/test/examples/stateless/UserServiceTest3.java b/examples/Chapter12/03-emTesting/src/test/examples/stateless/UserServiceTest3.java new file mode 100644 index 0000000..6c57495 --- /dev/null +++ b/examples/Chapter12/03-emTesting/src/test/examples/stateless/UserServiceTest3.java @@ -0,0 +1,68 @@ +package examples.stateless; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import junit.framework.TestCase; +import examples.model.User; +import examples.stateless.UserServiceBean; + +public class UserServiceTest3 extends TestCase { + private static final String USER_ID = "test_id"; + private static final String PASSWORD = "test_password"; + private static final String INVALID_USER_ID = "test_user"; + + private EntityManager em; + private EntityManagerFactory emf; + + public void setUp() { + emf = Persistence.createEntityManagerFactory("hr"); + em = emf.createEntityManager(); + createTestData(); + } + + public void tearDown() { + if (em != null) { + removeTestData(); + em.close(); + } + if (emf != null) { + emf.close(); + } + } + + private void createTestData() { + User user = new User(); + user.setName(USER_ID); + user.setPassword(PASSWORD); + em.getTransaction().begin(); + em.persist(user); + em.getTransaction().commit(); + } + + private void removeTestData() { + em.getTransaction().begin(); + User user = em.find(User.class, USER_ID); + if (user != null) { + em.remove(user); + } + em.getTransaction().commit(); + } + + public void testAuthenticateValidUser() throws Exception { + UserServiceBean service = new UserServiceBean(); + service.em = em; + User user = service.authenticate(USER_ID, PASSWORD); + assertNotNull(user); + assertEquals(USER_ID, user.getName()); + assertEquals(PASSWORD, user.getPassword()); + } + + public void testAuthenticateInvalidUser() throws Exception { + UserServiceBean service = new UserServiceBean(); + service.em = em; + User user = service.authenticate(INVALID_USER_ID, PASSWORD); + assertNull(user); + } +} \ No newline at end of file diff --git a/examples/Chapter12/04-xmlOverrides/build.xml b/examples/Chapter12/04-xmlOverrides/build.xml new file mode 100644 index 0000000..ce71cae --- /dev/null +++ b/examples/Chapter12/04-xmlOverrides/build.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Chapter12/04-xmlOverrides/etc/persistence/META-INF/derby-overrides.xml b/examples/Chapter12/04-xmlOverrides/etc/persistence/META-INF/derby-overrides.xml new file mode 100644 index 0000000..f7dd0ed --- /dev/null +++ b/examples/Chapter12/04-xmlOverrides/etc/persistence/META-INF/derby-overrides.xml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/examples/Chapter12/04-xmlOverrides/etc/persistence/META-INF/persistence.xml b/examples/Chapter12/04-xmlOverrides/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..bdf71a9 --- /dev/null +++ b/examples/Chapter12/04-xmlOverrides/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,14 @@ + + + META-INF/derby-overrides.xml + examples.model.Phone + + + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter12/04-xmlOverrides/etc/sql/db.sql b/examples/Chapter12/04-xmlOverrides/etc/sql/db.sql new file mode 100644 index 0000000..37698ed --- /dev/null +++ b/examples/Chapter12/04-xmlOverrides/etc/sql/db.sql @@ -0,0 +1,7 @@ +DROP TABLE PHONE; +DROP TABLE ID_GEN; + +CREATE TABLE PHONE (ID INTEGER NOT NULL, NUMBER VARCHAR(255), TYPE VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE ID_GEN (SEQ_NAME VARCHAR(80), SEQ_COUNT INTEGER, PRIMARY KEY (SEQ_NAME)); + +INSERT INTO ID_GEN (SEQ_NAME, SEQ_COUNT) VALUES ('PhoneId', 0); diff --git a/examples/Chapter12/04-xmlOverrides/run.bat b/examples/Chapter12/04-xmlOverrides/run.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter12/04-xmlOverrides/run.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter12/04-xmlOverrides/src/model/examples/model/Phone.java b/examples/Chapter12/04-xmlOverrides/src/model/examples/model/Phone.java new file mode 100644 index 0000000..d9ac844 --- /dev/null +++ b/examples/Chapter12/04-xmlOverrides/src/model/examples/model/Phone.java @@ -0,0 +1,47 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.SequenceGenerator; + +@Entity +public class Phone { + @SequenceGenerator(name="Phone_Gen", sequenceName="PHONE_SEQ") + @Id @GeneratedValue(strategy=GenerationType.SEQUENCE, + generator="Phone_Gen") + private int id; + 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/Chapter12/04-xmlOverrides/src/model/examples/stateless/PhoneService.java b/examples/Chapter12/04-xmlOverrides/src/model/examples/stateless/PhoneService.java new file mode 100644 index 0000000..9ad6dfa --- /dev/null +++ b/examples/Chapter12/04-xmlOverrides/src/model/examples/stateless/PhoneService.java @@ -0,0 +1,7 @@ +package examples.stateless; + +import examples.model.Phone; + +public interface PhoneService { + public Phone createPhone(Phone phone); +} diff --git a/examples/Chapter12/04-xmlOverrides/src/model/examples/stateless/PhoneServiceBean.java b/examples/Chapter12/04-xmlOverrides/src/model/examples/stateless/PhoneServiceBean.java new file mode 100644 index 0000000..8293d36 --- /dev/null +++ b/examples/Chapter12/04-xmlOverrides/src/model/examples/stateless/PhoneServiceBean.java @@ -0,0 +1,24 @@ +package examples.stateless; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Phone; + +@Stateless +public class PhoneServiceBean implements PhoneService { + @PersistenceContext + EntityManager em; + + public Phone createPhone(Phone phone) { + em.persist(phone); + return phone; + } + + protected Phone findUser(int id) { + return em.find(Phone.class, id); + } +} + + diff --git a/examples/Chapter12/04-xmlOverrides/src/test/examples/stateless/PhoneServiceTest.java b/examples/Chapter12/04-xmlOverrides/src/test/examples/stateless/PhoneServiceTest.java new file mode 100644 index 0000000..a568bde --- /dev/null +++ b/examples/Chapter12/04-xmlOverrides/src/test/examples/stateless/PhoneServiceTest.java @@ -0,0 +1,45 @@ +package examples.stateless; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import junit.framework.TestCase; +import examples.model.Phone; +import examples.stateless.PhoneServiceBean; + +public class PhoneServiceTest extends TestCase { + + private EntityManager em; + private EntityManagerFactory emf; + + public void setUp() { + emf = Persistence.createEntityManagerFactory("hr"); + em = emf.createEntityManager(); + } + + public void tearDown() { + if (em != null) { + em.close(); + } + if (emf != null) { + emf.close(); + } + } + + public void testCreatePhone() throws Exception { + PhoneServiceBean bean = new PhoneServiceBean(); + bean.em = em; + Phone phone = new Phone(); + phone.setNumber("555-1234"); + phone.setType("Home"); + em.getTransaction().begin(); + bean.createPhone(phone); + em.getTransaction().commit(); + phone = em.find(Phone.class, 1); + assertNotNull(phone); + assertEquals("555-1234", phone.getNumber()); + assertEquals("Home", phone.getType()); + } + +} \ No newline at end of file diff --git a/examples/Chapter12/05-minimizingDBConnections/build.xml b/examples/Chapter12/05-minimizingDBConnections/build.xml new file mode 100644 index 0000000..3c2d88f --- /dev/null +++ b/examples/Chapter12/05-minimizingDBConnections/build.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Chapter12/05-minimizingDBConnections/etc/persistence/META-INF/persistence.xml b/examples/Chapter12/05-minimizingDBConnections/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..f2a96d3 --- /dev/null +++ b/examples/Chapter12/05-minimizingDBConnections/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,13 @@ + + + examples.model.User + + + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter12/05-minimizingDBConnections/etc/sql/db.sql b/examples/Chapter12/05-minimizingDBConnections/etc/sql/db.sql new file mode 100644 index 0000000..7b6fba7 --- /dev/null +++ b/examples/Chapter12/05-minimizingDBConnections/etc/sql/db.sql @@ -0,0 +1,4 @@ +DROP TABLE USER_DB; + +CREATE TABLE USER_DB (NAME VARCHAR(255) NOT NULL, PASSWORD VARCHAR(255), PRIMARY KEY (NAME)); + diff --git a/examples/Chapter12/05-minimizingDBConnections/run.bat b/examples/Chapter12/05-minimizingDBConnections/run.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter12/05-minimizingDBConnections/run.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter12/05-minimizingDBConnections/src/model/examples/model/User.java b/examples/Chapter12/05-minimizingDBConnections/src/model/examples/model/User.java new file mode 100644 index 0000000..2496354 --- /dev/null +++ b/examples/Chapter12/05-minimizingDBConnections/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/Chapter12/05-minimizingDBConnections/src/model/examples/stateless/UserService.java b/examples/Chapter12/05-minimizingDBConnections/src/model/examples/stateless/UserService.java new file mode 100644 index 0000000..c458cde --- /dev/null +++ b/examples/Chapter12/05-minimizingDBConnections/src/model/examples/stateless/UserService.java @@ -0,0 +1,7 @@ +package examples.stateless; + +import examples.model.User; + +public interface UserService { + public User authenticate(String userId, String password); +} diff --git a/examples/Chapter12/05-minimizingDBConnections/src/model/examples/stateless/UserServiceBean.java b/examples/Chapter12/05-minimizingDBConnections/src/model/examples/stateless/UserServiceBean.java new file mode 100644 index 0000000..a403693 --- /dev/null +++ b/examples/Chapter12/05-minimizingDBConnections/src/model/examples/stateless/UserServiceBean.java @@ -0,0 +1,25 @@ +package examples.stateless; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.User; + +@Stateless +public class UserServiceBean implements UserService { + @PersistenceContext + EntityManager em; + + public User authenticate(String userId, String password) { + User user = findUser(userId); + // ... + return user; + } + + protected User findUser(String userId) { + return em.find(User.class, userId); + } +} + + diff --git a/examples/Chapter12/05-minimizingDBConnections/src/test/examples/stateless/DatabaseTest.java b/examples/Chapter12/05-minimizingDBConnections/src/test/examples/stateless/DatabaseTest.java new file mode 100644 index 0000000..82aa850 --- /dev/null +++ b/examples/Chapter12/05-minimizingDBConnections/src/test/examples/stateless/DatabaseTest.java @@ -0,0 +1,38 @@ +package examples.stateless; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import junit.extensions.TestSetup; +import junit.framework.Test; +import junit.framework.TestSuite; + +public class DatabaseTest { + public static EntityManagerFactory emf; + public static EntityManager em; + + public static Test suite() { + TestSuite suite = new TestSuite(); + suite.addTestSuite(UserServiceTest3.class); + + TestSetup wrapper = new TestSetup(suite) { + + protected void setUp() throws Exception { + emf = Persistence.createEntityManagerFactory("hr"); + em = emf.createEntityManager(); + } + + protected void tearDown() throws Exception { + if (em != null) { + em.close(); + } + if (emf != null) { + emf.close(); + } + } + }; + + return wrapper; + } +} diff --git a/examples/Chapter12/05-minimizingDBConnections/src/test/examples/stateless/MockEntityManager.java b/examples/Chapter12/05-minimizingDBConnections/src/test/examples/stateless/MockEntityManager.java new file mode 100644 index 0000000..1c2af0e --- /dev/null +++ b/examples/Chapter12/05-minimizingDBConnections/src/test/examples/stateless/MockEntityManager.java @@ -0,0 +1,88 @@ +package examples.stateless; + +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; +import javax.persistence.FlushModeType; +import javax.persistence.LockModeType; +import javax.persistence.Query; + +public class MockEntityManager implements EntityManager { + public void persist(Object arg0) { + } + + public T merge(T arg0) { + return null; + } + + public void remove(Object arg0) { + } + + public T find(Class arg0, Object arg1) { + return null; + } + + public T getReference(Class arg0, Object arg1) { + return null; + } + + public void flush() { + } + + public void refresh(Object arg0) { + } + + public boolean contains(Object arg0) { + return false; + } + + public Query createQuery(String arg0) { + return null; + } + + public Query createNamedQuery(String arg0) { + return null; + } + + public Query createNativeQuery(String arg0) { + return null; + } + + public Query createNativeQuery(String arg0, Class arg1) { + return null; + } + + public Query createNativeQuery(String arg0, String arg1) { + return null; + } + + public void close() { + } + + public boolean isOpen() { + return false; + } + + public void lock(Object arg0, LockModeType arg1) { + } + + public void clear() { + } + + public Object getDelegate() { + return null; + } + + public EntityTransaction getTransaction() { + return null; + } + + public FlushModeType getFlushMode() { + return null; + } + + public void setFlushMode(FlushModeType arg0) { + } + + public void joinTransaction() { + } +} diff --git a/examples/Chapter12/05-minimizingDBConnections/src/test/examples/stateless/UserServiceTest3.java b/examples/Chapter12/05-minimizingDBConnections/src/test/examples/stateless/UserServiceTest3.java new file mode 100644 index 0000000..db8d0de --- /dev/null +++ b/examples/Chapter12/05-minimizingDBConnections/src/test/examples/stateless/UserServiceTest3.java @@ -0,0 +1,54 @@ +package examples.stateless; + +import junit.framework.TestCase; +import examples.model.User; +import examples.stateless.UserServiceBean; + +public class UserServiceTest3 extends TestCase { + private static final String USER_ID = "test_id"; + private static final String PASSWORD = "test_password"; + private static final String INVALID_USER_ID = "test_user"; + + public void setUp() { + createTestData(); + } + public void tearDown() { + if (DatabaseTest.em != null) { + removeTestData(); + } + } + + private void createTestData() { + User user = new User(); + user.setName(USER_ID); + user.setPassword(PASSWORD); + DatabaseTest.em.getTransaction().begin(); + DatabaseTest.em.persist(user); + DatabaseTest.em.getTransaction().commit(); + } + + private void removeTestData() { + DatabaseTest.em.getTransaction().begin(); + User user = DatabaseTest.em.find(User.class, USER_ID); + if (user != null) { + DatabaseTest.em.remove(user); + } + DatabaseTest.em.getTransaction().commit(); + } + + public void testAuthenticateValidUser() throws Exception { + UserServiceBean service = new UserServiceBean(); + service.em = DatabaseTest.em; + User user = service.authenticate(USER_ID, PASSWORD); + assertNotNull(user); + assertEquals(USER_ID, user.getName()); + assertEquals(PASSWORD, user.getPassword()); + } + + public void testAuthenticateInvalidUser() throws Exception { + UserServiceBean service = new UserServiceBean(); + service.em = DatabaseTest.em; + User user = service.authenticate(INVALID_USER_ID, PASSWORD); + assertNull(user); + } +} \ No newline at end of file diff --git a/examples/Chapter12/06-containerManagedTxTesting/build.xml b/examples/Chapter12/06-containerManagedTxTesting/build.xml new file mode 100644 index 0000000..2fd9f64 --- /dev/null +++ b/examples/Chapter12/06-containerManagedTxTesting/build.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Chapter12/06-containerManagedTxTesting/etc/persistence/META-INF/persistence.xml b/examples/Chapter12/06-containerManagedTxTesting/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..d523e55 --- /dev/null +++ b/examples/Chapter12/06-containerManagedTxTesting/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,14 @@ + + + examples.model.Employee + examples.model.Department + + + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter12/06-containerManagedTxTesting/etc/sql/db.sql b/examples/Chapter12/06-containerManagedTxTesting/etc/sql/db.sql new file mode 100644 index 0000000..fccf9ee --- /dev/null +++ b/examples/Chapter12/06-containerManagedTxTesting/etc/sql/db.sql @@ -0,0 +1,7 @@ +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)); \ No newline at end of file diff --git a/examples/Chapter12/06-containerManagedTxTesting/run.bat b/examples/Chapter12/06-containerManagedTxTesting/run.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter12/06-containerManagedTxTesting/run.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter12/06-containerManagedTxTesting/src/model/examples/model/Department.java b/examples/Chapter12/06-containerManagedTxTesting/src/model/examples/model/Department.java new file mode 100644 index 0000000..a2a8ff4 --- /dev/null +++ b/examples/Chapter12/06-containerManagedTxTesting/src/model/examples/model/Department.java @@ -0,0 +1,52 @@ +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 Department(int id, String name) { + setId(id); + setName(name); + 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/Chapter12/06-containerManagedTxTesting/src/model/examples/model/Employee.java b/examples/Chapter12/06-containerManagedTxTesting/src/model/examples/model/Employee.java new file mode 100644 index 0000000..8281321 --- /dev/null +++ b/examples/Chapter12/06-containerManagedTxTesting/src/model/examples/model/Employee.java @@ -0,0 +1,82 @@ +package examples.model; + +import java.text.DateFormat; +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 Employee() {} + public Employee(int id, String name) { + setId(id); + setName(name); + } + + 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 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 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/Chapter12/06-containerManagedTxTesting/src/model/examples/stateless/DepartmentService.java b/examples/Chapter12/06-containerManagedTxTesting/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..aa4251c --- /dev/null +++ b/examples/Chapter12/06-containerManagedTxTesting/src/model/examples/stateless/DepartmentService.java @@ -0,0 +1,7 @@ +package examples.stateless; + +import java.util.List; + +public interface DepartmentService { + public List assignEmployeeToDepartment(int deptId, int empId); +} diff --git a/examples/Chapter12/06-containerManagedTxTesting/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter12/06-containerManagedTxTesting/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..5c3cc3a --- /dev/null +++ b/examples/Chapter12/06-containerManagedTxTesting/src/model/examples/stateless/DepartmentServiceBean.java @@ -0,0 +1,31 @@ +package examples.stateless; + +import java.util.List; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +public class DepartmentServiceBean implements DepartmentService { + private static final String QUERY = + "SELECT e " + + "FROM Employee e " + + "WHERE e.department = ?1 ORDER BY e.name"; + + @PersistenceContext(unitName="hr") + EntityManager em; + + public List assignEmployeeToDepartment(int deptId, int empId) { + Department dept = em.find(Department.class, deptId); + Employee emp = em.find(Employee.class, empId); + dept.getEmployees().add(emp); + emp.setDepartment(dept); + return em.createQuery(QUERY) + .setParameter(1, dept) + .getResultList(); + } +} diff --git a/examples/Chapter12/06-containerManagedTxTesting/src/test/examples/stateless/DepartmentServiceBeanTest.java b/examples/Chapter12/06-containerManagedTxTesting/src/test/examples/stateless/DepartmentServiceBeanTest.java new file mode 100644 index 0000000..e668aca --- /dev/null +++ b/examples/Chapter12/06-containerManagedTxTesting/src/test/examples/stateless/DepartmentServiceBeanTest.java @@ -0,0 +1,46 @@ +package examples.stateless; + +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import junit.framework.TestCase; +import examples.model.Department; +import examples.model.Employee; +import examples.stateless.DepartmentServiceBean; + +public class DepartmentServiceBeanTest extends TestCase { + + private EntityManager em; + private EntityManagerFactory emf; + + public void setUp() { + emf = Persistence.createEntityManagerFactory("hr"); + em = emf.createEntityManager(); + createTestData(); + } + + private void createTestData() { + Employee emp = new Employee(500, "Scott"); + em.persist(emp); + emp = new Employee(600, "John"); + em.persist(emp); + Department dept = new Department(700, "TEST"); + dept.getEmployees().add(emp); + emp.setDepartment(dept); + em.persist(dept); + } + + public void testAssignEmployeeToDepartment() throws Exception { + DepartmentServiceBean bean = new DepartmentServiceBean(); + bean.em = em; + em.getTransaction().begin(); + List result = bean.assignEmployeeToDepartment(700, 500); + em.getTransaction().rollback(); + assertEquals(2, result.size()); + assertEquals("John", ((Employee)result.get(0)).getName()); + assertEquals("Scott", ((Employee)result.get(1)).getName()); + } +} \ No newline at end of file diff --git a/examples/Chapter12/07-beanManagedTxTesting/build.xml b/examples/Chapter12/07-beanManagedTxTesting/build.xml new file mode 100644 index 0000000..63bd6fc --- /dev/null +++ b/examples/Chapter12/07-beanManagedTxTesting/build.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Chapter12/07-beanManagedTxTesting/etc/persistence/META-INF/persistence.xml b/examples/Chapter12/07-beanManagedTxTesting/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..63bc1e2 --- /dev/null +++ b/examples/Chapter12/07-beanManagedTxTesting/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,14 @@ + + + examples.model.Employee + examples.model.Department + + + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter12/07-beanManagedTxTesting/etc/sql/db.sql b/examples/Chapter12/07-beanManagedTxTesting/etc/sql/db.sql new file mode 100644 index 0000000..fccf9ee --- /dev/null +++ b/examples/Chapter12/07-beanManagedTxTesting/etc/sql/db.sql @@ -0,0 +1,7 @@ +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)); \ No newline at end of file diff --git a/examples/Chapter12/07-beanManagedTxTesting/run.bat b/examples/Chapter12/07-beanManagedTxTesting/run.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter12/07-beanManagedTxTesting/run.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter12/07-beanManagedTxTesting/src/model/examples/model/Department.java b/examples/Chapter12/07-beanManagedTxTesting/src/model/examples/model/Department.java new file mode 100644 index 0000000..a2a8ff4 --- /dev/null +++ b/examples/Chapter12/07-beanManagedTxTesting/src/model/examples/model/Department.java @@ -0,0 +1,52 @@ +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 Department(int id, String name) { + setId(id); + setName(name); + 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/Chapter12/07-beanManagedTxTesting/src/model/examples/model/Employee.java b/examples/Chapter12/07-beanManagedTxTesting/src/model/examples/model/Employee.java new file mode 100644 index 0000000..8281321 --- /dev/null +++ b/examples/Chapter12/07-beanManagedTxTesting/src/model/examples/model/Employee.java @@ -0,0 +1,82 @@ +package examples.model; + +import java.text.DateFormat; +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 Employee() {} + public Employee(int id, String name) { + setId(id); + setName(name); + } + + 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 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 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/Chapter12/07-beanManagedTxTesting/src/model/examples/stateless/DepartmentService.java b/examples/Chapter12/07-beanManagedTxTesting/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..aa4251c --- /dev/null +++ b/examples/Chapter12/07-beanManagedTxTesting/src/model/examples/stateless/DepartmentService.java @@ -0,0 +1,7 @@ +package examples.stateless; + +import java.util.List; + +public interface DepartmentService { + public List assignEmployeeToDepartment(int deptId, int empId); +} diff --git a/examples/Chapter12/07-beanManagedTxTesting/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter12/07-beanManagedTxTesting/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..6c97e47 --- /dev/null +++ b/examples/Chapter12/07-beanManagedTxTesting/src/model/examples/stateless/DepartmentServiceBean.java @@ -0,0 +1,47 @@ +package examples.stateless; + +import java.util.List; + +import javax.annotation.Resource; +import javax.ejb.EJBException; +import javax.ejb.Stateless; +import javax.ejb.TransactionManagement; +import javax.ejb.TransactionManagementType; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.transaction.UserTransaction; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +@TransactionManagement(TransactionManagementType.BEAN) +public class DepartmentServiceBean implements DepartmentService { + private static final String QUERY = + "SELECT e " + + "FROM Employee e " + + "WHERE e.department = ?1 ORDER BY e.name"; + + @PersistenceContext(unitName="hr") + EntityManager em; + + @Resource + UserTransaction tx; + + public List assignEmployeeToDepartment(int deptId, int empId) { + try { + tx.begin(); + Department dept = em.find(Department.class, deptId); + Employee emp = em.find(Employee.class, empId); + dept.getEmployees().add(emp); + emp.setDepartment(dept); + tx.commit(); + return em.createQuery(QUERY) + .setParameter(1, dept) + .getResultList(); + } catch (Exception e) { + // handle transaction exceptions + throw new EJBException(e); + } + } +} diff --git a/examples/Chapter12/07-beanManagedTxTesting/src/test/examples/stateless/DepartmentServiceBeanTest.java b/examples/Chapter12/07-beanManagedTxTesting/src/test/examples/stateless/DepartmentServiceBeanTest.java new file mode 100644 index 0000000..a29eb23 --- /dev/null +++ b/examples/Chapter12/07-beanManagedTxTesting/src/test/examples/stateless/DepartmentServiceBeanTest.java @@ -0,0 +1,45 @@ +package examples.stateless; + +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import junit.framework.TestCase; +import examples.model.Department; +import examples.model.Employee; +import examples.stateless.DepartmentServiceBean; + +public class DepartmentServiceBeanTest extends TestCase { + + private EntityManager em; + private EntityManagerFactory emf; + + public void setUp() { + emf = Persistence.createEntityManagerFactory("hr"); + em = emf.createEntityManager(); + createTestData(); + } + + private void createTestData() { + Employee emp = new Employee(500, "Scott"); + em.persist(emp); + emp = new Employee(600, "John"); + em.persist(emp); + Department dept = new Department(700, "TEST"); + dept.getEmployees().add(emp); + emp.setDepartment(dept); + em.persist(dept); + } + + public void testAssignEmployeeToDepartment() throws Exception { + DepartmentServiceBean bean = new DepartmentServiceBean(); + bean.em = em; + bean.tx = new EntityUserTransaction(em); + List result = bean.assignEmployeeToDepartment(700, 500); + assertEquals(2, result.size()); + assertEquals("John", ((Employee)result.get(0)).getName()); + assertEquals("Scott", ((Employee)result.get(1)).getName()); + } +} \ No newline at end of file diff --git a/examples/Chapter12/07-beanManagedTxTesting/src/test/examples/stateless/EntityUserTransaction.java b/examples/Chapter12/07-beanManagedTxTesting/src/test/examples/stateless/EntityUserTransaction.java new file mode 100644 index 0000000..d89ba94 --- /dev/null +++ b/examples/Chapter12/07-beanManagedTxTesting/src/test/examples/stateless/EntityUserTransaction.java @@ -0,0 +1,57 @@ +package examples.stateless; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceException; +import javax.transaction.NotSupportedException; +import javax.transaction.RollbackException; +import javax.transaction.Status; +import javax.transaction.SystemException; +import javax.transaction.UserTransaction; + +public class EntityUserTransaction implements UserTransaction { + private EntityManager em; + + public EntityUserTransaction(EntityManager em) { + this.em = em; + } + + public void begin() throws NotSupportedException { + if (em.getTransaction().isActive()) { + throw new NotSupportedException(); + } + em.getTransaction().begin(); + } + + public void commit() throws RollbackException { + try { + em.getTransaction().commit(); + } catch (javax.persistence.RollbackException e) { + throw new RollbackException(e.getMessage()); + } + } + + public void rollback() throws SystemException { + try { + em.getTransaction().rollback(); + } catch (PersistenceException e) { + throw new SystemException(e.getMessage()); + } + } + + public void setRollbackOnly() { + em.getTransaction().setRollbackOnly(); + } + + public int getStatus() { + if (em.getTransaction().isActive()) { + return Status.STATUS_ACTIVE; + } else { + return Status.STATUS_NO_TRANSACTION; + } + } + + public void setTransactionTimeout(int timeout) { + throw new UnsupportedOperationException(); + } +} + diff --git a/examples/Chapter12/08-nullUserTxTesting/build.xml b/examples/Chapter12/08-nullUserTxTesting/build.xml new file mode 100644 index 0000000..d058c82 --- /dev/null +++ b/examples/Chapter12/08-nullUserTxTesting/build.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Chapter12/08-nullUserTxTesting/etc/persistence/META-INF/persistence.xml b/examples/Chapter12/08-nullUserTxTesting/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..d6c2634 --- /dev/null +++ b/examples/Chapter12/08-nullUserTxTesting/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,14 @@ + + + examples.model.Employee + examples.model.Department + + + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter12/08-nullUserTxTesting/etc/sql/db.sql b/examples/Chapter12/08-nullUserTxTesting/etc/sql/db.sql new file mode 100644 index 0000000..fccf9ee --- /dev/null +++ b/examples/Chapter12/08-nullUserTxTesting/etc/sql/db.sql @@ -0,0 +1,7 @@ +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)); \ No newline at end of file diff --git a/examples/Chapter12/08-nullUserTxTesting/run.bat b/examples/Chapter12/08-nullUserTxTesting/run.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter12/08-nullUserTxTesting/run.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter12/08-nullUserTxTesting/src/model/examples/model/Department.java b/examples/Chapter12/08-nullUserTxTesting/src/model/examples/model/Department.java new file mode 100644 index 0000000..a2a8ff4 --- /dev/null +++ b/examples/Chapter12/08-nullUserTxTesting/src/model/examples/model/Department.java @@ -0,0 +1,52 @@ +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 Department(int id, String name) { + setId(id); + setName(name); + 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/Chapter12/08-nullUserTxTesting/src/model/examples/model/Employee.java b/examples/Chapter12/08-nullUserTxTesting/src/model/examples/model/Employee.java new file mode 100644 index 0000000..8281321 --- /dev/null +++ b/examples/Chapter12/08-nullUserTxTesting/src/model/examples/model/Employee.java @@ -0,0 +1,82 @@ +package examples.model; + +import java.text.DateFormat; +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 Employee() {} + public Employee(int id, String name) { + setId(id); + setName(name); + } + + 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 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 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/Chapter12/08-nullUserTxTesting/src/model/examples/stateless/DepartmentService.java b/examples/Chapter12/08-nullUserTxTesting/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..aa4251c --- /dev/null +++ b/examples/Chapter12/08-nullUserTxTesting/src/model/examples/stateless/DepartmentService.java @@ -0,0 +1,7 @@ +package examples.stateless; + +import java.util.List; + +public interface DepartmentService { + public List assignEmployeeToDepartment(int deptId, int empId); +} diff --git a/examples/Chapter12/08-nullUserTxTesting/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter12/08-nullUserTxTesting/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..6c97e47 --- /dev/null +++ b/examples/Chapter12/08-nullUserTxTesting/src/model/examples/stateless/DepartmentServiceBean.java @@ -0,0 +1,47 @@ +package examples.stateless; + +import java.util.List; + +import javax.annotation.Resource; +import javax.ejb.EJBException; +import javax.ejb.Stateless; +import javax.ejb.TransactionManagement; +import javax.ejb.TransactionManagementType; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.transaction.UserTransaction; + +import examples.model.Department; +import examples.model.Employee; + +@Stateless +@TransactionManagement(TransactionManagementType.BEAN) +public class DepartmentServiceBean implements DepartmentService { + private static final String QUERY = + "SELECT e " + + "FROM Employee e " + + "WHERE e.department = ?1 ORDER BY e.name"; + + @PersistenceContext(unitName="hr") + EntityManager em; + + @Resource + UserTransaction tx; + + public List assignEmployeeToDepartment(int deptId, int empId) { + try { + tx.begin(); + Department dept = em.find(Department.class, deptId); + Employee emp = em.find(Employee.class, empId); + dept.getEmployees().add(emp); + emp.setDepartment(dept); + tx.commit(); + return em.createQuery(QUERY) + .setParameter(1, dept) + .getResultList(); + } catch (Exception e) { + // handle transaction exceptions + throw new EJBException(e); + } + } +} diff --git a/examples/Chapter12/08-nullUserTxTesting/src/test/examples/stateless/DepartmentServiceBeanTest.java b/examples/Chapter12/08-nullUserTxTesting/src/test/examples/stateless/DepartmentServiceBeanTest.java new file mode 100644 index 0000000..1524981 --- /dev/null +++ b/examples/Chapter12/08-nullUserTxTesting/src/test/examples/stateless/DepartmentServiceBeanTest.java @@ -0,0 +1,47 @@ +package examples.stateless; + +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import junit.framework.TestCase; +import examples.model.Department; +import examples.model.Employee; +import examples.stateless.DepartmentServiceBean; + +public class DepartmentServiceBeanTest extends TestCase { + + private EntityManager em; + private EntityManagerFactory emf; + + public void setUp() { + emf = Persistence.createEntityManagerFactory("hr"); + em = emf.createEntityManager(); + createTestData(); + } + + private void createTestData() { + Employee emp = new Employee(500, "Scott"); + em.persist(emp); + emp = new Employee(600, "John"); + em.persist(emp); + Department dept = new Department(700, "TEST"); + dept.getEmployees().add(emp); + emp.setDepartment(dept); + em.persist(dept); + } + + public void testAssignEmployeeToDepartment() throws Exception { + DepartmentServiceBean bean = new DepartmentServiceBean(); + bean.em = em; + bean.tx = new NullUserTransaction(); + em.getTransaction().begin(); + List result = bean.assignEmployeeToDepartment(700, 500); + em.getTransaction().rollback(); + assertEquals(2, result.size()); + assertEquals("John", ((Employee)result.get(0)).getName()); + assertEquals("Scott", ((Employee)result.get(1)).getName()); + } +} \ No newline at end of file diff --git a/examples/Chapter12/08-nullUserTxTesting/src/test/examples/stateless/NullUserTransaction.java b/examples/Chapter12/08-nullUserTxTesting/src/test/examples/stateless/NullUserTransaction.java new file mode 100644 index 0000000..608be90 --- /dev/null +++ b/examples/Chapter12/08-nullUserTxTesting/src/test/examples/stateless/NullUserTransaction.java @@ -0,0 +1,16 @@ +package examples.stateless; + +import javax.transaction.Status; +import javax.transaction.UserTransaction; + +public class NullUserTransaction implements UserTransaction { + public void begin() {} + public void commit() {} + public void rollback() {} + public void setRollbackOnly() {} + public int getStatus() { + return Status.STATUS_NO_TRANSACTION; + } + public void setTransactionTimeout(int timeout) {} +} + diff --git a/examples/Chapter12/09-containerManagedEmTesting/build.xml b/examples/Chapter12/09-containerManagedEmTesting/build.xml new file mode 100644 index 0000000..6fc53be --- /dev/null +++ b/examples/Chapter12/09-containerManagedEmTesting/build.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Chapter12/09-containerManagedEmTesting/etc/persistence/META-INF/persistence.xml b/examples/Chapter12/09-containerManagedEmTesting/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..2bc120d --- /dev/null +++ b/examples/Chapter12/09-containerManagedEmTesting/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,14 @@ + + + examples.model.Employee + examples.model.LogRecord + + + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter12/09-containerManagedEmTesting/etc/sql/db.sql b/examples/Chapter12/09-containerManagedEmTesting/etc/sql/db.sql new file mode 100644 index 0000000..341aa4c --- /dev/null +++ b/examples/Chapter12/09-containerManagedEmTesting/etc/sql/db.sql @@ -0,0 +1,5 @@ +DROP TABLE EMPLOYEE; +DROP TABLE LOGRECORD; + +CREATE TABLE LOGRECORD (ID INTEGER NOT NULL, EMPNO INTEGER, ACTION VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), STARTDATE DATE, SALARY BIGINT); \ No newline at end of file diff --git a/examples/Chapter12/09-containerManagedEmTesting/run.bat b/examples/Chapter12/09-containerManagedEmTesting/run.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter12/09-containerManagedEmTesting/run.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter12/09-containerManagedEmTesting/src/model/examples/model/Employee.java b/examples/Chapter12/09-containerManagedEmTesting/src/model/examples/model/Employee.java new file mode 100644 index 0000000..4702666 --- /dev/null +++ b/examples/Chapter12/09-containerManagedEmTesting/src/model/examples/model/Employee.java @@ -0,0 +1,58 @@ +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() + + ", startDate: " + DateFormat.getDateInstance().format(getStartDate()); + } +} diff --git a/examples/Chapter12/09-containerManagedEmTesting/src/model/examples/model/LogRecord.java b/examples/Chapter12/09-containerManagedEmTesting/src/model/examples/model/LogRecord.java new file mode 100644 index 0000000..4714441 --- /dev/null +++ b/examples/Chapter12/09-containerManagedEmTesting/src/model/examples/model/LogRecord.java @@ -0,0 +1,47 @@ +package examples.model; + + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class LogRecord { + @Id + 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/Chapter12/09-containerManagedEmTesting/src/model/examples/stateless/AuditService.java b/examples/Chapter12/09-containerManagedEmTesting/src/model/examples/stateless/AuditService.java new file mode 100644 index 0000000..c2ad1c0 --- /dev/null +++ b/examples/Chapter12/09-containerManagedEmTesting/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/Chapter12/09-containerManagedEmTesting/src/model/examples/stateless/AuditServiceBean.java b/examples/Chapter12/09-containerManagedEmTesting/src/model/examples/stateless/AuditServiceBean.java new file mode 100644 index 0000000..0b3ef82 --- /dev/null +++ b/examples/Chapter12/09-containerManagedEmTesting/src/model/examples/stateless/AuditServiceBean.java @@ -0,0 +1,28 @@ +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 { + private EntityManager em; + + @PersistenceContext(unitName="hr") + void setEntityManager(EntityManager em) { + this.em = em; + } + + public void logTransaction(int empNo, String action) { + // verify employee number is valid + if (em.find(Employee.class, empNo) == null) { + throw new IllegalArgumentException("Unknown employee id"); + } + System.out.println("Message: " + action); + LogRecord lr = new LogRecord(empNo, action); + em.persist(lr); + } +} diff --git a/examples/Chapter12/09-containerManagedEmTesting/src/model/examples/stateless/EmployeeService.java b/examples/Chapter12/09-containerManagedEmTesting/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..d9c41fb --- /dev/null +++ b/examples/Chapter12/09-containerManagedEmTesting/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,7 @@ +package examples.stateless; + +import examples.model.Employee; + +public interface EmployeeService { + public void createEmployee(Employee emp); +} diff --git a/examples/Chapter12/09-containerManagedEmTesting/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter12/09-containerManagedEmTesting/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..392897f --- /dev/null +++ b/examples/Chapter12/09-containerManagedEmTesting/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,29 @@ +package examples.stateless; + +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 { + EntityManager em; + AuditService audit; + + @PersistenceContext + void setEntityManager(EntityManager em) { + this.em = em; + } + + @EJB + void setAuditService(AuditService audit) { + this.audit = audit; + } + + public void createEmployee(Employee emp) { + em.persist(emp); + audit.logTransaction(emp.getId(), "created employee"); + } +} diff --git a/examples/Chapter12/09-containerManagedEmTesting/src/test/examples/stateless/EntityUserTransaction.java b/examples/Chapter12/09-containerManagedEmTesting/src/test/examples/stateless/EntityUserTransaction.java new file mode 100644 index 0000000..d89ba94 --- /dev/null +++ b/examples/Chapter12/09-containerManagedEmTesting/src/test/examples/stateless/EntityUserTransaction.java @@ -0,0 +1,57 @@ +package examples.stateless; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceException; +import javax.transaction.NotSupportedException; +import javax.transaction.RollbackException; +import javax.transaction.Status; +import javax.transaction.SystemException; +import javax.transaction.UserTransaction; + +public class EntityUserTransaction implements UserTransaction { + private EntityManager em; + + public EntityUserTransaction(EntityManager em) { + this.em = em; + } + + public void begin() throws NotSupportedException { + if (em.getTransaction().isActive()) { + throw new NotSupportedException(); + } + em.getTransaction().begin(); + } + + public void commit() throws RollbackException { + try { + em.getTransaction().commit(); + } catch (javax.persistence.RollbackException e) { + throw new RollbackException(e.getMessage()); + } + } + + public void rollback() throws SystemException { + try { + em.getTransaction().rollback(); + } catch (PersistenceException e) { + throw new SystemException(e.getMessage()); + } + } + + public void setRollbackOnly() { + em.getTransaction().setRollbackOnly(); + } + + public int getStatus() { + if (em.getTransaction().isActive()) { + return Status.STATUS_ACTIVE; + } else { + return Status.STATUS_NO_TRANSACTION; + } + } + + public void setTransactionTimeout(int timeout) { + throw new UnsupportedOperationException(); + } +} + diff --git a/examples/Chapter12/09-containerManagedEmTesting/src/test/examples/stateless/TestEmployeeServiceBean.java b/examples/Chapter12/09-containerManagedEmTesting/src/test/examples/stateless/TestEmployeeServiceBean.java new file mode 100644 index 0000000..871b2e9 --- /dev/null +++ b/examples/Chapter12/09-containerManagedEmTesting/src/test/examples/stateless/TestEmployeeServiceBean.java @@ -0,0 +1,37 @@ +package examples.stateless; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import junit.framework.TestCase; +import examples.model.Employee; +import examples.stateless.AuditServiceBean; +import examples.stateless.EmployeeServiceBean; + +public class TestEmployeeServiceBean extends TestCase { + + private EntityManager em; + private EntityManagerFactory emf; + + public void setUp() { + emf = Persistence.createEntityManagerFactory("hr"); + em = emf.createEntityManager(); + } + + public void testCreateEmployee() throws Exception { + EmployeeServiceBean bean = new EmployeeServiceBean(); + AuditServiceBean auditBean = new AuditServiceBean(); + bean.setEntityManager(em); + bean.setAuditService(auditBean); + auditBean.setEntityManager(em); + Employee emp = new Employee(); + emp.setId(99); + emp.setName("Wayne"); + bean.createEmployee(emp); + emp = em.find(Employee.class, 99); + assertNotNull(emp); + assertEquals(99, emp.getId()); + assertEquals("Wayne", emp.getName()); + } +} \ No newline at end of file diff --git a/examples/Chapter12/10-springTesting/build.xml b/examples/Chapter12/10-springTesting/build.xml new file mode 100644 index 0000000..89d8964 --- /dev/null +++ b/examples/Chapter12/10-springTesting/build.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Chapter12/10-springTesting/etc/persistence/META-INF/persistence.xml b/examples/Chapter12/10-springTesting/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..f45a8b0 --- /dev/null +++ b/examples/Chapter12/10-springTesting/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,14 @@ + + + examples.model.Employee + examples.model.LogRecord + + + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter12/10-springTesting/etc/spring/test-employee-service-bean.xml b/examples/Chapter12/10-springTesting/etc/spring/test-employee-service-bean.xml new file mode 100644 index 0000000..0a720d8 --- /dev/null +++ b/examples/Chapter12/10-springTesting/etc/spring/test-employee-service-bean.xml @@ -0,0 +1,35 @@ + + + + + + + hr + + + + + + + + + + + + + + + + + + + diff --git a/examples/Chapter12/10-springTesting/etc/sql/db.sql b/examples/Chapter12/10-springTesting/etc/sql/db.sql new file mode 100644 index 0000000..4adf337 --- /dev/null +++ b/examples/Chapter12/10-springTesting/etc/sql/db.sql @@ -0,0 +1,3 @@ +DROP TABLE EMPLOYEE; + +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), STARTDATE DATE, SALARY BIGINT); \ No newline at end of file diff --git a/examples/Chapter12/10-springTesting/run.bat b/examples/Chapter12/10-springTesting/run.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter12/10-springTesting/run.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter12/10-springTesting/src/model/examples/model/Employee.java b/examples/Chapter12/10-springTesting/src/model/examples/model/Employee.java new file mode 100644 index 0000000..4702666 --- /dev/null +++ b/examples/Chapter12/10-springTesting/src/model/examples/model/Employee.java @@ -0,0 +1,58 @@ +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() + + ", startDate: " + DateFormat.getDateInstance().format(getStartDate()); + } +} diff --git a/examples/Chapter12/10-springTesting/src/model/examples/model/LogRecord.java b/examples/Chapter12/10-springTesting/src/model/examples/model/LogRecord.java new file mode 100644 index 0000000..4714441 --- /dev/null +++ b/examples/Chapter12/10-springTesting/src/model/examples/model/LogRecord.java @@ -0,0 +1,47 @@ +package examples.model; + + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class LogRecord { + @Id + 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/Chapter12/10-springTesting/src/model/examples/stateless/AuditService.java b/examples/Chapter12/10-springTesting/src/model/examples/stateless/AuditService.java new file mode 100644 index 0000000..c2ad1c0 --- /dev/null +++ b/examples/Chapter12/10-springTesting/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/Chapter12/10-springTesting/src/model/examples/stateless/AuditServiceBean.java b/examples/Chapter12/10-springTesting/src/model/examples/stateless/AuditServiceBean.java new file mode 100644 index 0000000..4e5969a --- /dev/null +++ b/examples/Chapter12/10-springTesting/src/model/examples/stateless/AuditServiceBean.java @@ -0,0 +1,28 @@ +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 { + private EntityManager entityManager; + + @PersistenceContext(unitName="hr") + public void setEntityManager(EntityManager em) { + this.entityManager = em; + } + + public void logTransaction(int empNo, String action) { + // verify employee number is valid + if (entityManager.find(Employee.class, empNo) == null) { + throw new IllegalArgumentException("Unknown employee id"); + } + System.out.println("Message: " + action); + LogRecord lr = new LogRecord(empNo, action); + entityManager.persist(lr); + } +} diff --git a/examples/Chapter12/10-springTesting/src/model/examples/stateless/EmployeeService.java b/examples/Chapter12/10-springTesting/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..d9c41fb --- /dev/null +++ b/examples/Chapter12/10-springTesting/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,7 @@ +package examples.stateless; + +import examples.model.Employee; + +public interface EmployeeService { + public void createEmployee(Employee emp); +} diff --git a/examples/Chapter12/10-springTesting/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter12/10-springTesting/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..aeecac9 --- /dev/null +++ b/examples/Chapter12/10-springTesting/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,29 @@ +package examples.stateless; + +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 { + EntityManager entityManager; + AuditService auditService; + + @PersistenceContext + public void setEntityManager(EntityManager em) { + this.entityManager = em; + } + + @EJB + public void setAuditService(AuditService audit) { + this.auditService = audit; + } + + public void createEmployee(Employee emp) { + entityManager.persist(emp); + auditService.logTransaction(emp.getId(), "created employee"); + } +} diff --git a/examples/Chapter12/10-springTesting/src/test/examples/stateless/EntityManagerFactoryBean.java b/examples/Chapter12/10-springTesting/src/test/examples/stateless/EntityManagerFactoryBean.java new file mode 100644 index 0000000..32c94bb --- /dev/null +++ b/examples/Chapter12/10-springTesting/src/test/examples/stateless/EntityManagerFactoryBean.java @@ -0,0 +1,27 @@ +package examples.stateless; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +public class EntityManagerFactoryBean { + String unitName; + EntityManagerFactory emf; + + public void setUnitName(String unitName) { + this.unitName = unitName; + } + + public EntityManager createEntityManager() { + if (emf == null) { + emf = Persistence.createEntityManagerFactory(unitName); + } + return emf.createEntityManager(); + } + + public void destroy() { + if (emf != null) { + emf.close(); + } + } +} diff --git a/examples/Chapter12/10-springTesting/src/test/examples/stateless/TestEmployeeServiceBean.java b/examples/Chapter12/10-springTesting/src/test/examples/stateless/TestEmployeeServiceBean.java new file mode 100644 index 0000000..1feaf4d --- /dev/null +++ b/examples/Chapter12/10-springTesting/src/test/examples/stateless/TestEmployeeServiceBean.java @@ -0,0 +1,39 @@ +package examples.stateless; + +import javax.persistence.EntityManager; + +import junit.framework.TestCase; + +import org.springframework.beans.factory.xml.XmlBeanFactory; +import org.springframework.core.io.ClassPathResource; + +import examples.model.Employee; + +public class TestEmployeeServiceBean extends TestCase { + XmlBeanFactory factory; + + public void setUp() { + ClassPathResource resource = + new ClassPathResource("test-employee-service-bean.xml"); + factory = new XmlBeanFactory(resource); + } + + public void tearDown() { + factory.destroySingletons(); + } + + public void testCreateEmployee() throws Exception { + EmployeeService bean = + (EmployeeService) factory.getBean("employee-service"); + Employee emp = new Employee(); + emp.setId(99); + emp.setName("Wayne"); + bean.createEmployee(emp); + EntityManager em = + (EntityManager) factory.getBean("shared-entity-manager"); + emp = em.find(Employee.class, 99); + assertNotNull(emp); + assertEquals(99, emp.getId()); + assertEquals("Wayne", emp.getName()); + } +} diff --git a/examples/Chapter13/entityBeanMigration/build.xml b/examples/Chapter13/entityBeanMigration/build.xml new file mode 100644 index 0000000..55c4a1c --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/build.xml @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Chapter13/entityBeanMigration/deploy.bat b/examples/Chapter13/entityBeanMigration/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter13/entityBeanMigration/etc/persistence/META-INF/persistence.xml b/examples/Chapter13/entityBeanMigration/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..6248f03 --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/entityBeanMigration + + + + + + \ No newline at end of file diff --git a/examples/Chapter13/entityBeanMigration/etc/sql/db.sql b/examples/Chapter13/entityBeanMigration/etc/sql/db.sql new file mode 100644 index 0000000..80b83ec --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/etc/sql/db.sql @@ -0,0 +1,66 @@ +DROP TABLE PROJECT_EMPLOYEE; +DROP TABLE EMPLOYEE; +DROP TABLE PROJECT; +DROP TABLE DEPT; +DROP TABLE ADDRESS; + +CREATE TABLE DEPT (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), SALARY BIGINT, + DEPARTMENT_ID INTEGER, MANAGER_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT DEPT_FK FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPT (ID), + CONSTRAINT MGR_FK FOREIGN KEY (MANAGER_ID) REFERENCES EMPLOYEE (ID)); +CREATE TABLE PROJECT_EMPLOYEE (EMPLOYEES_ID INTEGER, PROJECTS_ID INTEGER, + CONSTRAINT EMPLOYEES_FK FOREIGN KEY (EMPLOYEES_ID) REFERENCES EMPLOYEE(ID), + CONSTRAINT PROJECTS_FK FOREIGN KEY (PROJECTS_ID) REFERENCES PROJECT(ID)); +CREATE TABLE ADDRESS (ID INTEGER NOT NULL, CITY VARCHAR(255), STATE VARCHAR(255), STREET VARCHAR(255), ZIP_CODE VARCHAR(255), PRIMARY KEY (ID)); + + +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP_CODE) VALUES (1, 'New York', 'NY', '123 Apple Tree Cr.', '10001'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP_CODE) VALUES (2, 'Manhattan', 'NY', '654 Stanton Way.', '10003'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP_CODE) VALUES (3, 'New York', 'NY', '99 Queen St.', '10001'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP_CODE) VALUES (4, 'Redwood Shores', 'CA', '445 McDonell Cr.', '90123'); +INSERT INTO ADDRESS (ID, CITY, STATE, STREET, ZIP_CODE) VALUES (5, 'San Jose', 'CA', '624 Hamilton Dr.', '90123'); + + +INSERT INTO DEPT (ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO DEPT (ID, NAME) VALUES (2, 'QA'); +INSERT INTO DEPT (ID, NAME) VALUES (3, 'Accounting'); + +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 EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID, MANAGER_ID) VALUES (10, 'Joan', 59000, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID, MANAGER_ID) VALUES (9, 'Sarah', 52000, 2, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID, MANAGER_ID) VALUES (1, 'John', 55000, 2, 9); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID, MANAGER_ID) VALUES (2, 'Rob', 53000, 2, 9); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID, MANAGER_ID) VALUES (3, 'Peter', 40000, 2, 9); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID, MANAGER_ID) VALUES (4, 'Frank', 41000, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID, MANAGER_ID) VALUES (5, 'Scott', 60000, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID, MANAGER_ID) VALUES (6, 'Sue', 62000, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID, MANAGER_ID) VALUES (7, 'Stephanie', 54000, 1, 10); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID, MANAGER_ID) VALUES (8, 'Jennifer', 45000, 1, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID, MANAGER_ID) VALUES (11, 'Marcus', 35000, NULL, NULL); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID, MANAGER_ID) VALUES (12, 'Joe', 36000, 3, 11); +INSERT INTO EMPLOYEE (ID, NAME, SALARY, DEPARTMENT_ID, MANAGER_ID) VALUES (13, 'Jack', 43000, 3, NULL); + +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/Chapter13/entityBeanMigration/etc/web/WEB-INF/web.xml b/examples/Chapter13/entityBeanMigration/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/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/Chapter13/entityBeanMigration/src/ejb/examples/stateless/DepartmentHome.java b/examples/Chapter13/entityBeanMigration/src/ejb/examples/stateless/DepartmentHome.java new file mode 100644 index 0000000..5a0246b --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/src/ejb/examples/stateless/DepartmentHome.java @@ -0,0 +1,20 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.CreateException; +import javax.ejb.FinderException; +import javax.ejb.RemoveException; + +import examples.model.Department; + +public interface DepartmentHome { + public Department create(int id) throws CreateException; + public Department findByPrimaryKey(int id) throws FinderException; + public Collection findAll() throws FinderException; + public Collection findByName(String name) throws FinderException; + public Collection unallocatedEmployees(); + public void remove (Object pk) throws RemoveException; + public void remove (Department dept) throws RemoveException; +} + diff --git a/examples/Chapter13/entityBeanMigration/src/ejb/examples/stateless/DepartmentHomeBean.java b/examples/Chapter13/entityBeanMigration/src/ejb/examples/stateless/DepartmentHomeBean.java new file mode 100644 index 0000000..17e195a --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/src/ejb/examples/stateless/DepartmentHomeBean.java @@ -0,0 +1,82 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.CreateException; +import javax.ejb.FinderException; +import javax.ejb.RemoveException; +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.PersistenceException; + +import examples.model.Department; + +@Stateless +@PersistenceContext(name="EmployeeService", unitName="EmployeeService") +public class DepartmentHomeBean implements DepartmentHome { + @PersistenceContext(unitName="EmployeeService") + private EntityManager em; + + public Department create(int id) throws CreateException { + Department dept = new Department(); + dept.setId(id); + try { + em.persist(dept); + } catch (PersistenceException e) { + throw new CreateException(e.getMessage()); + } catch (IllegalArgumentException e) { + throw new CreateException(e.getMessage()); + } + return dept; + } + + public Department findByPrimaryKey(int id) throws FinderException { + try { + return em.find(Department.class, id); + } catch (PersistenceException e) { + throw new FinderException(e.getMessage()); + } + } + + public Collection findAll() throws FinderException { + try { + return em.createNamedQuery("Department.findAll") + .getResultList(); + } catch (PersistenceException e) { + throw new FinderException(e.getMessage()); + } + } + + public Collection findByName(String name) throws FinderException { + try { + return em.createNamedQuery("Department.findByName") + .setParameter(1, name) + .getResultList(); + } catch (PersistenceException e) { + throw new FinderException(e.getMessage()); + } + } + + public Collection unallocatedEmployees() { + return em.createNamedQuery("Department.empsWithNoDepartment") + .getResultList(); + } + + public void remove (Object pk) throws RemoveException { + Department d = em.find(Department.class, pk); + if (d == null) { + throw new RemoveException("Unable to find entity with pk: " + pk); + } + em.remove(d); + } + + public void remove(Department dept) throws RemoveException { + Department d = em.find(Department.class, dept.getId()); + if (d == null) { + throw new RemoveException("Unable to find entity with pk: " + dept.getId()); + } + em.remove(d); + } +} + diff --git a/examples/Chapter13/entityBeanMigration/src/ejb/examples/stateless/EmployeeHome.java b/examples/Chapter13/entityBeanMigration/src/ejb/examples/stateless/EmployeeHome.java new file mode 100644 index 0000000..0897fce --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/src/ejb/examples/stateless/EmployeeHome.java @@ -0,0 +1,19 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.CreateException; +import javax.ejb.FinderException; +import javax.ejb.RemoveException; + +import examples.model.Employee; + +public interface EmployeeHome { + public Employee create(int id) throws CreateException; + public Employee findByPrimaryKey(int id) throws FinderException; + public Collection findAll() throws FinderException; + public Collection getManagerStats() throws FinderException; + public void remove (Object pk) throws RemoveException; + public void remove (Employee emp) throws RemoveException; +} + diff --git a/examples/Chapter13/entityBeanMigration/src/ejb/examples/stateless/EmployeeHomeBean.java b/examples/Chapter13/entityBeanMigration/src/ejb/examples/stateless/EmployeeHomeBean.java new file mode 100644 index 0000000..3ef753b --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/src/ejb/examples/stateless/EmployeeHomeBean.java @@ -0,0 +1,76 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.CreateException; +import javax.ejb.FinderException; +import javax.ejb.RemoveException; +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.PersistenceException; + +import examples.model.Employee; + +@Stateless +@PersistenceContext(name="EmployeeService", unitName="EmployeeService") +public class EmployeeHomeBean implements EmployeeHome { + @PersistenceContext(unitName="EmployeeService") + private EntityManager em; + + public Employee create(int id) throws CreateException { + Employee emp = new Employee(); + emp.setId(id); + try { + em.persist(emp); + } catch (PersistenceException e) { + throw new CreateException(e.getMessage()); + } catch (IllegalArgumentException e) { + throw new CreateException(e.getMessage()); + } + return emp; + } + + public Employee findByPrimaryKey(int id) throws FinderException { + try { + return em.find(Employee.class, id); + } catch (PersistenceException e) { + throw new FinderException(e.getMessage()); + } + } + + public Collection findAll() throws FinderException { + try { + return em.createNamedQuery("Employee.findAll") + .getResultList(); + } catch (PersistenceException e) { + throw new FinderException(e.getMessage()); + } + } + + public Collection getManagerStats() throws FinderException { + try { + return em.createNamedQuery("Employee.findManagerStats") + .getResultList(); + } catch (PersistenceException e) { + throw new FinderException(e.getMessage()); + } + } + + public void remove (Object pk) throws RemoveException { + Employee e = em.find(Employee.class, pk); + if (e == null) { + throw new RemoveException("Unable to find entity with pk: " + pk); + } + em.remove(e); + } + + public void remove(Employee emp) throws RemoveException { + Employee e = em.find(Employee.class, emp.getId()); + if (e == null) { + throw new RemoveException("Unable to find entity with pk: " + emp.getId()); + } + em.remove(e); + } +} + diff --git a/examples/Chapter13/entityBeanMigration/src/ejb/examples/stateless/ProjectService.java b/examples/Chapter13/entityBeanMigration/src/ejb/examples/stateless/ProjectService.java new file mode 100644 index 0000000..bd20640 --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/src/ejb/examples/stateless/ProjectService.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import examples.model.ApplicationException; + +public interface ProjectService { + + public void addEmployeeToProject(int projectId, int empId) + throws ApplicationException; + // ... +} + diff --git a/examples/Chapter13/entityBeanMigration/src/ejb/examples/stateless/ProjectServiceBean.java b/examples/Chapter13/entityBeanMigration/src/ejb/examples/stateless/ProjectServiceBean.java new file mode 100644 index 0000000..f1e216f --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/src/ejb/examples/stateless/ProjectServiceBean.java @@ -0,0 +1,29 @@ +package examples.stateless; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; + +import examples.model.ApplicationException; +import examples.model.Employee; +import examples.model.Project; + +@Stateless +public class ProjectServiceBean implements ProjectService { + @PersistenceContext(name="EmployeeService") + private EntityManager em; + + public void addEmployeeToProject(int projectId, int empId) + throws ApplicationException { + Project project = em.find(Project.class, projectId); + if (project == null) + throw new ApplicationException("Unknown project id: " + projectId); + Employee emp = em.find(Employee.class, empId); + if (emp == null) + throw new ApplicationException("Unknown employee id: " + empId); + project.getEmployees().add(emp); + emp.getProjects().add(project); + } + + // ... +} diff --git a/examples/Chapter13/entityBeanMigration/src/model/examples/entitybean/Department.java b/examples/Chapter13/entityBeanMigration/src/model/examples/entitybean/Department.java new file mode 100644 index 0000000..dac4829 --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/src/model/examples/entitybean/Department.java @@ -0,0 +1,19 @@ +package examples.entitybean; + +import java.util.Collection; + +import javax.ejb.EJBLocalObject; + +public interface Department extends EJBLocalObject { + public int getId(); + public void setId(int id); + + public String getName(); + public void setName(String name); + + public Collection getEmployees(); + public void setEmployees(Collection employees); + + public Employee getManager(); +} + diff --git a/examples/Chapter13/entityBeanMigration/src/model/examples/entitybean/DepartmentBean.java b/examples/Chapter13/entityBeanMigration/src/model/examples/entitybean/DepartmentBean.java new file mode 100644 index 0000000..b454c9e --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/src/model/examples/entitybean/DepartmentBean.java @@ -0,0 +1,42 @@ +package examples.entitybean; + +import java.util.Collection; + +import javax.ejb.CreateException; +import javax.ejb.EntityBean; +import javax.ejb.EntityContext; + +public abstract class DepartmentBean implements EntityBean { + public abstract int getId(); + public abstract void setId(int id); + public abstract String getName(); + public abstract void setName(String name); + public abstract Collection getEmployees(); + public abstract void setEmployees(Collection employees); + + public abstract Employee ejbSelectManagerForDept(int deptId); + public abstract Collection ejbSelectEmployeesWithNoDepartment(); + + public Employee getManager() { + return ejbSelectManagerForDept(getId()); + } + + public Integer ejbCreate(int id) throws CreateException { + setId(id); + return null; + } + + public Collection ejbHomeUnallocatedEmployees() { + return ejbSelectEmployeesWithNoDepartment(); + } + + public void ejbPostCreate(int id) throws CreateException {} + public void ejbLoad() {} + public void ejbStore() {} + public void ejbActivate() {} + public void ejbPassivate() {} + public void ejbRemove() {} + public void setEntityContext(EntityContext ctx) {} + public void unsetEntityContext() {} +} + diff --git a/examples/Chapter13/entityBeanMigration/src/model/examples/entitybean/DepartmentHome.java b/examples/Chapter13/entityBeanMigration/src/model/examples/entitybean/DepartmentHome.java new file mode 100644 index 0000000..e912c4e --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/src/model/examples/entitybean/DepartmentHome.java @@ -0,0 +1,15 @@ +package examples.entitybean; + +import java.util.Collection; + +import javax.ejb.CreateException; +import javax.ejb.EJBLocalHome; +import javax.ejb.FinderException; + +public interface DepartmentHome extends EJBLocalHome { + public Department create(int id) throws CreateException; + public Department findByPrimaryKey(int id) throws FinderException; + public Collection findAll() throws FinderException; + public Department findByName(String name) throws FinderException; + public Collection unallocatedEmployees(); +} diff --git a/examples/Chapter13/entityBeanMigration/src/model/examples/entitybean/Employee.java b/examples/Chapter13/entityBeanMigration/src/model/examples/entitybean/Employee.java new file mode 100644 index 0000000..38efa58 --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/src/model/examples/entitybean/Employee.java @@ -0,0 +1,26 @@ +package examples.entitybean; + +import java.util.Collection; + +import javax.ejb.EJBLocalObject; + +public interface Employee extends EJBLocalObject { + public int getId(); + public void setId(int id); + + public String getname(); + public void setname(String name); + + public long getSalary(); + public void setSalary(long salary); + + public Department getDepartment(); + public void setDepartment(Department dept); + + public Collection getDirects(); + public void setDirects(Collection directs); + + public Employee getManager(); + public void setManager(Employee emp); +} + diff --git a/examples/Chapter13/entityBeanMigration/src/model/examples/entitybean/EmployeeBean.java b/examples/Chapter13/entityBeanMigration/src/model/examples/entitybean/EmployeeBean.java new file mode 100644 index 0000000..a7ab895 --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/src/model/examples/entitybean/EmployeeBean.java @@ -0,0 +1,41 @@ +package examples.entitybean; + +import java.util.Collection; + +import javax.ejb.CreateException; +import javax.ejb.EntityBean; +import javax.ejb.EntityContext; + +public abstract class EmployeeBean implements EntityBean { + public abstract int getId(); + public abstract void setId(int id); + + public abstract String getname(); + public abstract void setname(String name); + + public abstract long getSalary(); + public abstract void setSalary(long salary); + + public abstract Department getDepartment(); + public abstract void setDepartment(Department department); + + public abstract Collection getDirects(); + public abstract void setDirects(Collection directs); + + public abstract Employee getManager(); + public abstract void setManager(Employee empLocal); + + public Integer ejbCreate(int id) throws CreateException { + setId(id); + return null; + } + + public void ejbPostCreate(int id) throws CreateException {} + public void ejbLoad() {} + public void ejbStore() {} + public void ejbActivate() {} + public void ejbPassivate() {} + public void ejbRemove() {} + public void setEntityContext(EntityContext ctx) {} + public void unsetEntityContext() {} +} diff --git a/examples/Chapter13/entityBeanMigration/src/model/examples/entitybean/EmployeeHome.java b/examples/Chapter13/entityBeanMigration/src/model/examples/entitybean/EmployeeHome.java new file mode 100644 index 0000000..0bcca42 --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/src/model/examples/entitybean/EmployeeHome.java @@ -0,0 +1,10 @@ +package examples.entitybean; + +import javax.ejb.CreateException; +import javax.ejb.EJBLocalHome; +import javax.ejb.FinderException; + +public interface EmployeeHome extends EJBLocalHome { + public Employee create(int id) throws CreateException; + public Employee findByPrimaryKey(int id) throws FinderException; +} diff --git a/examples/Chapter13/entityBeanMigration/src/model/examples/entitybean/Project.java b/examples/Chapter13/entityBeanMigration/src/model/examples/entitybean/Project.java new file mode 100644 index 0000000..06f56b1 --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/src/model/examples/entitybean/Project.java @@ -0,0 +1,19 @@ +package examples.entitybean; + +import java.util.Collection; + +import javax.ejb.EJBLocalObject; + +public interface Project extends EJBLocalObject { + public int getId(); + public void setId(int id); + + public String getName(); + public void setName(String name); + + public Collection getEmployees(); + public void setEmployees(Collection employees); + + public Employee getManager(); +} + diff --git a/examples/Chapter13/entityBeanMigration/src/model/examples/entitybean/ProjectHome.java b/examples/Chapter13/entityBeanMigration/src/model/examples/entitybean/ProjectHome.java new file mode 100644 index 0000000..1b62286 --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/src/model/examples/entitybean/ProjectHome.java @@ -0,0 +1,15 @@ +package examples.entitybean; + +import java.util.Collection; + +import javax.ejb.CreateException; +import javax.ejb.EJBLocalHome; +import javax.ejb.FinderException; + +public interface ProjectHome extends EJBLocalHome { + public Project create(int id) throws CreateException; + public Project findByPrimaryKey(int id) throws FinderException; + public Collection findAll() throws FinderException; + public Project findByName(String name) throws FinderException; + public Collection unallocatedEmployees(); +} diff --git a/examples/Chapter13/entityBeanMigration/src/model/examples/model/Address.java b/examples/Chapter13/entityBeanMigration/src/model/examples/model/Address.java new file mode 100644 index 0000000..ecce15a --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/src/model/examples/model/Address.java @@ -0,0 +1,64 @@ +package examples.model; + +import javax.persistence.Column; +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; + @Column(name="ZIP_CODE") + 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 street: " + getStreet() + + ", city: " + getCity() + + ", state: " + getState() + + ", zip: " + getZip(); + } +} diff --git a/examples/Chapter13/entityBeanMigration/src/model/examples/model/AddressDAO.java b/examples/Chapter13/entityBeanMigration/src/model/examples/model/AddressDAO.java new file mode 100644 index 0000000..4116328 --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/src/model/examples/model/AddressDAO.java @@ -0,0 +1,66 @@ +package examples.model; + +import javax.persistence.EntityManager; + +public class AddressDAO { + private EntityManager em; + + public AddressDAO(EntityManager em) { + this.em = em; + } + + public void create(AddressTO address) { + Address entity = createEntity(address); + em.joinTransaction(); + em.persist(entity); + } + + + public void update(AddressTO address) { + em.joinTransaction(); + em.merge(createEntity(address)); + } + + + public void remove(int id) { + em.joinTransaction(); + Address entity = em.find(Address.class, id); + if (entity != null) { + em.remove(entity); + } else { + throw new RuntimeException("No such address id: " + id); + } + } + + public AddressTO find(int id) { + Address entity = em.find(Address.class, id); + if (entity != null) { + return createTO(entity); + } else { + return null; + } + } + + + private Address createEntity(AddressTO address) { + Address entity = new Address(); + entity.setId(address.getId()); + entity.setStreet(address.getStreet()); + entity.setCity(address.getCity()); + entity.setState(address.getState()); + entity.setZip(address.getZip()); + return entity; + } + + private AddressTO createTO(Address entity) { + AddressTO address = new AddressTO(); + address.setId(entity.getId()); + address.setStreet(entity.getStreet()); + address.setCity(entity.getCity()); + address.setState(entity.getState()); + address.setZip(entity.getZip()); + return address; + } +} + + diff --git a/examples/Chapter13/entityBeanMigration/src/model/examples/model/AddressEntityDAO.java b/examples/Chapter13/entityBeanMigration/src/model/examples/model/AddressEntityDAO.java new file mode 100644 index 0000000..8efd9f2 --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/src/model/examples/model/AddressEntityDAO.java @@ -0,0 +1,41 @@ +package examples.model; + + +import javax.persistence.EntityManager; + +public class AddressEntityDAO { + private EntityManager em; + + + public AddressEntityDAO(EntityManager em) { + this.em = em; + } + + + public void create(Address address) { + em.joinTransaction(); + em.persist(address); + } + + + public void update(Address address) { + em.joinTransaction(); + em.merge(address); + } + + + public void remove(int id) { + em.joinTransaction(); + Address entity = em.find(Address.class, id); + if (entity != null) { + em.remove(entity); + } else { + throw new RuntimeException("No such address id: " + id); + } + } + + + public Address find(int id) { + return em.find(Address.class, id); + } +} diff --git a/examples/Chapter13/entityBeanMigration/src/model/examples/model/AddressTO.java b/examples/Chapter13/entityBeanMigration/src/model/examples/model/AddressTO.java new file mode 100644 index 0000000..d94d0f6 --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/src/model/examples/model/AddressTO.java @@ -0,0 +1,42 @@ +package examples.model; + +public class AddressTO implements java.io.Serializable { + private int id; + private String street; + private String city; + private String state; + private String zip; + + public AddressTO() {} + + public AddressTO(int id, String street, String city, + String state, String zip) { + this.id = id; + this.street = street; + this.city = city; + this.state = state; + this.zip = zip; + } + + public int getId() { return id; } + public void setId(int id) { this.id = id; } + + 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 getStreet() { return street; } + public void setStreet(String street) { this.street = street; } + + 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/Chapter13/entityBeanMigration/src/model/examples/model/ApplicationException.java b/examples/Chapter13/entityBeanMigration/src/model/examples/model/ApplicationException.java new file mode 100644 index 0000000..b072cb4 --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/src/model/examples/model/ApplicationException.java @@ -0,0 +1,19 @@ +package examples.model; + +public class ApplicationException extends Exception { + + public ApplicationException() { + } + + public ApplicationException(String message, Throwable cause) { + super(message, cause); + } + + public ApplicationException(String message) { + super(message); + } + + public ApplicationException(Throwable cause) { + super(cause); + } +} diff --git a/examples/Chapter13/entityBeanMigration/src/model/examples/model/Department.java b/examples/Chapter13/entityBeanMigration/src/model/examples/model/Department.java new file mode 100644 index 0000000..ec2c7e1 --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/src/model/examples/model/Department.java @@ -0,0 +1,76 @@ +package examples.model; + + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.EntityManager; +import javax.persistence.Id; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.NoResultException; +import javax.persistence.OneToMany; +import javax.persistence.Table; + +@Entity +@Table(name = "DEPT") +@NamedQueries({ + @NamedQuery(name = "Department.managerForDept", + query = "SELECT OBJECT(e) " + + "FROM Employee e " + + "WHERE e.department.id = ?1 AND e.manager.department.id <> ?1"), + @NamedQuery(name="Department.findAll", + query="SELECT d FROM Department d"), + @NamedQuery(name="Department.empsWithNoDepartment", + query="SELECT e FROM Employee e WHERE e.department IS NULL"), + @NamedQuery(name="Department.findByName", + query="SELECT d FROM Department d WHERE d.name = ?1") +}) +public class Department { + @Id + private int id; + private String name; + @OneToMany(mappedBy = "department") + private Collection 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 void addEmployee(Employee emp) { + getEmployees().add(emp); + emp.setDepartment(this); + } + + public Employee getManager() { + EntityManager em = ServiceLocator.getInstance().getEntityManager("EmployeeService"); + try { + return (Employee) em.createNamedQuery("Department.managerForDept") + .setParameter(1, getId()) + .getSingleResult(); + } catch (NoResultException e) { + return null; + } + } + + public String toString() { + return "Department id: " + getId() + " name: " + getName() + " manager: " + getManager(); + } +} diff --git a/examples/Chapter13/entityBeanMigration/src/model/examples/model/Employee.java b/examples/Chapter13/entityBeanMigration/src/model/examples/model/Employee.java new file mode 100644 index 0000000..374c087 --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/src/model/examples/model/Employee.java @@ -0,0 +1,115 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +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; + + +@Entity +@NamedQueries({ + @NamedQuery(name="Employee.findAll", + query="SELECT e FROM Employee e"), + @NamedQuery(name="Employee.findManagerStats", + query="SELECT NEW examples.model.ManagerStats(e.name, COUNT(d.name), AVG(d.salary)) " + + "FROM Employee e JOIN e.directs d " + + "GROUP BY e.name") +}) +public class Employee { + @Id private int id; + private String name; + private long salary; + @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 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) { + 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 String toString() { + return "Employee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter13/entityBeanMigration/src/model/examples/model/ManagerStats.java b/examples/Chapter13/entityBeanMigration/src/model/examples/model/ManagerStats.java new file mode 100644 index 0000000..f2dd698 --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/src/model/examples/model/ManagerStats.java @@ -0,0 +1,31 @@ +package examples.model; + +public class ManagerStats { + private String managerName; + private long employeeCount; + private double avgSalary; + + public ManagerStats(String managerName, Long employeeCount, Double avgSalary) { + this.managerName = managerName; + this.employeeCount = employeeCount; + this.avgSalary = avgSalary; + } + + public String getManagerName() { + return managerName; + } + + public long getEmployeeCount() { + return employeeCount; + } + + public double getAverageSalary() { + return avgSalary; + } + + public String toString() { + return "Manager: " + getManagerName() + + " empCount: " + getEmployeeCount() + + " avgSalary: " + getAverageSalary(); + } +} diff --git a/examples/Chapter13/entityBeanMigration/src/model/examples/model/Project.java b/examples/Chapter13/entityBeanMigration/src/model/examples/model/Project.java new file mode 100644 index 0000000..6b56951 --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/src/model/examples/model/Project.java @@ -0,0 +1,52 @@ +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 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/Chapter13/entityBeanMigration/src/model/examples/model/ServiceLocator.java b/examples/Chapter13/entityBeanMigration/src/model/examples/model/ServiceLocator.java new file mode 100644 index 0000000..ad1eede --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/src/model/examples/model/ServiceLocator.java @@ -0,0 +1,27 @@ +package examples.model; + +import javax.ejb.EJBException; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.persistence.EntityManager; + +public class ServiceLocator { + private static ServiceLocator instance; + + private ServiceLocator() {} + + public static ServiceLocator getInstance() { + if (instance == null) { + instance = new ServiceLocator(); + } + return instance; + } + + public EntityManager getEntityManager(String emName) { + try { + return (EntityManager) new InitialContext().lookup("java:comp/env/" + emName); + } catch (NamingException e) { + throw new EJBException(e); + } + } +} diff --git a/examples/Chapter13/entityBeanMigration/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter13/entityBeanMigration/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..cc2adbf --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,148 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.ejb.EJB; +import javax.persistence.PersistenceContext; +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.DepartmentHome; +import examples.stateless.EmployeeHome; + +@PersistenceContext(name="EmployeeService", unitName="EmployeeService") +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 13: Using Migrated Home Facades"; + + private final String DESCRIPTION = + "This example demonstates the basics use of some migrated home facades."; + + @EJB DepartmentHome deptHome; + @EJB EmployeeHome empHome; + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + // process request + try { + String action = request.getParameter("action"); + if (action == null) { + // do nothing if no action requested + } else if (action.equals("CreateEmployee")) { + Employee emp = empHome.create(parseInt(request.getParameter("empId"))); + out.println("Created : " + emp); + } else if (action.equals("FindByPkEmployee")) { + Employee emp = empHome.findByPrimaryKey(parseInt(request.getParameter("empPk"))); + out.println("Found : " + emp); + } else if (action.equals("GetManagerStats")) { + out.println("ManagerStats:
"); + for (Object stat : empHome.getManagerStats()) { + out.print(stat + "
"); + } + } else if (action.equals("FindAllEmployees")) { + out.println("Employees:
"); + for (Object emp : empHome.findAll()) { + out.print(emp + "
"); + } + } else if (action.equals("RemoveEmployee")) { + empHome.remove(parseInt(request.getParameter("removeEmpId"))); + out.println("Removed Employee"); + + } else if (action.equals("CreateDepartment")) { + Department dept = deptHome.create(parseInt(request.getParameter("deptId"))); + out.println("Created: " + dept); + } else if (action.equals("FindByPkDepartment")) { + Department dept = deptHome.findByPrimaryKey(parseInt(request.getParameter("deptPk"))); + out.println("Found : " + dept); + } else if (action.equals("FindByNameDepartment")) { + out.println("
Departments:
"); + for (Object dept : deptHome.findByName(request.getParameter("deptName"))) { + out.print(dept + "
"); + } + } else if (action.equals("FindAllDepartments")) { + out.println("
Departments:
"); + for (Object dept : deptHome.findAll()) { + out.print(dept + "
"); + } + } else if (action.equals("UnallocatedEmployees")) { + out.println("
Departments:
"); + for (Object emp : deptHome.unallocatedEmployees()) { + out.print(emp + "
"); + } + } else if (action.equals("RemoveDepartment")) { + deptHome.remove(parseInt(request.getParameter("removeDeptId"))); + out.println("Removed Department"); + } + } 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 void printHtmlHeader(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.println("" + TITLE + ""); + out.println("

" + TITLE + "

"); + out.println("

" + DESCRIPTION + "

"); + out.println("
"); + out.println("
"); + // form for EmployeeHome Facade + out.println("

EmployeeHome Facade operations

"); + out.println("
"); + out.println("" + + ""); + out.println("" + + ""); + out.println("" + + ""); + out.println(""); + out.println(""); + out.println("
Id:(int)
Id:(int)
Id:(int)
"); + out.println("
"); + + // form for DepartmentHome Facade + out.println("

DepartmentHome Facade operations

"); + out.println(""); + out.println("" + + ""); + out.println("" + + ""); + out.println("" + + ""); + out.println("" + + ""); + out.println(""); + out.println(""); + out.println("
Id:(int)
Id:(int)
Name:(String)
Id:(int)
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter13/entityBeanMigration/undeploy.bat b/examples/Chapter13/entityBeanMigration/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter13/entityBeanMigration/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ 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..534327e --- /dev/null +++ b/examples/Chapter2/employeeService/build.xml @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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..6d7fab4 --- /dev/null +++ b/examples/Chapter2/employeeService/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,13 @@ + + + examples.model.Employee + + + + + + + + + + \ 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/run.bat b/examples/Chapter2/employeeService/run.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter2/employeeService/run.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/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..fedecc4 --- /dev/null +++ b/examples/Chapter2/employeeService/runInteractive.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant interactive_client + +pause \ No newline at end of file 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..bfb234a --- /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..b9b6293 --- /dev/null +++ b/examples/Chapter3/01-slsbExample/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +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..17d0ef3 --- /dev/null +++ b/examples/Chapter3/01-slsbExample/etc/web/WEB-INF/web.xml @@ -0,0 +1,21 @@ + + + + HelloServiceServlet + examples.servlet.HelloServiceServlet + + + + HelloServiceServlet + /HelloServiceServlet + + + + ejb/HelloService + Session + examples.stateless.HelloService + + \ 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..5c23c44 --- /dev/null +++ b/examples/Chapter3/01-slsbExample/src/servlet/examples/servlet/HelloServiceServlet.java @@ -0,0 +1,80 @@ +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.HelloService; + +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."; + + + 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) { + // lookup the HelloService + HelloService service = null; + try { + service = (HelloService) + 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/01-slsbExample/undeploy.bat b/examples/Chapter3/01-slsbExample/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter3/01-slsbExample/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/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..f025018 --- /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..b9b6293 --- /dev/null +++ b/examples/Chapter3/02-slsbLifecycleExample/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +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..00674ea --- /dev/null +++ b/examples/Chapter3/02-slsbLifecycleExample/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/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..d4a4c7b --- /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..b9b6293 --- /dev/null +++ b/examples/Chapter3/03-slsbRemoteExample/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +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..a966f3d --- /dev/null +++ b/examples/Chapter3/03-slsbRemoteExample/runClient.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/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..00674ea --- /dev/null +++ b/examples/Chapter3/03-slsbRemoteExample/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/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..43a2d90 --- /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..b9b6293 --- /dev/null +++ b/examples/Chapter3/04-sfsbExample/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +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..4bfffb7 --- /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..00674ea --- /dev/null +++ b/examples/Chapter3/04-sfsbExample/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/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..e303c8a --- /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..b9b6293 --- /dev/null +++ b/examples/Chapter3/05-sfsbLifecycleExample/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +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..8734632 --- /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..48eefa4 --- /dev/null +++ b/examples/Chapter3/05-sfsbLifecycleExample/src/servlet/examples/servlet/OrderBrowserServlet.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 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.
" + + "The simple example allows you to browse any orders that have been created. " + + "NOTE: The example doesn't show the details of issuing/parsing the jdbc to create " + + "orders, hence no orders are displayed. It only 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..00674ea --- /dev/null +++ b/examples/Chapter3/05-sfsbLifecycleExample/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter3/06-mdbExample/build.xml b/examples/Chapter3/06-mdbExample/build.xml new file mode 100644 index 0000000..f148ba4 --- /dev/null +++ b/examples/Chapter3/06-mdbExample/build.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Chapter3/06-mdbExample/deploy.bat b/examples/Chapter3/06-mdbExample/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter3/06-mdbExample/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter3/06-mdbExample/etc/web/WEB-INF/web.xml b/examples/Chapter3/06-mdbExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..1485222 --- /dev/null +++ b/examples/Chapter3/06-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/06-mdbExample/src/model/examples/mdb/ReportProcessorBean.java b/examples/Chapter3/06-mdbExample/src/model/examples/mdb/ReportProcessorBean.java new file mode 100644 index 0000000..2cae9f1 --- /dev/null +++ b/examples/Chapter3/06-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/06-mdbExample/src/servlet/examples/servlet/ReportProcessorServlet.java b/examples/Chapter3/06-mdbExample/src/servlet/examples/servlet/ReportProcessorServlet.java new file mode 100644 index 0000000..824a0b8 --- /dev/null +++ b/examples/Chapter3/06-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/06-mdbExample/undeploy.bat b/examples/Chapter3/06-mdbExample/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter3/06-mdbExample/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter3/07-servletExample/build.xml b/examples/Chapter3/07-servletExample/build.xml new file mode 100644 index 0000000..f208752 --- /dev/null +++ b/examples/Chapter3/07-servletExample/build.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/examples/Chapter3/07-servletExample/deploy.bat b/examples/Chapter3/07-servletExample/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter3/07-servletExample/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter3/07-servletExample/etc/web/WEB-INF/web.xml b/examples/Chapter3/07-servletExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..2922bb2 --- /dev/null +++ b/examples/Chapter3/07-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/07-servletExample/src/servlet/examples/servlet/LoginServlet.java b/examples/Chapter3/07-servletExample/src/servlet/examples/servlet/LoginServlet.java new file mode 100644 index 0000000..cc521d4 --- /dev/null +++ b/examples/Chapter3/07-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/07-servletExample/undeploy.bat b/examples/Chapter3/07-servletExample/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter3/07-servletExample/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter3/08-dependencyLookup/build.xml b/examples/Chapter3/08-dependencyLookup/build.xml new file mode 100644 index 0000000..08b35ac --- /dev/null +++ b/examples/Chapter3/08-dependencyLookup/build.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/examples/Chapter3/08-dependencyLookup/deploy.bat b/examples/Chapter3/08-dependencyLookup/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter3/08-dependencyLookup/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter3/08-dependencyLookup/etc/web/WEB-INF/web.xml b/examples/Chapter3/08-dependencyLookup/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..0aa3e8f --- /dev/null +++ b/examples/Chapter3/08-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/08-dependencyLookup/src/model/examples/stateless/AuditService.java b/examples/Chapter3/08-dependencyLookup/src/model/examples/stateless/AuditService.java new file mode 100644 index 0000000..8ae36bc --- /dev/null +++ b/examples/Chapter3/08-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/08-dependencyLookup/src/model/examples/stateless/AuditServiceBean.java b/examples/Chapter3/08-dependencyLookup/src/model/examples/stateless/AuditServiceBean.java new file mode 100644 index 0000000..1091120 --- /dev/null +++ b/examples/Chapter3/08-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/08-dependencyLookup/src/model/examples/stateless/DepartmentService.java b/examples/Chapter3/08-dependencyLookup/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..3225979 --- /dev/null +++ b/examples/Chapter3/08-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/08-dependencyLookup/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter3/08-dependencyLookup/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..02bc39a --- /dev/null +++ b/examples/Chapter3/08-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/08-dependencyLookup/src/servlet/examples/servlet/DepartmentServiceServlet.java b/examples/Chapter3/08-dependencyLookup/src/servlet/examples/servlet/DepartmentServiceServlet.java new file mode 100644 index 0000000..919a818 --- /dev/null +++ b/examples/Chapter3/08-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/08-dependencyLookup/undeploy.bat b/examples/Chapter3/08-dependencyLookup/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter3/08-dependencyLookup/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter3/09-ejbContextLookup/build.xml b/examples/Chapter3/09-ejbContextLookup/build.xml new file mode 100644 index 0000000..e2b88fe --- /dev/null +++ b/examples/Chapter3/09-ejbContextLookup/build.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/examples/Chapter3/09-ejbContextLookup/deploy.bat b/examples/Chapter3/09-ejbContextLookup/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter3/09-ejbContextLookup/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter3/09-ejbContextLookup/etc/web/WEB-INF/web.xml b/examples/Chapter3/09-ejbContextLookup/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..0aa3e8f --- /dev/null +++ b/examples/Chapter3/09-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/09-ejbContextLookup/src/model/examples/stateless/AuditService.java b/examples/Chapter3/09-ejbContextLookup/src/model/examples/stateless/AuditService.java new file mode 100644 index 0000000..8ae36bc --- /dev/null +++ b/examples/Chapter3/09-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/09-ejbContextLookup/src/model/examples/stateless/AuditServiceBean.java b/examples/Chapter3/09-ejbContextLookup/src/model/examples/stateless/AuditServiceBean.java new file mode 100644 index 0000000..1091120 --- /dev/null +++ b/examples/Chapter3/09-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/09-ejbContextLookup/src/model/examples/stateless/DepartmentService.java b/examples/Chapter3/09-ejbContextLookup/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..3225979 --- /dev/null +++ b/examples/Chapter3/09-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/09-ejbContextLookup/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter3/09-ejbContextLookup/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..8a785b9 --- /dev/null +++ b/examples/Chapter3/09-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/09-ejbContextLookup/src/servlet/examples/servlet/DepartmentServiceServlet.java b/examples/Chapter3/09-ejbContextLookup/src/servlet/examples/servlet/DepartmentServiceServlet.java new file mode 100644 index 0000000..5dbbd52 --- /dev/null +++ b/examples/Chapter3/09-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/09-ejbContextLookup/undeploy.bat b/examples/Chapter3/09-ejbContextLookup/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter3/09-ejbContextLookup/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter3/10-fieldInjection/build.xml b/examples/Chapter3/10-fieldInjection/build.xml new file mode 100644 index 0000000..0b58252 --- /dev/null +++ b/examples/Chapter3/10-fieldInjection/build.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/examples/Chapter3/10-fieldInjection/deploy.bat b/examples/Chapter3/10-fieldInjection/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter3/10-fieldInjection/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter3/10-fieldInjection/etc/web/WEB-INF/web.xml b/examples/Chapter3/10-fieldInjection/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..a64ff0e --- /dev/null +++ b/examples/Chapter3/10-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/10-fieldInjection/src/model/examples/stateless/AuditService.java b/examples/Chapter3/10-fieldInjection/src/model/examples/stateless/AuditService.java new file mode 100644 index 0000000..8ae36bc --- /dev/null +++ b/examples/Chapter3/10-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/10-fieldInjection/src/model/examples/stateless/AuditServiceBean.java b/examples/Chapter3/10-fieldInjection/src/model/examples/stateless/AuditServiceBean.java new file mode 100644 index 0000000..1091120 --- /dev/null +++ b/examples/Chapter3/10-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/10-fieldInjection/src/model/examples/stateless/DepartmentService.java b/examples/Chapter3/10-fieldInjection/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..3225979 --- /dev/null +++ b/examples/Chapter3/10-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/10-fieldInjection/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter3/10-fieldInjection/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..410f407 --- /dev/null +++ b/examples/Chapter3/10-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/10-fieldInjection/src/servlet/examples/servlet/DepartmentServiceServlet.java b/examples/Chapter3/10-fieldInjection/src/servlet/examples/servlet/DepartmentServiceServlet.java new file mode 100644 index 0000000..3be4068 --- /dev/null +++ b/examples/Chapter3/10-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/10-fieldInjection/undeploy.bat b/examples/Chapter3/10-fieldInjection/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter3/10-fieldInjection/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter3/11-setterInjection/build.xml b/examples/Chapter3/11-setterInjection/build.xml new file mode 100644 index 0000000..8c38acb --- /dev/null +++ b/examples/Chapter3/11-setterInjection/build.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/examples/Chapter3/11-setterInjection/deploy.bat b/examples/Chapter3/11-setterInjection/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter3/11-setterInjection/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter3/11-setterInjection/etc/web/WEB-INF/web.xml b/examples/Chapter3/11-setterInjection/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..a64ff0e --- /dev/null +++ b/examples/Chapter3/11-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/11-setterInjection/src/model/examples/stateless/AuditService.java b/examples/Chapter3/11-setterInjection/src/model/examples/stateless/AuditService.java new file mode 100644 index 0000000..8ae36bc --- /dev/null +++ b/examples/Chapter3/11-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/11-setterInjection/src/model/examples/stateless/AuditServiceBean.java b/examples/Chapter3/11-setterInjection/src/model/examples/stateless/AuditServiceBean.java new file mode 100644 index 0000000..1091120 --- /dev/null +++ b/examples/Chapter3/11-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/11-setterInjection/src/model/examples/stateless/DepartmentService.java b/examples/Chapter3/11-setterInjection/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..3225979 --- /dev/null +++ b/examples/Chapter3/11-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/11-setterInjection/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter3/11-setterInjection/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..00cb6e3 --- /dev/null +++ b/examples/Chapter3/11-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/11-setterInjection/src/servlet/examples/servlet/DepartmentServiceServlet.java b/examples/Chapter3/11-setterInjection/src/servlet/examples/servlet/DepartmentServiceServlet.java new file mode 100644 index 0000000..b4c3c58 --- /dev/null +++ b/examples/Chapter3/11-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/11-setterInjection/undeploy.bat b/examples/Chapter3/11-setterInjection/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter3/11-setterInjection/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter3/12-bmtExample/build.xml b/examples/Chapter3/12-bmtExample/build.xml new file mode 100644 index 0000000..594bfdf --- /dev/null +++ b/examples/Chapter3/12-bmtExample/build.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/examples/Chapter3/12-bmtExample/deploy.bat b/examples/Chapter3/12-bmtExample/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter3/12-bmtExample/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter3/12-bmtExample/etc/web/WEB-INF/web.xml b/examples/Chapter3/12-bmtExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..36c8478 --- /dev/null +++ b/examples/Chapter3/12-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/12-bmtExample/src/model/examples/stateless/ProcessingService.java b/examples/Chapter3/12-bmtExample/src/model/examples/stateless/ProcessingService.java new file mode 100644 index 0000000..efba451 --- /dev/null +++ b/examples/Chapter3/12-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/12-bmtExample/src/model/examples/stateless/ProcessingServiceBean.java b/examples/Chapter3/12-bmtExample/src/model/examples/stateless/ProcessingServiceBean.java new file mode 100644 index 0000000..0111fcd --- /dev/null +++ b/examples/Chapter3/12-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/12-bmtExample/src/servlet/examples/servlet/ProcessingServiceServlet.java b/examples/Chapter3/12-bmtExample/src/servlet/examples/servlet/ProcessingServiceServlet.java new file mode 100644 index 0000000..cc9a2d3 --- /dev/null +++ b/examples/Chapter3/12-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/12-bmtExample/undeploy.bat b/examples/Chapter3/12-bmtExample/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter3/12-bmtExample/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter3/13-cmtExample/build.xml b/examples/Chapter3/13-cmtExample/build.xml new file mode 100644 index 0000000..b46c6ba --- /dev/null +++ b/examples/Chapter3/13-cmtExample/build.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/examples/Chapter3/13-cmtExample/deploy.bat b/examples/Chapter3/13-cmtExample/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter3/13-cmtExample/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter3/13-cmtExample/etc/web/WEB-INF/web.xml b/examples/Chapter3/13-cmtExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..e5b5a7e --- /dev/null +++ b/examples/Chapter3/13-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/13-cmtExample/src/model/examples/stateful/ShoppingCart.java b/examples/Chapter3/13-cmtExample/src/model/examples/stateful/ShoppingCart.java new file mode 100644 index 0000000..7e8ba32 --- /dev/null +++ b/examples/Chapter3/13-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/13-cmtExample/src/model/examples/stateful/ShoppingCartBean.java b/examples/Chapter3/13-cmtExample/src/model/examples/stateful/ShoppingCartBean.java new file mode 100644 index 0000000..337140e --- /dev/null +++ b/examples/Chapter3/13-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/13-cmtExample/src/servlet/examples/servlet/ShoppingCartServlet.java b/examples/Chapter3/13-cmtExample/src/servlet/examples/servlet/ShoppingCartServlet.java new file mode 100644 index 0000000..7106efa --- /dev/null +++ b/examples/Chapter3/13-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/13-cmtExample/undeploy.bat b/examples/Chapter3/13-cmtExample/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter3/13-cmtExample/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter3/14-userTxExample/build.xml b/examples/Chapter3/14-userTxExample/build.xml new file mode 100644 index 0000000..20bffba --- /dev/null +++ b/examples/Chapter3/14-userTxExample/build.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/examples/Chapter3/14-userTxExample/deploy.bat b/examples/Chapter3/14-userTxExample/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter3/14-userTxExample/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter3/14-userTxExample/etc/web/WEB-INF/web.xml b/examples/Chapter3/14-userTxExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..e7a135a --- /dev/null +++ b/examples/Chapter3/14-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/14-userTxExample/src/model/examples/stateless/ProjectService.java b/examples/Chapter3/14-userTxExample/src/model/examples/stateless/ProjectService.java new file mode 100644 index 0000000..7b77ecf --- /dev/null +++ b/examples/Chapter3/14-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/14-userTxExample/src/model/examples/stateless/ProjectServiceBean.java b/examples/Chapter3/14-userTxExample/src/model/examples/stateless/ProjectServiceBean.java new file mode 100644 index 0000000..4027b72 --- /dev/null +++ b/examples/Chapter3/14-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/14-userTxExample/src/servlet/examples/servlet/ProjectServlet.java b/examples/Chapter3/14-userTxExample/src/servlet/examples/servlet/ProjectServlet.java new file mode 100644 index 0000000..19d7584 --- /dev/null +++ b/examples/Chapter3/14-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/14-userTxExample/undeploy.bat b/examples/Chapter3/14-userTxExample/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter3/14-userTxExample/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter3/15-employeeService/build.xml b/examples/Chapter3/15-employeeService/build.xml new file mode 100644 index 0000000..453cb0c --- /dev/null +++ b/examples/Chapter3/15-employeeService/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter3/15-employeeService/deploy.bat b/examples/Chapter3/15-employeeService/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter3/15-employeeService/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter3/15-employeeService/etc/persistence/META-INF/persistence.xml b/examples/Chapter3/15-employeeService/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..e3b740c --- /dev/null +++ b/examples/Chapter3/15-employeeService/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/EmpServDB_ch3 + + + + + + \ No newline at end of file diff --git a/examples/Chapter3/15-employeeService/etc/sql/db.sql b/examples/Chapter3/15-employeeService/etc/sql/db.sql new file mode 100644 index 0000000..e35905b --- /dev/null +++ b/examples/Chapter3/15-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/15-employeeService/etc/web/WEB-INF/web.xml b/examples/Chapter3/15-employeeService/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..9eebc68 --- /dev/null +++ b/examples/Chapter3/15-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/15-employeeService/src/model/examples/model/Employee.java b/examples/Chapter3/15-employeeService/src/model/examples/model/Employee.java new file mode 100644 index 0000000..40615dd --- /dev/null +++ b/examples/Chapter3/15-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/15-employeeService/src/model/examples/stateless/EmployeeService.java b/examples/Chapter3/15-employeeService/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..0b84488 --- /dev/null +++ b/examples/Chapter3/15-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 void removeEmployee(int id); + public Employee changeEmployeeSalary(int id, long newSalary); + public Employee findEmployee(int id); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter3/15-employeeService/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter3/15-employeeService/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..b3579a6 --- /dev/null +++ b/examples/Chapter3/15-employeeService/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,58 @@ +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 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(); + } +} diff --git a/examples/Chapter3/15-employeeService/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter3/15-employeeService/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..fe173be --- /dev/null +++ b/examples/Chapter3/15-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"); + service.removeEmployee(parseInt(id)); + out.println("Removed Employee with id: " + id); + } 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/15-employeeService/undeploy.bat b/examples/Chapter3/15-employeeService/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter3/15-employeeService/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/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..2e5bd0a --- /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..b9b6293 --- /dev/null +++ b/examples/Chapter4/01-fieldAccess/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +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..4ebbc8d --- /dev/null +++ b/examples/Chapter4/01-fieldAccess/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/fieldAccess + + + + + + \ 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..7298c35 --- /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 demonstates 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..00674ea --- /dev/null +++ b/examples/Chapter4/01-fieldAccess/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/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..0ba1599 --- /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..b9b6293 --- /dev/null +++ b/examples/Chapter4/02-propertyAccess/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +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..66250e3 --- /dev/null +++ b/examples/Chapter4/02-propertyAccess/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/propertyAccess + + + + + + \ 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..dd3cb4d --- /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 demonstates 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..00674ea --- /dev/null +++ b/examples/Chapter4/02-propertyAccess/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter4/03-customTableSchema/build.xml b/examples/Chapter4/03-customTableSchema/build.xml new file mode 100644 index 0000000..7085090 --- /dev/null +++ b/examples/Chapter4/03-customTableSchema/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/03-customTableSchema/deploy.bat b/examples/Chapter4/03-customTableSchema/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter4/03-customTableSchema/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter4/03-customTableSchema/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/03-customTableSchema/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..65d64d6 --- /dev/null +++ b/examples/Chapter4/03-customTableSchema/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/customTableSchema + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/03-customTableSchema/etc/sql/db.sql b/examples/Chapter4/03-customTableSchema/etc/sql/db.sql new file mode 100644 index 0000000..552b016 --- /dev/null +++ b/examples/Chapter4/03-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/03-customTableSchema/etc/web/WEB-INF/web.xml b/examples/Chapter4/03-customTableSchema/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/03-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/03-customTableSchema/src/model/examples/model/Employee.java b/examples/Chapter4/03-customTableSchema/src/model/examples/model/Employee.java new file mode 100644 index 0000000..2b514c5 --- /dev/null +++ b/examples/Chapter4/03-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/03-customTableSchema/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/03-customTableSchema/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..1707ef2 --- /dev/null +++ b/examples/Chapter4/03-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/03-customTableSchema/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/03-customTableSchema/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..0815bdf --- /dev/null +++ b/examples/Chapter4/03-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/03-customTableSchema/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/03-customTableSchema/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..11517a2 --- /dev/null +++ b/examples/Chapter4/03-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 demonstates 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/03-customTableSchema/undeploy.bat b/examples/Chapter4/03-customTableSchema/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter4/03-customTableSchema/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter4/04-customColumnMapping/build.xml b/examples/Chapter4/04-customColumnMapping/build.xml new file mode 100644 index 0000000..52f4701 --- /dev/null +++ b/examples/Chapter4/04-customColumnMapping/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/04-customColumnMapping/deploy.bat b/examples/Chapter4/04-customColumnMapping/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter4/04-customColumnMapping/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter4/04-customColumnMapping/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/04-customColumnMapping/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..0becdd9 --- /dev/null +++ b/examples/Chapter4/04-customColumnMapping/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/customColumnMapping + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/04-customColumnMapping/etc/sql/db.sql b/examples/Chapter4/04-customColumnMapping/etc/sql/db.sql new file mode 100644 index 0000000..bfe6b57 --- /dev/null +++ b/examples/Chapter4/04-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/04-customColumnMapping/etc/web/WEB-INF/web.xml b/examples/Chapter4/04-customColumnMapping/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/04-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/04-customColumnMapping/src/model/examples/model/Employee.java b/examples/Chapter4/04-customColumnMapping/src/model/examples/model/Employee.java new file mode 100644 index 0000000..bb2331f --- /dev/null +++ b/examples/Chapter4/04-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/04-customColumnMapping/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/04-customColumnMapping/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..85900ed --- /dev/null +++ b/examples/Chapter4/04-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/04-customColumnMapping/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/04-customColumnMapping/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..fe2483d --- /dev/null +++ b/examples/Chapter4/04-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/04-customColumnMapping/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/04-customColumnMapping/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..0300957 --- /dev/null +++ b/examples/Chapter4/04-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 demonstates 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/04-customColumnMapping/undeploy.bat b/examples/Chapter4/04-customColumnMapping/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter4/04-customColumnMapping/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter4/05-lobMapping/build.xml b/examples/Chapter4/05-lobMapping/build.xml new file mode 100644 index 0000000..42a0264 --- /dev/null +++ b/examples/Chapter4/05-lobMapping/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/05-lobMapping/deploy.bat b/examples/Chapter4/05-lobMapping/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter4/05-lobMapping/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter4/05-lobMapping/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/05-lobMapping/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..f9d5cd6 --- /dev/null +++ b/examples/Chapter4/05-lobMapping/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/lobMapping + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/05-lobMapping/etc/sql/db.sql b/examples/Chapter4/05-lobMapping/etc/sql/db.sql new file mode 100644 index 0000000..53b0112 --- /dev/null +++ b/examples/Chapter4/05-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/05-lobMapping/etc/web/WEB-INF/web.xml b/examples/Chapter4/05-lobMapping/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/05-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/05-lobMapping/src/model/examples/model/Employee.java b/examples/Chapter4/05-lobMapping/src/model/examples/model/Employee.java new file mode 100644 index 0000000..1e37e0d --- /dev/null +++ b/examples/Chapter4/05-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/05-lobMapping/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/05-lobMapping/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..381f445 --- /dev/null +++ b/examples/Chapter4/05-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/05-lobMapping/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/05-lobMapping/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..57477df --- /dev/null +++ b/examples/Chapter4/05-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/05-lobMapping/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/05-lobMapping/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..64aab75 --- /dev/null +++ b/examples/Chapter4/05-lobMapping/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,114 @@ +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 demonstates 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, although this feature is not currently" + + "supported by TopLink Essentials"; + + + // 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/05-lobMapping/undeploy.bat b/examples/Chapter4/05-lobMapping/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter4/05-lobMapping/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter4/06-enumMapping/build.xml b/examples/Chapter4/06-enumMapping/build.xml new file mode 100644 index 0000000..73b6a65 --- /dev/null +++ b/examples/Chapter4/06-enumMapping/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/06-enumMapping/deploy.bat b/examples/Chapter4/06-enumMapping/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter4/06-enumMapping/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter4/06-enumMapping/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/06-enumMapping/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..3955064 --- /dev/null +++ b/examples/Chapter4/06-enumMapping/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/enumMapping + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/06-enumMapping/etc/sql/db.sql b/examples/Chapter4/06-enumMapping/etc/sql/db.sql new file mode 100644 index 0000000..3f0c1a9 --- /dev/null +++ b/examples/Chapter4/06-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/06-enumMapping/etc/web/WEB-INF/web.xml b/examples/Chapter4/06-enumMapping/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/06-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/06-enumMapping/src/model/examples/model/Employee.java b/examples/Chapter4/06-enumMapping/src/model/examples/model/Employee.java new file mode 100644 index 0000000..4362ae3 --- /dev/null +++ b/examples/Chapter4/06-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/06-enumMapping/src/model/examples/model/EmployeeType.java b/examples/Chapter4/06-enumMapping/src/model/examples/model/EmployeeType.java new file mode 100644 index 0000000..6fab5b2 --- /dev/null +++ b/examples/Chapter4/06-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/06-enumMapping/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/06-enumMapping/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..d5ed61c --- /dev/null +++ b/examples/Chapter4/06-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/06-enumMapping/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/06-enumMapping/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..195f5c1 --- /dev/null +++ b/examples/Chapter4/06-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/06-enumMapping/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/06-enumMapping/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..5802b54 --- /dev/null +++ b/examples/Chapter4/06-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 demonstates 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/06-enumMapping/undeploy.bat b/examples/Chapter4/06-enumMapping/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter4/06-enumMapping/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter4/07-temporalMapping/build.xml b/examples/Chapter4/07-temporalMapping/build.xml new file mode 100644 index 0000000..0e9bd28 --- /dev/null +++ b/examples/Chapter4/07-temporalMapping/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/07-temporalMapping/deploy.bat b/examples/Chapter4/07-temporalMapping/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter4/07-temporalMapping/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter4/07-temporalMapping/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/07-temporalMapping/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..0b0751d --- /dev/null +++ b/examples/Chapter4/07-temporalMapping/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/temporalMapping + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/07-temporalMapping/etc/sql/db.sql b/examples/Chapter4/07-temporalMapping/etc/sql/db.sql new file mode 100644 index 0000000..c4d8b70 --- /dev/null +++ b/examples/Chapter4/07-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/07-temporalMapping/etc/web/WEB-INF/web.xml b/examples/Chapter4/07-temporalMapping/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/07-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/07-temporalMapping/src/model/examples/model/Employee.java b/examples/Chapter4/07-temporalMapping/src/model/examples/model/Employee.java new file mode 100644 index 0000000..d52e503 --- /dev/null +++ b/examples/Chapter4/07-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/07-temporalMapping/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/07-temporalMapping/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..f36fdf0 --- /dev/null +++ b/examples/Chapter4/07-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/07-temporalMapping/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/07-temporalMapping/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..0c2c796 --- /dev/null +++ b/examples/Chapter4/07-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/07-temporalMapping/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/07-temporalMapping/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..2c22490 --- /dev/null +++ b/examples/Chapter4/07-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/07-temporalMapping/undeploy.bat b/examples/Chapter4/07-temporalMapping/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter4/07-temporalMapping/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter4/08-transientMapping/build.xml b/examples/Chapter4/08-transientMapping/build.xml new file mode 100644 index 0000000..f7556da --- /dev/null +++ b/examples/Chapter4/08-transientMapping/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/08-transientMapping/deploy.bat b/examples/Chapter4/08-transientMapping/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter4/08-transientMapping/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter4/08-transientMapping/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/08-transientMapping/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..4a93ff9 --- /dev/null +++ b/examples/Chapter4/08-transientMapping/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/transientMapping + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/08-transientMapping/etc/sql/db.sql b/examples/Chapter4/08-transientMapping/etc/sql/db.sql new file mode 100644 index 0000000..e35905b --- /dev/null +++ b/examples/Chapter4/08-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/08-transientMapping/etc/web/WEB-INF/web.xml b/examples/Chapter4/08-transientMapping/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/08-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/08-transientMapping/src/model/EmpResources.java b/examples/Chapter4/08-transientMapping/src/model/EmpResources.java new file mode 100644 index 0000000..8ffeeb9 --- /dev/null +++ b/examples/Chapter4/08-transientMapping/src/model/EmpResources.java @@ -0,0 +1,9 @@ + +import java.util.ListResourceBundle; + +public class EmpResources extends ListResourceBundle { + + protected Object[][] getContents() { + return new Object[][] {{"Employee", "Localized Employee!"}}; + } +} diff --git a/examples/Chapter4/08-transientMapping/src/model/examples/model/Employee.java b/examples/Chapter4/08-transientMapping/src/model/examples/model/Employee.java new file mode 100644 index 0000000..1bb3498 --- /dev/null +++ b/examples/Chapter4/08-transientMapping/src/model/examples/model/Employee.java @@ -0,0 +1,47 @@ +package examples.model; + +import java.util.ResourceBundle; + +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Employee { + @Id + private int id; + private String name; + private long salary; + transient private String translatedName; + + 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() { + if (translatedName == null) { + translatedName = + ResourceBundle.getBundle("EmpResources").getString("Employee"); + } + return translatedName + " id: " + getId() + " name: " + getName() + " salary: " + getSalary(); + } +} diff --git a/examples/Chapter4/08-transientMapping/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/08-transientMapping/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..1707ef2 --- /dev/null +++ b/examples/Chapter4/08-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/08-transientMapping/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/08-transientMapping/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..0815bdf --- /dev/null +++ b/examples/Chapter4/08-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/08-transientMapping/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/08-transientMapping/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..2f57ab5 --- /dev/null +++ b/examples/Chapter4/08-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/08-transientMapping/undeploy.bat b/examples/Chapter4/08-transientMapping/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter4/08-transientMapping/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter4/09-autoIdGeneration/build.xml b/examples/Chapter4/09-autoIdGeneration/build.xml new file mode 100644 index 0000000..051689e --- /dev/null +++ b/examples/Chapter4/09-autoIdGeneration/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/09-autoIdGeneration/deploy.bat b/examples/Chapter4/09-autoIdGeneration/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter4/09-autoIdGeneration/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter4/09-autoIdGeneration/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/09-autoIdGeneration/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..31635f4 --- /dev/null +++ b/examples/Chapter4/09-autoIdGeneration/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/autoIdGeneration + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/09-autoIdGeneration/etc/sql/db.sql b/examples/Chapter4/09-autoIdGeneration/etc/sql/db.sql new file mode 100644 index 0000000..4d41c4b --- /dev/null +++ b/examples/Chapter4/09-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/09-autoIdGeneration/etc/web/WEB-INF/web.xml b/examples/Chapter4/09-autoIdGeneration/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/09-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/09-autoIdGeneration/src/model/examples/model/Employee.java b/examples/Chapter4/09-autoIdGeneration/src/model/examples/model/Employee.java new file mode 100644 index 0000000..8d50e3c --- /dev/null +++ b/examples/Chapter4/09-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/09-autoIdGeneration/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/09-autoIdGeneration/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..824af91 --- /dev/null +++ b/examples/Chapter4/09-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/09-autoIdGeneration/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/09-autoIdGeneration/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..e98e2fe --- /dev/null +++ b/examples/Chapter4/09-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/09-autoIdGeneration/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/09-autoIdGeneration/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..fec98aa --- /dev/null +++ b/examples/Chapter4/09-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/09-autoIdGeneration/undeploy.bat b/examples/Chapter4/09-autoIdGeneration/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter4/09-autoIdGeneration/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter4/10-tableIdGeneration/build.xml b/examples/Chapter4/10-tableIdGeneration/build.xml new file mode 100644 index 0000000..a76832c --- /dev/null +++ b/examples/Chapter4/10-tableIdGeneration/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/10-tableIdGeneration/deploy.bat b/examples/Chapter4/10-tableIdGeneration/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter4/10-tableIdGeneration/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter4/10-tableIdGeneration/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/10-tableIdGeneration/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..668f6ac --- /dev/null +++ b/examples/Chapter4/10-tableIdGeneration/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/tableIdGeneration + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/10-tableIdGeneration/etc/sql/db.sql b/examples/Chapter4/10-tableIdGeneration/etc/sql/db.sql new file mode 100644 index 0000000..ba52474 --- /dev/null +++ b/examples/Chapter4/10-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/10-tableIdGeneration/etc/web/WEB-INF/web.xml b/examples/Chapter4/10-tableIdGeneration/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/10-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/10-tableIdGeneration/src/model/examples/model/Address.java b/examples/Chapter4/10-tableIdGeneration/src/model/examples/model/Address.java new file mode 100644 index 0000000..a7651d7 --- /dev/null +++ b/examples/Chapter4/10-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/10-tableIdGeneration/src/model/examples/model/Employee.java b/examples/Chapter4/10-tableIdGeneration/src/model/examples/model/Employee.java new file mode 100644 index 0000000..aad9d2a --- /dev/null +++ b/examples/Chapter4/10-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/10-tableIdGeneration/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/10-tableIdGeneration/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..4002008 --- /dev/null +++ b/examples/Chapter4/10-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/10-tableIdGeneration/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/10-tableIdGeneration/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..94b67a0 --- /dev/null +++ b/examples/Chapter4/10-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/10-tableIdGeneration/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/10-tableIdGeneration/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..c0d837a --- /dev/null +++ b/examples/Chapter4/10-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/10-tableIdGeneration/undeploy.bat b/examples/Chapter4/10-tableIdGeneration/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter4/10-tableIdGeneration/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter4/11-sequenceIdGeneration/build.xml b/examples/Chapter4/11-sequenceIdGeneration/build.xml new file mode 100644 index 0000000..bb75fa2 --- /dev/null +++ b/examples/Chapter4/11-sequenceIdGeneration/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/11-sequenceIdGeneration/deploy.bat b/examples/Chapter4/11-sequenceIdGeneration/deploy.bat new file mode 100644 index 0000000..bf6879b --- /dev/null +++ b/examples/Chapter4/11-sequenceIdGeneration/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant -v + +pause \ No newline at end of file diff --git a/examples/Chapter4/11-sequenceIdGeneration/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/11-sequenceIdGeneration/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..6241bd9 --- /dev/null +++ b/examples/Chapter4/11-sequenceIdGeneration/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/sequenceIdGeneration + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/11-sequenceIdGeneration/etc/sql/db.sql b/examples/Chapter4/11-sequenceIdGeneration/etc/sql/db.sql new file mode 100644 index 0000000..9b497a3 --- /dev/null +++ b/examples/Chapter4/11-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/11-sequenceIdGeneration/etc/web/WEB-INF/web.xml b/examples/Chapter4/11-sequenceIdGeneration/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/11-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/11-sequenceIdGeneration/src/model/examples/model/Employee.java b/examples/Chapter4/11-sequenceIdGeneration/src/model/examples/model/Employee.java new file mode 100644 index 0000000..a133194 --- /dev/null +++ b/examples/Chapter4/11-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/11-sequenceIdGeneration/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/11-sequenceIdGeneration/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..824af91 --- /dev/null +++ b/examples/Chapter4/11-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/11-sequenceIdGeneration/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/11-sequenceIdGeneration/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..e98e2fe --- /dev/null +++ b/examples/Chapter4/11-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/11-sequenceIdGeneration/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/11-sequenceIdGeneration/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..2a8efac --- /dev/null +++ b/examples/Chapter4/11-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/11-sequenceIdGeneration/undeploy.bat b/examples/Chapter4/11-sequenceIdGeneration/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter4/11-sequenceIdGeneration/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter4/12-dbIdentityIdGeneration/build.xml b/examples/Chapter4/12-dbIdentityIdGeneration/build.xml new file mode 100644 index 0000000..db063e0 --- /dev/null +++ b/examples/Chapter4/12-dbIdentityIdGeneration/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/12-dbIdentityIdGeneration/deploy.bat b/examples/Chapter4/12-dbIdentityIdGeneration/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter4/12-dbIdentityIdGeneration/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter4/12-dbIdentityIdGeneration/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/12-dbIdentityIdGeneration/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..6f98705 --- /dev/null +++ b/examples/Chapter4/12-dbIdentityIdGeneration/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/dbIdentityIdGeneration + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/12-dbIdentityIdGeneration/etc/sql/db.sql b/examples/Chapter4/12-dbIdentityIdGeneration/etc/sql/db.sql new file mode 100644 index 0000000..1fb6e32 --- /dev/null +++ b/examples/Chapter4/12-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/12-dbIdentityIdGeneration/etc/web/WEB-INF/web.xml b/examples/Chapter4/12-dbIdentityIdGeneration/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/12-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/12-dbIdentityIdGeneration/src/model/examples/model/Employee.java b/examples/Chapter4/12-dbIdentityIdGeneration/src/model/examples/model/Employee.java new file mode 100644 index 0000000..41de4d1 --- /dev/null +++ b/examples/Chapter4/12-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/12-dbIdentityIdGeneration/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/12-dbIdentityIdGeneration/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..824af91 --- /dev/null +++ b/examples/Chapter4/12-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/12-dbIdentityIdGeneration/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/12-dbIdentityIdGeneration/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..e98e2fe --- /dev/null +++ b/examples/Chapter4/12-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/12-dbIdentityIdGeneration/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/12-dbIdentityIdGeneration/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..b2ff9ce --- /dev/null +++ b/examples/Chapter4/12-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/12-dbIdentityIdGeneration/undeploy.bat b/examples/Chapter4/12-dbIdentityIdGeneration/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter4/12-dbIdentityIdGeneration/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter4/13-manyToOne/build.xml b/examples/Chapter4/13-manyToOne/build.xml new file mode 100644 index 0000000..9fa11d4 --- /dev/null +++ b/examples/Chapter4/13-manyToOne/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/13-manyToOne/deploy.bat b/examples/Chapter4/13-manyToOne/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter4/13-manyToOne/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter4/13-manyToOne/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/13-manyToOne/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..0904dd9 --- /dev/null +++ b/examples/Chapter4/13-manyToOne/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/manyToOne + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/13-manyToOne/etc/sql/db.sql b/examples/Chapter4/13-manyToOne/etc/sql/db.sql new file mode 100644 index 0000000..5b2112b --- /dev/null +++ b/examples/Chapter4/13-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/13-manyToOne/etc/web/WEB-INF/web.xml b/examples/Chapter4/13-manyToOne/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/13-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/13-manyToOne/src/model/examples/model/Department.java b/examples/Chapter4/13-manyToOne/src/model/examples/model/Department.java new file mode 100644 index 0000000..42e0787 --- /dev/null +++ b/examples/Chapter4/13-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/13-manyToOne/src/model/examples/model/Employee.java b/examples/Chapter4/13-manyToOne/src/model/examples/model/Employee.java new file mode 100644 index 0000000..e161138 --- /dev/null +++ b/examples/Chapter4/13-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/13-manyToOne/src/model/examples/stateless/DepartmentService.java b/examples/Chapter4/13-manyToOne/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..7003e8d --- /dev/null +++ b/examples/Chapter4/13-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/13-manyToOne/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter4/13-manyToOne/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..7d47cb1 --- /dev/null +++ b/examples/Chapter4/13-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/13-manyToOne/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/13-manyToOne/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..84116f6 --- /dev/null +++ b/examples/Chapter4/13-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/13-manyToOne/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/13-manyToOne/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..b678784 --- /dev/null +++ b/examples/Chapter4/13-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/13-manyToOne/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/13-manyToOne/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..c1c0854 --- /dev/null +++ b/examples/Chapter4/13-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/13-manyToOne/undeploy.bat b/examples/Chapter4/13-manyToOne/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter4/13-manyToOne/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter4/14-joinColumn/build.xml b/examples/Chapter4/14-joinColumn/build.xml new file mode 100644 index 0000000..ee11a54 --- /dev/null +++ b/examples/Chapter4/14-joinColumn/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/14-joinColumn/deploy.bat b/examples/Chapter4/14-joinColumn/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter4/14-joinColumn/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter4/14-joinColumn/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/14-joinColumn/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..3c99b32 --- /dev/null +++ b/examples/Chapter4/14-joinColumn/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/joinColumn + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/14-joinColumn/etc/sql/db.sql b/examples/Chapter4/14-joinColumn/etc/sql/db.sql new file mode 100644 index 0000000..d58340d --- /dev/null +++ b/examples/Chapter4/14-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/14-joinColumn/etc/web/WEB-INF/web.xml b/examples/Chapter4/14-joinColumn/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/14-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/14-joinColumn/src/model/examples/model/Department.java b/examples/Chapter4/14-joinColumn/src/model/examples/model/Department.java new file mode 100644 index 0000000..42e0787 --- /dev/null +++ b/examples/Chapter4/14-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/14-joinColumn/src/model/examples/model/Employee.java b/examples/Chapter4/14-joinColumn/src/model/examples/model/Employee.java new file mode 100644 index 0000000..e40fb71 --- /dev/null +++ b/examples/Chapter4/14-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/14-joinColumn/src/model/examples/stateless/DepartmentService.java b/examples/Chapter4/14-joinColumn/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..7003e8d --- /dev/null +++ b/examples/Chapter4/14-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/14-joinColumn/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter4/14-joinColumn/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..7d47cb1 --- /dev/null +++ b/examples/Chapter4/14-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/14-joinColumn/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/14-joinColumn/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..84116f6 --- /dev/null +++ b/examples/Chapter4/14-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/14-joinColumn/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/14-joinColumn/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..b678784 --- /dev/null +++ b/examples/Chapter4/14-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/14-joinColumn/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/14-joinColumn/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..426b374 --- /dev/null +++ b/examples/Chapter4/14-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/14-joinColumn/undeploy.bat b/examples/Chapter4/14-joinColumn/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter4/14-joinColumn/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter4/15-oneToOneUnidirectional/build.xml b/examples/Chapter4/15-oneToOneUnidirectional/build.xml new file mode 100644 index 0000000..7ca127c --- /dev/null +++ b/examples/Chapter4/15-oneToOneUnidirectional/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/15-oneToOneUnidirectional/deploy.bat b/examples/Chapter4/15-oneToOneUnidirectional/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter4/15-oneToOneUnidirectional/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter4/15-oneToOneUnidirectional/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/15-oneToOneUnidirectional/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..0a0a834 --- /dev/null +++ b/examples/Chapter4/15-oneToOneUnidirectional/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/oneToOneUnidirectional + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/15-oneToOneUnidirectional/etc/sql/db.sql b/examples/Chapter4/15-oneToOneUnidirectional/etc/sql/db.sql new file mode 100644 index 0000000..c617acd --- /dev/null +++ b/examples/Chapter4/15-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/15-oneToOneUnidirectional/etc/web/WEB-INF/web.xml b/examples/Chapter4/15-oneToOneUnidirectional/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/15-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/15-oneToOneUnidirectional/src/model/examples/model/Employee.java b/examples/Chapter4/15-oneToOneUnidirectional/src/model/examples/model/Employee.java new file mode 100644 index 0000000..57e0ff1 --- /dev/null +++ b/examples/Chapter4/15-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/15-oneToOneUnidirectional/src/model/examples/model/ParkingSpace.java b/examples/Chapter4/15-oneToOneUnidirectional/src/model/examples/model/ParkingSpace.java new file mode 100644 index 0000000..d9fff74 --- /dev/null +++ b/examples/Chapter4/15-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/15-oneToOneUnidirectional/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/15-oneToOneUnidirectional/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..4768f09 --- /dev/null +++ b/examples/Chapter4/15-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/15-oneToOneUnidirectional/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/15-oneToOneUnidirectional/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..678d876 --- /dev/null +++ b/examples/Chapter4/15-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/15-oneToOneUnidirectional/src/model/examples/stateless/ParkingSpaceService.java b/examples/Chapter4/15-oneToOneUnidirectional/src/model/examples/stateless/ParkingSpaceService.java new file mode 100644 index 0000000..cb201cf --- /dev/null +++ b/examples/Chapter4/15-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/15-oneToOneUnidirectional/src/model/examples/stateless/ParkingSpaceServiceBean.java b/examples/Chapter4/15-oneToOneUnidirectional/src/model/examples/stateless/ParkingSpaceServiceBean.java new file mode 100644 index 0000000..4c1bf24 --- /dev/null +++ b/examples/Chapter4/15-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/15-oneToOneUnidirectional/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/15-oneToOneUnidirectional/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..fb48110 --- /dev/null +++ b/examples/Chapter4/15-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/15-oneToOneUnidirectional/undeploy.bat b/examples/Chapter4/15-oneToOneUnidirectional/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter4/15-oneToOneUnidirectional/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter4/16-oneToOneBidirectional/build.xml b/examples/Chapter4/16-oneToOneBidirectional/build.xml new file mode 100644 index 0000000..e60d7ca --- /dev/null +++ b/examples/Chapter4/16-oneToOneBidirectional/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/16-oneToOneBidirectional/deploy.bat b/examples/Chapter4/16-oneToOneBidirectional/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter4/16-oneToOneBidirectional/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter4/16-oneToOneBidirectional/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/16-oneToOneBidirectional/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..f3daa4d --- /dev/null +++ b/examples/Chapter4/16-oneToOneBidirectional/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/oneToOneBidirectional + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/16-oneToOneBidirectional/etc/sql/db.sql b/examples/Chapter4/16-oneToOneBidirectional/etc/sql/db.sql new file mode 100644 index 0000000..80a6acd --- /dev/null +++ b/examples/Chapter4/16-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/16-oneToOneBidirectional/etc/web/WEB-INF/web.xml b/examples/Chapter4/16-oneToOneBidirectional/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/16-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/16-oneToOneBidirectional/src/model/examples/model/Employee.java b/examples/Chapter4/16-oneToOneBidirectional/src/model/examples/model/Employee.java new file mode 100644 index 0000000..57e0ff1 --- /dev/null +++ b/examples/Chapter4/16-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/16-oneToOneBidirectional/src/model/examples/model/ParkingSpace.java b/examples/Chapter4/16-oneToOneBidirectional/src/model/examples/model/ParkingSpace.java new file mode 100644 index 0000000..cbf9690 --- /dev/null +++ b/examples/Chapter4/16-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/16-oneToOneBidirectional/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/16-oneToOneBidirectional/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..4768f09 --- /dev/null +++ b/examples/Chapter4/16-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/16-oneToOneBidirectional/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/16-oneToOneBidirectional/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..ab7df24 --- /dev/null +++ b/examples/Chapter4/16-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/16-oneToOneBidirectional/src/model/examples/stateless/ParkingSpaceService.java b/examples/Chapter4/16-oneToOneBidirectional/src/model/examples/stateless/ParkingSpaceService.java new file mode 100644 index 0000000..cb201cf --- /dev/null +++ b/examples/Chapter4/16-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/16-oneToOneBidirectional/src/model/examples/stateless/ParkingSpaceServiceBean.java b/examples/Chapter4/16-oneToOneBidirectional/src/model/examples/stateless/ParkingSpaceServiceBean.java new file mode 100644 index 0000000..4c1bf24 --- /dev/null +++ b/examples/Chapter4/16-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/16-oneToOneBidirectional/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/16-oneToOneBidirectional/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..d8064aa --- /dev/null +++ b/examples/Chapter4/16-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/16-oneToOneBidirectional/undeploy.bat b/examples/Chapter4/16-oneToOneBidirectional/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter4/16-oneToOneBidirectional/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter4/17-oneToOnePkMapping/build.xml b/examples/Chapter4/17-oneToOnePkMapping/build.xml new file mode 100644 index 0000000..5f91195 --- /dev/null +++ b/examples/Chapter4/17-oneToOnePkMapping/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/17-oneToOnePkMapping/deploy.bat b/examples/Chapter4/17-oneToOnePkMapping/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter4/17-oneToOnePkMapping/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter4/17-oneToOnePkMapping/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/17-oneToOnePkMapping/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..0acdea4 --- /dev/null +++ b/examples/Chapter4/17-oneToOnePkMapping/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/oneToOnePkMapping + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/17-oneToOnePkMapping/etc/sql/db.sql b/examples/Chapter4/17-oneToOnePkMapping/etc/sql/db.sql new file mode 100644 index 0000000..b2ebcb0 --- /dev/null +++ b/examples/Chapter4/17-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/17-oneToOnePkMapping/etc/web/WEB-INF/web.xml b/examples/Chapter4/17-oneToOnePkMapping/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/17-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/17-oneToOnePkMapping/src/model/examples/model/Employee.java b/examples/Chapter4/17-oneToOnePkMapping/src/model/examples/model/Employee.java new file mode 100644 index 0000000..c1d6162 --- /dev/null +++ b/examples/Chapter4/17-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/17-oneToOnePkMapping/src/model/examples/model/ParkingSpace.java b/examples/Chapter4/17-oneToOnePkMapping/src/model/examples/model/ParkingSpace.java new file mode 100644 index 0000000..809c60f --- /dev/null +++ b/examples/Chapter4/17-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/17-oneToOnePkMapping/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/17-oneToOnePkMapping/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..1707ef2 --- /dev/null +++ b/examples/Chapter4/17-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/17-oneToOnePkMapping/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/17-oneToOnePkMapping/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..0815bdf --- /dev/null +++ b/examples/Chapter4/17-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/17-oneToOnePkMapping/src/model/examples/stateless/ParkingSpaceService.java b/examples/Chapter4/17-oneToOnePkMapping/src/model/examples/stateless/ParkingSpaceService.java new file mode 100644 index 0000000..50d6a76 --- /dev/null +++ b/examples/Chapter4/17-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/17-oneToOnePkMapping/src/model/examples/stateless/ParkingSpaceServiceBean.java b/examples/Chapter4/17-oneToOnePkMapping/src/model/examples/stateless/ParkingSpaceServiceBean.java new file mode 100644 index 0000000..f9a9702 --- /dev/null +++ b/examples/Chapter4/17-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/17-oneToOnePkMapping/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/17-oneToOnePkMapping/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..3efd561 --- /dev/null +++ b/examples/Chapter4/17-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/17-oneToOnePkMapping/undeploy.bat b/examples/Chapter4/17-oneToOnePkMapping/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter4/17-oneToOnePkMapping/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter4/18-oneToManyBidirectional/build.xml b/examples/Chapter4/18-oneToManyBidirectional/build.xml new file mode 100644 index 0000000..e105b01 --- /dev/null +++ b/examples/Chapter4/18-oneToManyBidirectional/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/18-oneToManyBidirectional/deploy.bat b/examples/Chapter4/18-oneToManyBidirectional/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter4/18-oneToManyBidirectional/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter4/18-oneToManyBidirectional/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/18-oneToManyBidirectional/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..671725b --- /dev/null +++ b/examples/Chapter4/18-oneToManyBidirectional/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/oneToManyBidirectional + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/18-oneToManyBidirectional/etc/sql/db.sql b/examples/Chapter4/18-oneToManyBidirectional/etc/sql/db.sql new file mode 100644 index 0000000..5b2112b --- /dev/null +++ b/examples/Chapter4/18-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/18-oneToManyBidirectional/etc/web/WEB-INF/web.xml b/examples/Chapter4/18-oneToManyBidirectional/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/18-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/18-oneToManyBidirectional/src/model/examples/model/Department.java b/examples/Chapter4/18-oneToManyBidirectional/src/model/examples/model/Department.java new file mode 100644 index 0000000..78d7b9b --- /dev/null +++ b/examples/Chapter4/18-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/18-oneToManyBidirectional/src/model/examples/model/Employee.java b/examples/Chapter4/18-oneToManyBidirectional/src/model/examples/model/Employee.java new file mode 100644 index 0000000..e161138 --- /dev/null +++ b/examples/Chapter4/18-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/18-oneToManyBidirectional/src/model/examples/stateless/DepartmentService.java b/examples/Chapter4/18-oneToManyBidirectional/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..7003e8d --- /dev/null +++ b/examples/Chapter4/18-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/18-oneToManyBidirectional/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter4/18-oneToManyBidirectional/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..7d47cb1 --- /dev/null +++ b/examples/Chapter4/18-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/18-oneToManyBidirectional/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/18-oneToManyBidirectional/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..84116f6 --- /dev/null +++ b/examples/Chapter4/18-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/18-oneToManyBidirectional/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/18-oneToManyBidirectional/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..3a28921 --- /dev/null +++ b/examples/Chapter4/18-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/18-oneToManyBidirectional/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/18-oneToManyBidirectional/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..ade70d6 --- /dev/null +++ b/examples/Chapter4/18-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/18-oneToManyBidirectional/undeploy.bat b/examples/Chapter4/18-oneToManyBidirectional/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter4/18-oneToManyBidirectional/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter4/19-oneToManyTargetEntity/build.xml b/examples/Chapter4/19-oneToManyTargetEntity/build.xml new file mode 100644 index 0000000..cd73c09 --- /dev/null +++ b/examples/Chapter4/19-oneToManyTargetEntity/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/19-oneToManyTargetEntity/deploy.bat b/examples/Chapter4/19-oneToManyTargetEntity/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter4/19-oneToManyTargetEntity/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter4/19-oneToManyTargetEntity/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/19-oneToManyTargetEntity/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..c17bd34 --- /dev/null +++ b/examples/Chapter4/19-oneToManyTargetEntity/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/oneToManyTargetEntity + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/19-oneToManyTargetEntity/etc/sql/db.sql b/examples/Chapter4/19-oneToManyTargetEntity/etc/sql/db.sql new file mode 100644 index 0000000..5b2112b --- /dev/null +++ b/examples/Chapter4/19-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/19-oneToManyTargetEntity/etc/web/WEB-INF/web.xml b/examples/Chapter4/19-oneToManyTargetEntity/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/19-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/19-oneToManyTargetEntity/src/model/examples/model/Department.java b/examples/Chapter4/19-oneToManyTargetEntity/src/model/examples/model/Department.java new file mode 100644 index 0000000..6b96a87 --- /dev/null +++ b/examples/Chapter4/19-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/19-oneToManyTargetEntity/src/model/examples/model/Employee.java b/examples/Chapter4/19-oneToManyTargetEntity/src/model/examples/model/Employee.java new file mode 100644 index 0000000..e161138 --- /dev/null +++ b/examples/Chapter4/19-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/19-oneToManyTargetEntity/src/model/examples/stateless/DepartmentService.java b/examples/Chapter4/19-oneToManyTargetEntity/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..7003e8d --- /dev/null +++ b/examples/Chapter4/19-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/19-oneToManyTargetEntity/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter4/19-oneToManyTargetEntity/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..7d47cb1 --- /dev/null +++ b/examples/Chapter4/19-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/19-oneToManyTargetEntity/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/19-oneToManyTargetEntity/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..84116f6 --- /dev/null +++ b/examples/Chapter4/19-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/19-oneToManyTargetEntity/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/19-oneToManyTargetEntity/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..3a28921 --- /dev/null +++ b/examples/Chapter4/19-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/19-oneToManyTargetEntity/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/19-oneToManyTargetEntity/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..2a967af --- /dev/null +++ b/examples/Chapter4/19-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/19-oneToManyTargetEntity/undeploy.bat b/examples/Chapter4/19-oneToManyTargetEntity/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter4/19-oneToManyTargetEntity/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter4/20-manyToManyBidirectional/build.xml b/examples/Chapter4/20-manyToManyBidirectional/build.xml new file mode 100644 index 0000000..e2d4669 --- /dev/null +++ b/examples/Chapter4/20-manyToManyBidirectional/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/20-manyToManyBidirectional/deploy.bat b/examples/Chapter4/20-manyToManyBidirectional/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter4/20-manyToManyBidirectional/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter4/20-manyToManyBidirectional/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/20-manyToManyBidirectional/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..d4865e0 --- /dev/null +++ b/examples/Chapter4/20-manyToManyBidirectional/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/manyToManyBidirectional + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/20-manyToManyBidirectional/etc/sql/db.sql b/examples/Chapter4/20-manyToManyBidirectional/etc/sql/db.sql new file mode 100644 index 0000000..a762ecb --- /dev/null +++ b/examples/Chapter4/20-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/20-manyToManyBidirectional/etc/web/WEB-INF/web.xml b/examples/Chapter4/20-manyToManyBidirectional/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/20-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/20-manyToManyBidirectional/src/model/examples/model/Employee.java b/examples/Chapter4/20-manyToManyBidirectional/src/model/examples/model/Employee.java new file mode 100644 index 0000000..6c8f8e2 --- /dev/null +++ b/examples/Chapter4/20-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/20-manyToManyBidirectional/src/model/examples/model/Project.java b/examples/Chapter4/20-manyToManyBidirectional/src/model/examples/model/Project.java new file mode 100644 index 0000000..56635d0 --- /dev/null +++ b/examples/Chapter4/20-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/20-manyToManyBidirectional/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/20-manyToManyBidirectional/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..0922f7a --- /dev/null +++ b/examples/Chapter4/20-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/20-manyToManyBidirectional/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/20-manyToManyBidirectional/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..a8dcc0c --- /dev/null +++ b/examples/Chapter4/20-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/20-manyToManyBidirectional/src/model/examples/stateless/ProjectService.java b/examples/Chapter4/20-manyToManyBidirectional/src/model/examples/stateless/ProjectService.java new file mode 100644 index 0000000..5ef7dbc --- /dev/null +++ b/examples/Chapter4/20-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/20-manyToManyBidirectional/src/model/examples/stateless/ProjectServiceBean.java b/examples/Chapter4/20-manyToManyBidirectional/src/model/examples/stateless/ProjectServiceBean.java new file mode 100644 index 0000000..40d80c4 --- /dev/null +++ b/examples/Chapter4/20-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/20-manyToManyBidirectional/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/20-manyToManyBidirectional/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..6c1d936 --- /dev/null +++ b/examples/Chapter4/20-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/20-manyToManyBidirectional/undeploy.bat b/examples/Chapter4/20-manyToManyBidirectional/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter4/20-manyToManyBidirectional/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter4/21-manyToManyJoinTable/build.xml b/examples/Chapter4/21-manyToManyJoinTable/build.xml new file mode 100644 index 0000000..0f0218f --- /dev/null +++ b/examples/Chapter4/21-manyToManyJoinTable/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/21-manyToManyJoinTable/deploy.bat b/examples/Chapter4/21-manyToManyJoinTable/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter4/21-manyToManyJoinTable/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter4/21-manyToManyJoinTable/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/21-manyToManyJoinTable/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..6da43af --- /dev/null +++ b/examples/Chapter4/21-manyToManyJoinTable/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/manyToManyJoinTable + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/21-manyToManyJoinTable/etc/sql/db.sql b/examples/Chapter4/21-manyToManyJoinTable/etc/sql/db.sql new file mode 100644 index 0000000..2f536ce --- /dev/null +++ b/examples/Chapter4/21-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/21-manyToManyJoinTable/etc/web/WEB-INF/web.xml b/examples/Chapter4/21-manyToManyJoinTable/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/21-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/21-manyToManyJoinTable/src/model/examples/model/Employee.java b/examples/Chapter4/21-manyToManyJoinTable/src/model/examples/model/Employee.java new file mode 100644 index 0000000..995c52f --- /dev/null +++ b/examples/Chapter4/21-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/21-manyToManyJoinTable/src/model/examples/model/Project.java b/examples/Chapter4/21-manyToManyJoinTable/src/model/examples/model/Project.java new file mode 100644 index 0000000..56635d0 --- /dev/null +++ b/examples/Chapter4/21-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/21-manyToManyJoinTable/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/21-manyToManyJoinTable/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..0922f7a --- /dev/null +++ b/examples/Chapter4/21-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/21-manyToManyJoinTable/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/21-manyToManyJoinTable/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..a8dcc0c --- /dev/null +++ b/examples/Chapter4/21-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/21-manyToManyJoinTable/src/model/examples/stateless/ProjectService.java b/examples/Chapter4/21-manyToManyJoinTable/src/model/examples/stateless/ProjectService.java new file mode 100644 index 0000000..5ef7dbc --- /dev/null +++ b/examples/Chapter4/21-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/21-manyToManyJoinTable/src/model/examples/stateless/ProjectServiceBean.java b/examples/Chapter4/21-manyToManyJoinTable/src/model/examples/stateless/ProjectServiceBean.java new file mode 100644 index 0000000..40d80c4 --- /dev/null +++ b/examples/Chapter4/21-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/21-manyToManyJoinTable/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/21-manyToManyJoinTable/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..b6236aa --- /dev/null +++ b/examples/Chapter4/21-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/21-manyToManyJoinTable/undeploy.bat b/examples/Chapter4/21-manyToManyJoinTable/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter4/21-manyToManyJoinTable/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter4/22-oneToManyUnidirectional/build.xml b/examples/Chapter4/22-oneToManyUnidirectional/build.xml new file mode 100644 index 0000000..be519f4 --- /dev/null +++ b/examples/Chapter4/22-oneToManyUnidirectional/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/22-oneToManyUnidirectional/deploy.bat b/examples/Chapter4/22-oneToManyUnidirectional/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter4/22-oneToManyUnidirectional/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter4/22-oneToManyUnidirectional/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/22-oneToManyUnidirectional/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..2ca70a2 --- /dev/null +++ b/examples/Chapter4/22-oneToManyUnidirectional/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/oneToManyUnidirectional + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/22-oneToManyUnidirectional/etc/sql/db.sql b/examples/Chapter4/22-oneToManyUnidirectional/etc/sql/db.sql new file mode 100644 index 0000000..fe2e575 --- /dev/null +++ b/examples/Chapter4/22-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/22-oneToManyUnidirectional/etc/web/WEB-INF/web.xml b/examples/Chapter4/22-oneToManyUnidirectional/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/22-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/22-oneToManyUnidirectional/src/model/examples/model/Employee.java b/examples/Chapter4/22-oneToManyUnidirectional/src/model/examples/model/Employee.java new file mode 100644 index 0000000..30a7238 --- /dev/null +++ b/examples/Chapter4/22-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/22-oneToManyUnidirectional/src/model/examples/model/Phone.java b/examples/Chapter4/22-oneToManyUnidirectional/src/model/examples/model/Phone.java new file mode 100644 index 0000000..343cd07 --- /dev/null +++ b/examples/Chapter4/22-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/22-oneToManyUnidirectional/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/22-oneToManyUnidirectional/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..ee66ad9 --- /dev/null +++ b/examples/Chapter4/22-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/22-oneToManyUnidirectional/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/22-oneToManyUnidirectional/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..c803d82 --- /dev/null +++ b/examples/Chapter4/22-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/22-oneToManyUnidirectional/src/model/examples/stateless/PhoneService.java b/examples/Chapter4/22-oneToManyUnidirectional/src/model/examples/stateless/PhoneService.java new file mode 100644 index 0000000..447675b --- /dev/null +++ b/examples/Chapter4/22-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/22-oneToManyUnidirectional/src/model/examples/stateless/PhoneServiceBean.java b/examples/Chapter4/22-oneToManyUnidirectional/src/model/examples/stateless/PhoneServiceBean.java new file mode 100644 index 0000000..e12ef2f --- /dev/null +++ b/examples/Chapter4/22-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/22-oneToManyUnidirectional/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/22-oneToManyUnidirectional/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..eaf0fe6 --- /dev/null +++ b/examples/Chapter4/22-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/22-oneToManyUnidirectional/undeploy.bat b/examples/Chapter4/22-oneToManyUnidirectional/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter4/22-oneToManyUnidirectional/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter4/23-oneToManyList/build.xml b/examples/Chapter4/23-oneToManyList/build.xml new file mode 100644 index 0000000..2185f27 --- /dev/null +++ b/examples/Chapter4/23-oneToManyList/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/23-oneToManyList/deploy.bat b/examples/Chapter4/23-oneToManyList/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter4/23-oneToManyList/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter4/23-oneToManyList/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/23-oneToManyList/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..67ce0f1 --- /dev/null +++ b/examples/Chapter4/23-oneToManyList/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/oneToManyList + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/23-oneToManyList/etc/sql/db.sql b/examples/Chapter4/23-oneToManyList/etc/sql/db.sql new file mode 100644 index 0000000..5b2112b --- /dev/null +++ b/examples/Chapter4/23-oneToManyList/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/23-oneToManyList/etc/web/WEB-INF/web.xml b/examples/Chapter4/23-oneToManyList/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/23-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/Chapter4/23-oneToManyList/src/model/examples/model/Department.java b/examples/Chapter4/23-oneToManyList/src/model/examples/model/Department.java new file mode 100644 index 0000000..8ebb9d4 --- /dev/null +++ b/examples/Chapter4/23-oneToManyList/src/model/examples/model/Department.java @@ -0,0 +1,61 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; +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) { + 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/23-oneToManyList/src/model/examples/model/Employee.java b/examples/Chapter4/23-oneToManyList/src/model/examples/model/Employee.java new file mode 100644 index 0000000..e161138 --- /dev/null +++ b/examples/Chapter4/23-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/Chapter4/23-oneToManyList/src/model/examples/stateless/DepartmentService.java b/examples/Chapter4/23-oneToManyList/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..7003e8d --- /dev/null +++ b/examples/Chapter4/23-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/Chapter4/23-oneToManyList/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter4/23-oneToManyList/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..7d47cb1 --- /dev/null +++ b/examples/Chapter4/23-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/Chapter4/23-oneToManyList/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/23-oneToManyList/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..84116f6 --- /dev/null +++ b/examples/Chapter4/23-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/Chapter4/23-oneToManyList/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/23-oneToManyList/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..3a28921 --- /dev/null +++ b/examples/Chapter4/23-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/Chapter4/23-oneToManyList/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/23-oneToManyList/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..ed08708 --- /dev/null +++ b/examples/Chapter4/23-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 4: One-to-Many List Example"; + + private final String DESCRIPTION = + "This example demonstates how to specify a List 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 " + 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/Chapter4/23-oneToManyList/undeploy.bat b/examples/Chapter4/23-oneToManyList/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter4/23-oneToManyList/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter4/24-oneToManyMap/build.xml b/examples/Chapter4/24-oneToManyMap/build.xml new file mode 100644 index 0000000..e100580 --- /dev/null +++ b/examples/Chapter4/24-oneToManyMap/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/24-oneToManyMap/deploy.bat b/examples/Chapter4/24-oneToManyMap/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter4/24-oneToManyMap/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter4/24-oneToManyMap/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/24-oneToManyMap/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..c74336a --- /dev/null +++ b/examples/Chapter4/24-oneToManyMap/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/oneToManyMap + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/24-oneToManyMap/etc/sql/db.sql b/examples/Chapter4/24-oneToManyMap/etc/sql/db.sql new file mode 100644 index 0000000..5b2112b --- /dev/null +++ b/examples/Chapter4/24-oneToManyMap/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/24-oneToManyMap/etc/web/WEB-INF/web.xml b/examples/Chapter4/24-oneToManyMap/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/24-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/Chapter4/24-oneToManyMap/src/model/examples/model/Department.java b/examples/Chapter4/24-oneToManyMap/src/model/examples/model/Department.java new file mode 100644 index 0000000..efaf32e --- /dev/null +++ b/examples/Chapter4/24-oneToManyMap/src/model/examples/model/Department.java @@ -0,0 +1,60 @@ +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(mappedBy="department") + @MapKey(name="name") + 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) { + if (!getEmployees().containsKey(employee.getName())) { + getEmployees().put(employee.getName(), employee); + if (employee.getDepartment() != null) { + employee.getDepartment().getEmployees().remove(employee.getName()); + } + employee.setDepartment(this); + } + } + + public Map getEmployees() { + return employees; + } + + public String toString() { + return "Department id: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter4/24-oneToManyMap/src/model/examples/model/Employee.java b/examples/Chapter4/24-oneToManyMap/src/model/examples/model/Employee.java new file mode 100644 index 0000000..e161138 --- /dev/null +++ b/examples/Chapter4/24-oneToManyMap/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/24-oneToManyMap/src/model/examples/stateless/DepartmentService.java b/examples/Chapter4/24-oneToManyMap/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..7003e8d --- /dev/null +++ b/examples/Chapter4/24-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/Chapter4/24-oneToManyMap/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter4/24-oneToManyMap/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..7d47cb1 --- /dev/null +++ b/examples/Chapter4/24-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/Chapter4/24-oneToManyMap/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/24-oneToManyMap/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..84116f6 --- /dev/null +++ b/examples/Chapter4/24-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, int deptId); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter4/24-oneToManyMap/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/24-oneToManyMap/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..73510ca --- /dev/null +++ b/examples/Chapter4/24-oneToManyMap/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.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); + 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/24-oneToManyMap/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/24-oneToManyMap/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..2ed618a --- /dev/null +++ b/examples/Chapter4/24-oneToManyMap/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: One-to-Many Map Example"; + + private final String DESCRIPTION = + "This example demonstates how to specify a Map 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 " + 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/Chapter4/24-oneToManyMap/undeploy.bat b/examples/Chapter4/24-oneToManyMap/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter4/24-oneToManyMap/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter4/25-oneToOneLazy/build.xml b/examples/Chapter4/25-oneToOneLazy/build.xml new file mode 100644 index 0000000..ae89e08 --- /dev/null +++ b/examples/Chapter4/25-oneToOneLazy/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter4/25-oneToOneLazy/deploy.bat b/examples/Chapter4/25-oneToOneLazy/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter4/25-oneToOneLazy/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter4/25-oneToOneLazy/etc/persistence/META-INF/persistence.xml b/examples/Chapter4/25-oneToOneLazy/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..60b0ab3 --- /dev/null +++ b/examples/Chapter4/25-oneToOneLazy/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/oneToOneLazy + + + + + + \ No newline at end of file diff --git a/examples/Chapter4/25-oneToOneLazy/etc/sql/db.sql b/examples/Chapter4/25-oneToOneLazy/etc/sql/db.sql new file mode 100644 index 0000000..90a6791 --- /dev/null +++ b/examples/Chapter4/25-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/25-oneToOneLazy/etc/web/WEB-INF/web.xml b/examples/Chapter4/25-oneToOneLazy/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter4/25-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/25-oneToOneLazy/src/model/examples/model/Employee.java b/examples/Chapter4/25-oneToOneLazy/src/model/examples/model/Employee.java new file mode 100644 index 0000000..cff90fe --- /dev/null +++ b/examples/Chapter4/25-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/25-oneToOneLazy/src/model/examples/model/ParkingSpace.java b/examples/Chapter4/25-oneToOneLazy/src/model/examples/model/ParkingSpace.java new file mode 100644 index 0000000..d9fff74 --- /dev/null +++ b/examples/Chapter4/25-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/25-oneToOneLazy/src/model/examples/stateless/EmployeeService.java b/examples/Chapter4/25-oneToOneLazy/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..4768f09 --- /dev/null +++ b/examples/Chapter4/25-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/25-oneToOneLazy/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter4/25-oneToOneLazy/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..678d876 --- /dev/null +++ b/examples/Chapter4/25-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/25-oneToOneLazy/src/model/examples/stateless/ParkingSpaceService.java b/examples/Chapter4/25-oneToOneLazy/src/model/examples/stateless/ParkingSpaceService.java new file mode 100644 index 0000000..cb201cf --- /dev/null +++ b/examples/Chapter4/25-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/25-oneToOneLazy/src/model/examples/stateless/ParkingSpaceServiceBean.java b/examples/Chapter4/25-oneToOneLazy/src/model/examples/stateless/ParkingSpaceServiceBean.java new file mode 100644 index 0000000..4c1bf24 --- /dev/null +++ b/examples/Chapter4/25-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/25-oneToOneLazy/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter4/25-oneToOneLazy/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..728ce4b --- /dev/null +++ b/examples/Chapter4/25-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/25-oneToOneLazy/undeploy.bat b/examples/Chapter4/25-oneToOneLazy/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter4/25-oneToOneLazy/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/01-txScopedEmExample/build.xml b/examples/Chapter5/01-txScopedEmExample/build.xml new file mode 100644 index 0000000..f8d0b97 --- /dev/null +++ b/examples/Chapter5/01-txScopedEmExample/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/01-txScopedEmExample/deploy.bat b/examples/Chapter5/01-txScopedEmExample/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter5/01-txScopedEmExample/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/01-txScopedEmExample/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/01-txScopedEmExample/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..893b4d7 --- /dev/null +++ b/examples/Chapter5/01-txScopedEmExample/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/txScopedEmExample + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/01-txScopedEmExample/etc/sql/db.sql b/examples/Chapter5/01-txScopedEmExample/etc/sql/db.sql new file mode 100644 index 0000000..3cd19ae --- /dev/null +++ b/examples/Chapter5/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/Chapter5/01-txScopedEmExample/etc/web/WEB-INF/web.xml b/examples/Chapter5/01-txScopedEmExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/01-txScopedEmExample/src/model/examples/model/Employee.java b/examples/Chapter5/01-txScopedEmExample/src/model/examples/model/Employee.java new file mode 100644 index 0000000..e94ea3e --- /dev/null +++ b/examples/Chapter5/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/Chapter5/01-txScopedEmExample/src/model/examples/model/Project.java b/examples/Chapter5/01-txScopedEmExample/src/model/examples/model/Project.java new file mode 100644 index 0000000..8226327 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/01-txScopedEmExample/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/01-txScopedEmExample/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..938e90d --- /dev/null +++ b/examples/Chapter5/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/Chapter5/01-txScopedEmExample/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/01-txScopedEmExample/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..adb12c0 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/01-txScopedEmExample/src/model/examples/stateless/ProjectService.java b/examples/Chapter5/01-txScopedEmExample/src/model/examples/stateless/ProjectService.java new file mode 100644 index 0000000..24e37e1 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/01-txScopedEmExample/src/model/examples/stateless/ProjectServiceBean.java b/examples/Chapter5/01-txScopedEmExample/src/model/examples/stateless/ProjectServiceBean.java new file mode 100644 index 0000000..aa8a648 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/01-txScopedEmExample/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter5/01-txScopedEmExample/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..9e38388 --- /dev/null +++ b/examples/Chapter5/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 5: 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/Chapter5/01-txScopedEmExample/undeploy.bat b/examples/Chapter5/01-txScopedEmExample/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter5/01-txScopedEmExample/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/02-extendedEmExample1/build.xml b/examples/Chapter5/02-extendedEmExample1/build.xml new file mode 100644 index 0000000..c1ef15b --- /dev/null +++ b/examples/Chapter5/02-extendedEmExample1/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/02-extendedEmExample1/deploy.bat b/examples/Chapter5/02-extendedEmExample1/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter5/02-extendedEmExample1/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/02-extendedEmExample1/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/02-extendedEmExample1/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..31209aa --- /dev/null +++ b/examples/Chapter5/02-extendedEmExample1/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/extendedEmExample + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/02-extendedEmExample1/etc/sql/db.sql b/examples/Chapter5/02-extendedEmExample1/etc/sql/db.sql new file mode 100644 index 0000000..88a74b3 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/02-extendedEmExample1/etc/web/WEB-INF/web.xml b/examples/Chapter5/02-extendedEmExample1/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/02-extendedEmExample1/src/model/examples/model/Department.java b/examples/Chapter5/02-extendedEmExample1/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter5/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/Chapter5/02-extendedEmExample1/src/model/examples/model/Employee.java b/examples/Chapter5/02-extendedEmExample1/src/model/examples/model/Employee.java new file mode 100644 index 0000000..b4ce131 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/02-extendedEmExample1/src/model/examples/stateless/DepartmentManager.java b/examples/Chapter5/02-extendedEmExample1/src/model/examples/stateless/DepartmentManager.java new file mode 100644 index 0000000..6ff6396 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/02-extendedEmExample1/src/model/examples/stateless/DepartmentManagerBean.java b/examples/Chapter5/02-extendedEmExample1/src/model/examples/stateless/DepartmentManagerBean.java new file mode 100644 index 0000000..2ecaf1f --- /dev/null +++ b/examples/Chapter5/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/Chapter5/02-extendedEmExample1/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/02-extendedEmExample1/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..cc0558b --- /dev/null +++ b/examples/Chapter5/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/Chapter5/02-extendedEmExample1/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/02-extendedEmExample1/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..748e5a5 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/02-extendedEmExample1/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter5/02-extendedEmExample1/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..0c468ba --- /dev/null +++ b/examples/Chapter5/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 5: 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/Chapter5/02-extendedEmExample1/undeploy.bat b/examples/Chapter5/02-extendedEmExample1/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter5/02-extendedEmExample1/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/03-extendedEmExample2/build.xml b/examples/Chapter5/03-extendedEmExample2/build.xml new file mode 100644 index 0000000..7e633db --- /dev/null +++ b/examples/Chapter5/03-extendedEmExample2/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/03-extendedEmExample2/deploy.bat b/examples/Chapter5/03-extendedEmExample2/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter5/03-extendedEmExample2/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/03-extendedEmExample2/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/03-extendedEmExample2/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..1152ccf --- /dev/null +++ b/examples/Chapter5/03-extendedEmExample2/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/extendedEmExample2 + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/03-extendedEmExample2/etc/sql/db.sql b/examples/Chapter5/03-extendedEmExample2/etc/sql/db.sql new file mode 100644 index 0000000..88a74b3 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/03-extendedEmExample2/etc/web/WEB-INF/web.xml b/examples/Chapter5/03-extendedEmExample2/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/03-extendedEmExample2/src/model/examples/model/Department.java b/examples/Chapter5/03-extendedEmExample2/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter5/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/Chapter5/03-extendedEmExample2/src/model/examples/model/Employee.java b/examples/Chapter5/03-extendedEmExample2/src/model/examples/model/Employee.java new file mode 100644 index 0000000..b4ce131 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/03-extendedEmExample2/src/model/examples/stateless/DepartmentManager.java b/examples/Chapter5/03-extendedEmExample2/src/model/examples/stateless/DepartmentManager.java new file mode 100644 index 0000000..6ff6396 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/03-extendedEmExample2/src/model/examples/stateless/DepartmentManagerBean.java b/examples/Chapter5/03-extendedEmExample2/src/model/examples/stateless/DepartmentManagerBean.java new file mode 100644 index 0000000..f5d31f9 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/03-extendedEmExample2/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/03-extendedEmExample2/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..cc0558b --- /dev/null +++ b/examples/Chapter5/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/Chapter5/03-extendedEmExample2/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/03-extendedEmExample2/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..748e5a5 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/03-extendedEmExample2/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter5/03-extendedEmExample2/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..0500d56 --- /dev/null +++ b/examples/Chapter5/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 5: 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/Chapter5/03-extendedEmExample2/undeploy.bat b/examples/Chapter5/03-extendedEmExample2/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter5/03-extendedEmExample2/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/04-extendedEmExample3/build.xml b/examples/Chapter5/04-extendedEmExample3/build.xml new file mode 100644 index 0000000..48a0d55 --- /dev/null +++ b/examples/Chapter5/04-extendedEmExample3/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/04-extendedEmExample3/deploy.bat b/examples/Chapter5/04-extendedEmExample3/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter5/04-extendedEmExample3/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/04-extendedEmExample3/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/04-extendedEmExample3/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..611a55f --- /dev/null +++ b/examples/Chapter5/04-extendedEmExample3/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/extendedEmExample3 + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/04-extendedEmExample3/etc/sql/db.sql b/examples/Chapter5/04-extendedEmExample3/etc/sql/db.sql new file mode 100644 index 0000000..88a74b3 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/04-extendedEmExample3/etc/web/WEB-INF/web.xml b/examples/Chapter5/04-extendedEmExample3/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/04-extendedEmExample3/src/model/examples/model/Department.java b/examples/Chapter5/04-extendedEmExample3/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter5/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/Chapter5/04-extendedEmExample3/src/model/examples/model/Employee.java b/examples/Chapter5/04-extendedEmExample3/src/model/examples/model/Employee.java new file mode 100644 index 0000000..b4ce131 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/04-extendedEmExample3/src/model/examples/stateless/DepartmentManager.java b/examples/Chapter5/04-extendedEmExample3/src/model/examples/stateless/DepartmentManager.java new file mode 100644 index 0000000..6ff6396 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/04-extendedEmExample3/src/model/examples/stateless/DepartmentManagerBean.java b/examples/Chapter5/04-extendedEmExample3/src/model/examples/stateless/DepartmentManagerBean.java new file mode 100644 index 0000000..50021df --- /dev/null +++ b/examples/Chapter5/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/Chapter5/04-extendedEmExample3/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/04-extendedEmExample3/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..cc0558b --- /dev/null +++ b/examples/Chapter5/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/Chapter5/04-extendedEmExample3/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/04-extendedEmExample3/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..748e5a5 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/04-extendedEmExample3/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter5/04-extendedEmExample3/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..6f92562 --- /dev/null +++ b/examples/Chapter5/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 5: 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/Chapter5/04-extendedEmExample3/undeploy.bat b/examples/Chapter5/04-extendedEmExample3/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter5/04-extendedEmExample3/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/05-applicationManagedSE/build.xml b/examples/Chapter5/05-applicationManagedSE/build.xml new file mode 100644 index 0000000..4c28390 --- /dev/null +++ b/examples/Chapter5/05-applicationManagedSE/build.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/05-applicationManagedSE/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/05-applicationManagedSE/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..9ee692c --- /dev/null +++ b/examples/Chapter5/05-applicationManagedSE/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,13 @@ + + + examples.model.Employee + + + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/05-applicationManagedSE/etc/sql/db.sql b/examples/Chapter5/05-applicationManagedSE/etc/sql/db.sql new file mode 100644 index 0000000..c934828 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/05-applicationManagedSE/run.bat b/examples/Chapter5/05-applicationManagedSE/run.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter5/05-applicationManagedSE/run.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter5/05-applicationManagedSE/src/client/examples/client/EmployeeClient.java b/examples/Chapter5/05-applicationManagedSE/src/client/examples/client/EmployeeClient.java new file mode 100644 index 0000000..496296f --- /dev/null +++ b/examples/Chapter5/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/Chapter5/05-applicationManagedSE/src/model/examples/model/Employee.java b/examples/Chapter5/05-applicationManagedSE/src/model/examples/model/Employee.java new file mode 100644 index 0000000..40615dd --- /dev/null +++ b/examples/Chapter5/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/Chapter5/05-applicationManagedSE/src/model/examples/model/EmployeeService.java b/examples/Chapter5/05-applicationManagedSE/src/model/examples/model/EmployeeService.java new file mode 100644 index 0000000..9274f42 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/06-applicationManagedEE/build.xml b/examples/Chapter5/06-applicationManagedEE/build.xml new file mode 100644 index 0000000..8607147 --- /dev/null +++ b/examples/Chapter5/06-applicationManagedEE/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/06-applicationManagedEE/deploy.bat b/examples/Chapter5/06-applicationManagedEE/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter5/06-applicationManagedEE/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/06-applicationManagedEE/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/06-applicationManagedEE/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..0e4da70 --- /dev/null +++ b/examples/Chapter5/06-applicationManagedEE/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/applicationManagedEE + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/06-applicationManagedEE/etc/sql/db.sql b/examples/Chapter5/06-applicationManagedEE/etc/sql/db.sql new file mode 100644 index 0000000..1147049 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/06-applicationManagedEE/etc/web/WEB-INF/web.xml b/examples/Chapter5/06-applicationManagedEE/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..2922bb2 --- /dev/null +++ b/examples/Chapter5/06-applicationManagedEE/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/Chapter5/06-applicationManagedEE/src/model/examples/model/User.java b/examples/Chapter5/06-applicationManagedEE/src/model/examples/model/User.java new file mode 100644 index 0000000..ee47e87 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/06-applicationManagedEE/src/servlet/examples/servlet/LoginServlet.java b/examples/Chapter5/06-applicationManagedEE/src/servlet/examples/servlet/LoginServlet.java new file mode 100644 index 0000000..c6b4e97 --- /dev/null +++ b/examples/Chapter5/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 5: 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/Chapter5/06-applicationManagedEE/undeploy.bat b/examples/Chapter5/06-applicationManagedEE/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter5/06-applicationManagedEE/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/07-txScopedPersistenceContext/build.xml b/examples/Chapter5/07-txScopedPersistenceContext/build.xml new file mode 100644 index 0000000..713f3a1 --- /dev/null +++ b/examples/Chapter5/07-txScopedPersistenceContext/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/07-txScopedPersistenceContext/deploy.bat b/examples/Chapter5/07-txScopedPersistenceContext/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter5/07-txScopedPersistenceContext/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter5/07-txScopedPersistenceContext/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/07-txScopedPersistenceContext/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..d41f1ec --- /dev/null +++ b/examples/Chapter5/07-txScopedPersistenceContext/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/txScopedPersistenceContext + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/07-txScopedPersistenceContext/etc/sql/db.sql b/examples/Chapter5/07-txScopedPersistenceContext/etc/sql/db.sql new file mode 100644 index 0000000..ea842a6 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/07-txScopedPersistenceContext/etc/web/WEB-INF/web.xml b/examples/Chapter5/07-txScopedPersistenceContext/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter5/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/Chapter5/07-txScopedPersistenceContext/src/model/examples/model/Employee.java b/examples/Chapter5/07-txScopedPersistenceContext/src/model/examples/model/Employee.java new file mode 100644 index 0000000..337dab3 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/07-txScopedPersistenceContext/src/model/examples/model/LogRecord.java b/examples/Chapter5/07-txScopedPersistenceContext/src/model/examples/model/LogRecord.java new file mode 100644 index 0000000..ad1970f --- /dev/null +++ b/examples/Chapter5/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/Chapter5/07-txScopedPersistenceContext/src/model/examples/stateless/AuditService.java b/examples/Chapter5/07-txScopedPersistenceContext/src/model/examples/stateless/AuditService.java new file mode 100644 index 0000000..5b0fc2a --- /dev/null +++ b/examples/Chapter5/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/Chapter5/07-txScopedPersistenceContext/src/model/examples/stateless/AuditServiceBean.java b/examples/Chapter5/07-txScopedPersistenceContext/src/model/examples/stateless/AuditServiceBean.java new file mode 100644 index 0000000..575521d --- /dev/null +++ b/examples/Chapter5/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/Chapter5/07-txScopedPersistenceContext/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/07-txScopedPersistenceContext/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..9b8ef67 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/07-txScopedPersistenceContext/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/07-txScopedPersistenceContext/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..2ba9cd8 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/07-txScopedPersistenceContext/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter5/07-txScopedPersistenceContext/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..54f732c --- /dev/null +++ b/examples/Chapter5/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 5: 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/Chapter5/07-txScopedPersistenceContext/undeploy.bat b/examples/Chapter5/07-txScopedPersistenceContext/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter5/07-txScopedPersistenceContext/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/08-extendedPersistenceContext/build.xml b/examples/Chapter5/08-extendedPersistenceContext/build.xml new file mode 100644 index 0000000..37fd2b0 --- /dev/null +++ b/examples/Chapter5/08-extendedPersistenceContext/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/08-extendedPersistenceContext/deploy.bat b/examples/Chapter5/08-extendedPersistenceContext/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter5/08-extendedPersistenceContext/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/08-extendedPersistenceContext/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/08-extendedPersistenceContext/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..adc042e --- /dev/null +++ b/examples/Chapter5/08-extendedPersistenceContext/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/extendedPersistenceContext + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/08-extendedPersistenceContext/etc/sql/db.sql b/examples/Chapter5/08-extendedPersistenceContext/etc/sql/db.sql new file mode 100644 index 0000000..93114a2 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/08-extendedPersistenceContext/etc/web/WEB-INF/web.xml b/examples/Chapter5/08-extendedPersistenceContext/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/08-extendedPersistenceContext/src/model/examples/model/Department.java b/examples/Chapter5/08-extendedPersistenceContext/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter5/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/Chapter5/08-extendedPersistenceContext/src/model/examples/model/Employee.java b/examples/Chapter5/08-extendedPersistenceContext/src/model/examples/model/Employee.java new file mode 100644 index 0000000..b4ce131 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/08-extendedPersistenceContext/src/model/examples/model/LogRecord.java b/examples/Chapter5/08-extendedPersistenceContext/src/model/examples/model/LogRecord.java new file mode 100644 index 0000000..ad1970f --- /dev/null +++ b/examples/Chapter5/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/Chapter5/08-extendedPersistenceContext/src/model/examples/stateless/AuditService.java b/examples/Chapter5/08-extendedPersistenceContext/src/model/examples/stateless/AuditService.java new file mode 100644 index 0000000..c2ad1c0 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/08-extendedPersistenceContext/src/model/examples/stateless/AuditServiceBean.java b/examples/Chapter5/08-extendedPersistenceContext/src/model/examples/stateless/AuditServiceBean.java new file mode 100644 index 0000000..2fbabe1 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/08-extendedPersistenceContext/src/model/examples/stateless/DepartmentManager.java b/examples/Chapter5/08-extendedPersistenceContext/src/model/examples/stateless/DepartmentManager.java new file mode 100644 index 0000000..6ff6396 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/08-extendedPersistenceContext/src/model/examples/stateless/DepartmentManagerBean.java b/examples/Chapter5/08-extendedPersistenceContext/src/model/examples/stateless/DepartmentManagerBean.java new file mode 100644 index 0000000..cecaa3c --- /dev/null +++ b/examples/Chapter5/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/Chapter5/08-extendedPersistenceContext/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/08-extendedPersistenceContext/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..cc0558b --- /dev/null +++ b/examples/Chapter5/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/Chapter5/08-extendedPersistenceContext/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/08-extendedPersistenceContext/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..748e5a5 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/08-extendedPersistenceContext/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter5/08-extendedPersistenceContext/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..ea9005d --- /dev/null +++ b/examples/Chapter5/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 5: 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/Chapter5/08-extendedPersistenceContext/undeploy.bat b/examples/Chapter5/08-extendedPersistenceContext/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter5/08-extendedPersistenceContext/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/09-persistenceContextCollision/build.xml b/examples/Chapter5/09-persistenceContextCollision/build.xml new file mode 100644 index 0000000..9e207dd --- /dev/null +++ b/examples/Chapter5/09-persistenceContextCollision/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/09-persistenceContextCollision/deploy.bat b/examples/Chapter5/09-persistenceContextCollision/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter5/09-persistenceContextCollision/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/09-persistenceContextCollision/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/09-persistenceContextCollision/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..a3a1290 --- /dev/null +++ b/examples/Chapter5/09-persistenceContextCollision/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/persistenceContextCollision + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/09-persistenceContextCollision/etc/sql/db.sql b/examples/Chapter5/09-persistenceContextCollision/etc/sql/db.sql new file mode 100644 index 0000000..93114a2 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/09-persistenceContextCollision/etc/web/WEB-INF/web.xml b/examples/Chapter5/09-persistenceContextCollision/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/09-persistenceContextCollision/src/model/examples/model/Department.java b/examples/Chapter5/09-persistenceContextCollision/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter5/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/Chapter5/09-persistenceContextCollision/src/model/examples/model/Employee.java b/examples/Chapter5/09-persistenceContextCollision/src/model/examples/model/Employee.java new file mode 100644 index 0000000..b4ce131 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/09-persistenceContextCollision/src/model/examples/model/LogRecord.java b/examples/Chapter5/09-persistenceContextCollision/src/model/examples/model/LogRecord.java new file mode 100644 index 0000000..ad1970f --- /dev/null +++ b/examples/Chapter5/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/Chapter5/09-persistenceContextCollision/src/model/examples/stateless/AuditService.java b/examples/Chapter5/09-persistenceContextCollision/src/model/examples/stateless/AuditService.java new file mode 100644 index 0000000..c2ad1c0 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/09-persistenceContextCollision/src/model/examples/stateless/AuditServiceBean.java b/examples/Chapter5/09-persistenceContextCollision/src/model/examples/stateless/AuditServiceBean.java new file mode 100644 index 0000000..9169339 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/09-persistenceContextCollision/src/model/examples/stateless/DepartmentManager.java b/examples/Chapter5/09-persistenceContextCollision/src/model/examples/stateless/DepartmentManager.java new file mode 100644 index 0000000..185ee47 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/09-persistenceContextCollision/src/model/examples/stateless/DepartmentManagerBean.java b/examples/Chapter5/09-persistenceContextCollision/src/model/examples/stateless/DepartmentManagerBean.java new file mode 100644 index 0000000..dbc16df --- /dev/null +++ b/examples/Chapter5/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/Chapter5/09-persistenceContextCollision/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/09-persistenceContextCollision/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..cc0558b --- /dev/null +++ b/examples/Chapter5/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/Chapter5/09-persistenceContextCollision/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/09-persistenceContextCollision/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..748e5a5 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/09-persistenceContextCollision/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter5/09-persistenceContextCollision/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..ac6aa4a --- /dev/null +++ b/examples/Chapter5/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 5: 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/Chapter5/09-persistenceContextCollision/undeploy.bat b/examples/Chapter5/09-persistenceContextCollision/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter5/09-persistenceContextCollision/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/10-persistenceContextInheritance/build.xml b/examples/Chapter5/10-persistenceContextInheritance/build.xml new file mode 100644 index 0000000..76ec2ab --- /dev/null +++ b/examples/Chapter5/10-persistenceContextInheritance/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/10-persistenceContextInheritance/deploy.bat b/examples/Chapter5/10-persistenceContextInheritance/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter5/10-persistenceContextInheritance/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/10-persistenceContextInheritance/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/10-persistenceContextInheritance/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..5e21589 --- /dev/null +++ b/examples/Chapter5/10-persistenceContextInheritance/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/persistenceContextInheritance + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/10-persistenceContextInheritance/etc/sql/db.sql b/examples/Chapter5/10-persistenceContextInheritance/etc/sql/db.sql new file mode 100644 index 0000000..93114a2 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/10-persistenceContextInheritance/etc/web/WEB-INF/web.xml b/examples/Chapter5/10-persistenceContextInheritance/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/10-persistenceContextInheritance/src/model/examples/model/Department.java b/examples/Chapter5/10-persistenceContextInheritance/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter5/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/Chapter5/10-persistenceContextInheritance/src/model/examples/model/Employee.java b/examples/Chapter5/10-persistenceContextInheritance/src/model/examples/model/Employee.java new file mode 100644 index 0000000..b4ce131 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/10-persistenceContextInheritance/src/model/examples/model/LogRecord.java b/examples/Chapter5/10-persistenceContextInheritance/src/model/examples/model/LogRecord.java new file mode 100644 index 0000000..ad1970f --- /dev/null +++ b/examples/Chapter5/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/Chapter5/10-persistenceContextInheritance/src/model/examples/stateless/AuditService.java b/examples/Chapter5/10-persistenceContextInheritance/src/model/examples/stateless/AuditService.java new file mode 100644 index 0000000..c2ad1c0 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/10-persistenceContextInheritance/src/model/examples/stateless/AuditServiceBean.java b/examples/Chapter5/10-persistenceContextInheritance/src/model/examples/stateless/AuditServiceBean.java new file mode 100644 index 0000000..2fbabe1 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/10-persistenceContextInheritance/src/model/examples/stateless/DepartmentManager.java b/examples/Chapter5/10-persistenceContextInheritance/src/model/examples/stateless/DepartmentManager.java new file mode 100644 index 0000000..6ff6396 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/10-persistenceContextInheritance/src/model/examples/stateless/DepartmentManagerBean.java b/examples/Chapter5/10-persistenceContextInheritance/src/model/examples/stateless/DepartmentManagerBean.java new file mode 100644 index 0000000..4db6e6f --- /dev/null +++ b/examples/Chapter5/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/Chapter5/10-persistenceContextInheritance/src/model/examples/stateless/EmployeeManager.java b/examples/Chapter5/10-persistenceContextInheritance/src/model/examples/stateless/EmployeeManager.java new file mode 100644 index 0000000..34a1b21 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/10-persistenceContextInheritance/src/model/examples/stateless/EmployeeManagerBean.java b/examples/Chapter5/10-persistenceContextInheritance/src/model/examples/stateless/EmployeeManagerBean.java new file mode 100644 index 0000000..428a147 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/10-persistenceContextInheritance/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/10-persistenceContextInheritance/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..cc0558b --- /dev/null +++ b/examples/Chapter5/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/Chapter5/10-persistenceContextInheritance/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/10-persistenceContextInheritance/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..748e5a5 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/10-persistenceContextInheritance/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter5/10-persistenceContextInheritance/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..caec070 --- /dev/null +++ b/examples/Chapter5/10-persistenceContextInheritance/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 5: 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"); + 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/Chapter5/10-persistenceContextInheritance/undeploy.bat b/examples/Chapter5/10-persistenceContextInheritance/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter5/10-persistenceContextInheritance/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/11-applicationManagedJTA/build.xml b/examples/Chapter5/11-applicationManagedJTA/build.xml new file mode 100644 index 0000000..b0dde2a --- /dev/null +++ b/examples/Chapter5/11-applicationManagedJTA/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/11-applicationManagedJTA/deploy.bat b/examples/Chapter5/11-applicationManagedJTA/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter5/11-applicationManagedJTA/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/11-applicationManagedJTA/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/11-applicationManagedJTA/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..681a651 --- /dev/null +++ b/examples/Chapter5/11-applicationManagedJTA/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/applicationManagedJTA + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/11-applicationManagedJTA/etc/sql/db.sql b/examples/Chapter5/11-applicationManagedJTA/etc/sql/db.sql new file mode 100644 index 0000000..88a74b3 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/11-applicationManagedJTA/etc/web/WEB-INF/web.xml b/examples/Chapter5/11-applicationManagedJTA/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/11-applicationManagedJTA/src/model/examples/model/Department.java b/examples/Chapter5/11-applicationManagedJTA/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter5/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/Chapter5/11-applicationManagedJTA/src/model/examples/model/Employee.java b/examples/Chapter5/11-applicationManagedJTA/src/model/examples/model/Employee.java new file mode 100644 index 0000000..b4ce131 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/11-applicationManagedJTA/src/model/examples/stateless/DepartmentManager.java b/examples/Chapter5/11-applicationManagedJTA/src/model/examples/stateless/DepartmentManager.java new file mode 100644 index 0000000..6ff6396 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/11-applicationManagedJTA/src/model/examples/stateless/DepartmentManagerBean.java b/examples/Chapter5/11-applicationManagedJTA/src/model/examples/stateless/DepartmentManagerBean.java new file mode 100644 index 0000000..af6fa7e --- /dev/null +++ b/examples/Chapter5/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/Chapter5/11-applicationManagedJTA/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/11-applicationManagedJTA/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..cc0558b --- /dev/null +++ b/examples/Chapter5/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/Chapter5/11-applicationManagedJTA/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/11-applicationManagedJTA/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..748e5a5 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/11-applicationManagedJTA/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter5/11-applicationManagedJTA/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..e82b13c --- /dev/null +++ b/examples/Chapter5/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 5: 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/Chapter5/11-applicationManagedJTA/undeploy.bat b/examples/Chapter5/11-applicationManagedJTA/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter5/11-applicationManagedJTA/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/12-sharingApplicationManagedJTA/build.xml b/examples/Chapter5/12-sharingApplicationManagedJTA/build.xml new file mode 100644 index 0000000..a0cc332 --- /dev/null +++ b/examples/Chapter5/12-sharingApplicationManagedJTA/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/12-sharingApplicationManagedJTA/deploy.bat b/examples/Chapter5/12-sharingApplicationManagedJTA/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter5/12-sharingApplicationManagedJTA/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/12-sharingApplicationManagedJTA/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/12-sharingApplicationManagedJTA/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..71f82e5 --- /dev/null +++ b/examples/Chapter5/12-sharingApplicationManagedJTA/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/sharingApplicationManagedJTA + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/12-sharingApplicationManagedJTA/etc/sql/db.sql b/examples/Chapter5/12-sharingApplicationManagedJTA/etc/sql/db.sql new file mode 100644 index 0000000..b2b562d --- /dev/null +++ b/examples/Chapter5/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/Chapter5/12-sharingApplicationManagedJTA/etc/web/WEB-INF/web.xml b/examples/Chapter5/12-sharingApplicationManagedJTA/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5d96981 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/12-sharingApplicationManagedJTA/src/model/examples/model/Employee.java b/examples/Chapter5/12-sharingApplicationManagedJTA/src/model/examples/model/Employee.java new file mode 100644 index 0000000..40615dd --- /dev/null +++ b/examples/Chapter5/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/Chapter5/12-sharingApplicationManagedJTA/src/model/examples/model/EmployeeService.java b/examples/Chapter5/12-sharingApplicationManagedJTA/src/model/examples/model/EmployeeService.java new file mode 100644 index 0000000..9274f42 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/12-sharingApplicationManagedJTA/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter5/12-sharingApplicationManagedJTA/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..27d3c82 --- /dev/null +++ b/examples/Chapter5/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 5: 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/Chapter5/12-sharingApplicationManagedJTA/undeploy.bat b/examples/Chapter5/12-sharingApplicationManagedJTA/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter5/12-sharingApplicationManagedJTA/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/13-resourceLocalTxSE/build.xml b/examples/Chapter5/13-resourceLocalTxSE/build.xml new file mode 100644 index 0000000..eaae9c2 --- /dev/null +++ b/examples/Chapter5/13-resourceLocalTxSE/build.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/13-resourceLocalTxSE/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/13-resourceLocalTxSE/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..e76a686 --- /dev/null +++ b/examples/Chapter5/13-resourceLocalTxSE/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,13 @@ + + + examples.model.User + + + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/13-resourceLocalTxSE/etc/sql/db.sql b/examples/Chapter5/13-resourceLocalTxSE/etc/sql/db.sql new file mode 100644 index 0000000..e44a732 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/13-resourceLocalTxSE/run.bat b/examples/Chapter5/13-resourceLocalTxSE/run.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter5/13-resourceLocalTxSE/run.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter5/13-resourceLocalTxSE/src/client/examples/client/ExpirePasswords.java b/examples/Chapter5/13-resourceLocalTxSE/src/client/examples/client/ExpirePasswords.java new file mode 100644 index 0000000..dd52f33 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/13-resourceLocalTxSE/src/model/examples/model/User.java b/examples/Chapter5/13-resourceLocalTxSE/src/model/examples/model/User.java new file mode 100644 index 0000000..e56d669 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/14-resourceLocalTxEE/build.xml b/examples/Chapter5/14-resourceLocalTxEE/build.xml new file mode 100644 index 0000000..fd3ceb2 --- /dev/null +++ b/examples/Chapter5/14-resourceLocalTxEE/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/14-resourceLocalTxEE/deploy.bat b/examples/Chapter5/14-resourceLocalTxEE/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter5/14-resourceLocalTxEE/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/14-resourceLocalTxEE/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/14-resourceLocalTxEE/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..6eae2b3 --- /dev/null +++ b/examples/Chapter5/14-resourceLocalTxEE/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/resourceLocalTxEE + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/14-resourceLocalTxEE/etc/sql/db.sql b/examples/Chapter5/14-resourceLocalTxEE/etc/sql/db.sql new file mode 100644 index 0000000..e6b183e --- /dev/null +++ b/examples/Chapter5/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/Chapter5/14-resourceLocalTxEE/etc/web/WEB-INF/web.xml b/examples/Chapter5/14-resourceLocalTxEE/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..882291d --- /dev/null +++ b/examples/Chapter5/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/Chapter5/14-resourceLocalTxEE/src/model/examples/model/LogRecord.java b/examples/Chapter5/14-resourceLocalTxEE/src/model/examples/model/LogRecord.java new file mode 100644 index 0000000..ad1970f --- /dev/null +++ b/examples/Chapter5/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/Chapter5/14-resourceLocalTxEE/src/model/examples/stateless/LogService.java b/examples/Chapter5/14-resourceLocalTxEE/src/model/examples/stateless/LogService.java new file mode 100644 index 0000000..a137cf0 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/14-resourceLocalTxEE/src/model/examples/stateless/LogServiceBean.java b/examples/Chapter5/14-resourceLocalTxEE/src/model/examples/stateless/LogServiceBean.java new file mode 100644 index 0000000..8365249 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/14-resourceLocalTxEE/src/servlet/examples/servlet/LoggingServlet.java b/examples/Chapter5/14-resourceLocalTxEE/src/servlet/examples/servlet/LoggingServlet.java new file mode 100644 index 0000000..5e48eb1 --- /dev/null +++ b/examples/Chapter5/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 5: 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/Chapter5/14-resourceLocalTxEE/undeploy.bat b/examples/Chapter5/14-resourceLocalTxEE/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter5/14-resourceLocalTxEE/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/15-persistingWithRelationships/build.xml b/examples/Chapter5/15-persistingWithRelationships/build.xml new file mode 100644 index 0000000..00e338c --- /dev/null +++ b/examples/Chapter5/15-persistingWithRelationships/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/15-persistingWithRelationships/deploy.bat b/examples/Chapter5/15-persistingWithRelationships/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter5/15-persistingWithRelationships/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/15-persistingWithRelationships/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/15-persistingWithRelationships/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..9b1c40c --- /dev/null +++ b/examples/Chapter5/15-persistingWithRelationships/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/persistingWithRelationships + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/15-persistingWithRelationships/etc/sql/db.sql b/examples/Chapter5/15-persistingWithRelationships/etc/sql/db.sql new file mode 100644 index 0000000..f9b9756 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/15-persistingWithRelationships/etc/web/WEB-INF/web.xml b/examples/Chapter5/15-persistingWithRelationships/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/15-persistingWithRelationships/src/model/examples/model/Department.java b/examples/Chapter5/15-persistingWithRelationships/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter5/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/Chapter5/15-persistingWithRelationships/src/model/examples/model/Employee.java b/examples/Chapter5/15-persistingWithRelationships/src/model/examples/model/Employee.java new file mode 100644 index 0000000..3b074a5 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/15-persistingWithRelationships/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/15-persistingWithRelationships/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..208d7df --- /dev/null +++ b/examples/Chapter5/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/Chapter5/15-persistingWithRelationships/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/15-persistingWithRelationships/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..afbf2ef --- /dev/null +++ b/examples/Chapter5/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/Chapter5/15-persistingWithRelationships/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter5/15-persistingWithRelationships/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..9c7b6de --- /dev/null +++ b/examples/Chapter5/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 5: 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/Chapter5/15-persistingWithRelationships/undeploy.bat b/examples/Chapter5/15-persistingWithRelationships/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter5/15-persistingWithRelationships/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/16-persistingWithRelationshipsUsingGetReference/build.xml b/examples/Chapter5/16-persistingWithRelationshipsUsingGetReference/build.xml new file mode 100644 index 0000000..e5756c7 --- /dev/null +++ b/examples/Chapter5/16-persistingWithRelationshipsUsingGetReference/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/16-persistingWithRelationshipsUsingGetReference/deploy.bat b/examples/Chapter5/16-persistingWithRelationshipsUsingGetReference/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter5/16-persistingWithRelationshipsUsingGetReference/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/16-persistingWithRelationshipsUsingGetReference/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/16-persistingWithRelationshipsUsingGetReference/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..eefde7d --- /dev/null +++ b/examples/Chapter5/16-persistingWithRelationshipsUsingGetReference/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/persistingWithRelationshipsUsingGetReference + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/16-persistingWithRelationshipsUsingGetReference/etc/sql/db.sql b/examples/Chapter5/16-persistingWithRelationshipsUsingGetReference/etc/sql/db.sql new file mode 100644 index 0000000..f9b9756 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/16-persistingWithRelationshipsUsingGetReference/etc/web/WEB-INF/web.xml b/examples/Chapter5/16-persistingWithRelationshipsUsingGetReference/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/16-persistingWithRelationshipsUsingGetReference/src/model/examples/model/Department.java b/examples/Chapter5/16-persistingWithRelationshipsUsingGetReference/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter5/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/Chapter5/16-persistingWithRelationshipsUsingGetReference/src/model/examples/model/Employee.java b/examples/Chapter5/16-persistingWithRelationshipsUsingGetReference/src/model/examples/model/Employee.java new file mode 100644 index 0000000..3b074a5 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/16-persistingWithRelationshipsUsingGetReference/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/16-persistingWithRelationshipsUsingGetReference/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..208d7df --- /dev/null +++ b/examples/Chapter5/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/Chapter5/16-persistingWithRelationshipsUsingGetReference/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/16-persistingWithRelationshipsUsingGetReference/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..3b84d06 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/16-persistingWithRelationshipsUsingGetReference/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter5/16-persistingWithRelationshipsUsingGetReference/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..775332c --- /dev/null +++ b/examples/Chapter5/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 5: 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/Chapter5/16-persistingWithRelationshipsUsingGetReference/undeploy.bat b/examples/Chapter5/16-persistingWithRelationshipsUsingGetReference/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter5/16-persistingWithRelationshipsUsingGetReference/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/17-removingWithRelationships/build.xml b/examples/Chapter5/17-removingWithRelationships/build.xml new file mode 100644 index 0000000..769207e --- /dev/null +++ b/examples/Chapter5/17-removingWithRelationships/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/17-removingWithRelationships/deploy.bat b/examples/Chapter5/17-removingWithRelationships/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter5/17-removingWithRelationships/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/17-removingWithRelationships/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/17-removingWithRelationships/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..0fca578 --- /dev/null +++ b/examples/Chapter5/17-removingWithRelationships/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/removingWithRelationships + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/17-removingWithRelationships/etc/sql/db.sql b/examples/Chapter5/17-removingWithRelationships/etc/sql/db.sql new file mode 100644 index 0000000..ca6c7a8 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/17-removingWithRelationships/etc/web/WEB-INF/web.xml b/examples/Chapter5/17-removingWithRelationships/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/17-removingWithRelationships/src/model/examples/model/Employee.java b/examples/Chapter5/17-removingWithRelationships/src/model/examples/model/Employee.java new file mode 100644 index 0000000..70dda67 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/17-removingWithRelationships/src/model/examples/model/ParkingSpace.java b/examples/Chapter5/17-removingWithRelationships/src/model/examples/model/ParkingSpace.java new file mode 100644 index 0000000..77813c6 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/17-removingWithRelationships/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/17-removingWithRelationships/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..5e0c3ea --- /dev/null +++ b/examples/Chapter5/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/Chapter5/17-removingWithRelationships/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/17-removingWithRelationships/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..f4bea22 --- /dev/null +++ b/examples/Chapter5/17-removingWithRelationships/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,34 @@ +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 void removeParkingSpace(int empId) { + Employee emp = em.find(Employee.class, empId); + emp.setParkingSpace(null); + em.remove(emp.getParkingSpace()); + + } + + 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/Chapter5/17-removingWithRelationships/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter5/17-removingWithRelationships/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..5c4bcd6 --- /dev/null +++ b/examples/Chapter5/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 5: 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/Chapter5/17-removingWithRelationships/undeploy.bat b/examples/Chapter5/17-removingWithRelationships/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter5/17-removingWithRelationships/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/18-persistingWithRelationshipsCascade/build.xml b/examples/Chapter5/18-persistingWithRelationshipsCascade/build.xml new file mode 100644 index 0000000..fdb4937 --- /dev/null +++ b/examples/Chapter5/18-persistingWithRelationshipsCascade/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/18-persistingWithRelationshipsCascade/deploy.bat b/examples/Chapter5/18-persistingWithRelationshipsCascade/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter5/18-persistingWithRelationshipsCascade/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter5/18-persistingWithRelationshipsCascade/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/18-persistingWithRelationshipsCascade/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..5f3cd5a --- /dev/null +++ b/examples/Chapter5/18-persistingWithRelationshipsCascade/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/persistingWithRelationshipsCascade + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/18-persistingWithRelationshipsCascade/etc/sql/db.sql b/examples/Chapter5/18-persistingWithRelationshipsCascade/etc/sql/db.sql new file mode 100644 index 0000000..346085a --- /dev/null +++ b/examples/Chapter5/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/Chapter5/18-persistingWithRelationshipsCascade/etc/web/WEB-INF/web.xml b/examples/Chapter5/18-persistingWithRelationshipsCascade/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter5/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/Chapter5/18-persistingWithRelationshipsCascade/src/model/examples/model/Address.java b/examples/Chapter5/18-persistingWithRelationshipsCascade/src/model/examples/model/Address.java new file mode 100644 index 0000000..e18406b --- /dev/null +++ b/examples/Chapter5/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/Chapter5/18-persistingWithRelationshipsCascade/src/model/examples/model/Employee.java b/examples/Chapter5/18-persistingWithRelationshipsCascade/src/model/examples/model/Employee.java new file mode 100644 index 0000000..8c1c112 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/18-persistingWithRelationshipsCascade/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/18-persistingWithRelationshipsCascade/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..52d57fc --- /dev/null +++ b/examples/Chapter5/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/Chapter5/18-persistingWithRelationshipsCascade/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/18-persistingWithRelationshipsCascade/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..822d3c7 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/18-persistingWithRelationshipsCascade/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter5/18-persistingWithRelationshipsCascade/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..8a7f528 --- /dev/null +++ b/examples/Chapter5/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 4: 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/Chapter5/18-persistingWithRelationshipsCascade/undeploy.bat b/examples/Chapter5/18-persistingWithRelationshipsCascade/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter5/18-persistingWithRelationshipsCascade/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/19-removingWithRelationshipsCascade/build.xml b/examples/Chapter5/19-removingWithRelationshipsCascade/build.xml new file mode 100644 index 0000000..0080c4d --- /dev/null +++ b/examples/Chapter5/19-removingWithRelationshipsCascade/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/19-removingWithRelationshipsCascade/deploy.bat b/examples/Chapter5/19-removingWithRelationshipsCascade/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter5/19-removingWithRelationshipsCascade/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/19-removingWithRelationshipsCascade/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/19-removingWithRelationshipsCascade/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..dc0ae3d --- /dev/null +++ b/examples/Chapter5/19-removingWithRelationshipsCascade/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/removingWithRelationshipsCascade + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/19-removingWithRelationshipsCascade/etc/sql/db.sql b/examples/Chapter5/19-removingWithRelationshipsCascade/etc/sql/db.sql new file mode 100644 index 0000000..48d4c71 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/19-removingWithRelationshipsCascade/etc/web/WEB-INF/web.xml b/examples/Chapter5/19-removingWithRelationshipsCascade/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/19-removingWithRelationshipsCascade/src/model/examples/model/Employee.java b/examples/Chapter5/19-removingWithRelationshipsCascade/src/model/examples/model/Employee.java new file mode 100644 index 0000000..fcf42e1 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/19-removingWithRelationshipsCascade/src/model/examples/model/ParkingSpace.java b/examples/Chapter5/19-removingWithRelationshipsCascade/src/model/examples/model/ParkingSpace.java new file mode 100644 index 0000000..77813c6 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/19-removingWithRelationshipsCascade/src/model/examples/model/Phone.java b/examples/Chapter5/19-removingWithRelationshipsCascade/src/model/examples/model/Phone.java new file mode 100644 index 0000000..afa5419 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/19-removingWithRelationshipsCascade/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/19-removingWithRelationshipsCascade/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..2b74bfc --- /dev/null +++ b/examples/Chapter5/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/Chapter5/19-removingWithRelationshipsCascade/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/19-removingWithRelationshipsCascade/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..1d39dd2 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/19-removingWithRelationshipsCascade/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter5/19-removingWithRelationshipsCascade/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..c6629f4 --- /dev/null +++ b/examples/Chapter5/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 5: 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/Chapter5/19-removingWithRelationshipsCascade/undeploy.bat b/examples/Chapter5/19-removingWithRelationshipsCascade/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter5/19-removingWithRelationshipsCascade/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/20-mergingDetachedEntities/build.xml b/examples/Chapter5/20-mergingDetachedEntities/build.xml new file mode 100644 index 0000000..15d12f0 --- /dev/null +++ b/examples/Chapter5/20-mergingDetachedEntities/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/20-mergingDetachedEntities/deploy.bat b/examples/Chapter5/20-mergingDetachedEntities/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter5/20-mergingDetachedEntities/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/20-mergingDetachedEntities/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/20-mergingDetachedEntities/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..6996f2d --- /dev/null +++ b/examples/Chapter5/20-mergingDetachedEntities/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/mergingDetachedEntities + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/20-mergingDetachedEntities/etc/sql/db.sql b/examples/Chapter5/20-mergingDetachedEntities/etc/sql/db.sql new file mode 100644 index 0000000..cf5762b --- /dev/null +++ b/examples/Chapter5/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/Chapter5/20-mergingDetachedEntities/etc/web/WEB-INF/web.xml b/examples/Chapter5/20-mergingDetachedEntities/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/20-mergingDetachedEntities/src/model/examples/model/Employee.java b/examples/Chapter5/20-mergingDetachedEntities/src/model/examples/model/Employee.java new file mode 100644 index 0000000..ee504f9 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/20-mergingDetachedEntities/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/20-mergingDetachedEntities/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..9b9bbee --- /dev/null +++ b/examples/Chapter5/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/Chapter5/20-mergingDetachedEntities/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/20-mergingDetachedEntities/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..ccd2528 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/20-mergingDetachedEntities/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter5/20-mergingDetachedEntities/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..03aada2 --- /dev/null +++ b/examples/Chapter5/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 5: 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/Chapter5/20-mergingDetachedEntities/undeploy.bat b/examples/Chapter5/20-mergingDetachedEntities/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter5/20-mergingDetachedEntities/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/21-detachmentWithTriggeredLazyLoading/build.xml b/examples/Chapter5/21-detachmentWithTriggeredLazyLoading/build.xml new file mode 100644 index 0000000..73d2b2c --- /dev/null +++ b/examples/Chapter5/21-detachmentWithTriggeredLazyLoading/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/21-detachmentWithTriggeredLazyLoading/deploy.bat b/examples/Chapter5/21-detachmentWithTriggeredLazyLoading/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter5/21-detachmentWithTriggeredLazyLoading/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/21-detachmentWithTriggeredLazyLoading/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/21-detachmentWithTriggeredLazyLoading/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..62342c8 --- /dev/null +++ b/examples/Chapter5/21-detachmentWithTriggeredLazyLoading/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/detachmentWithTriggeredLazyLoading + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/21-detachmentWithTriggeredLazyLoading/etc/sql/db.sql b/examples/Chapter5/21-detachmentWithTriggeredLazyLoading/etc/sql/db.sql new file mode 100644 index 0000000..5e4ea5b --- /dev/null +++ b/examples/Chapter5/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/Chapter5/21-detachmentWithTriggeredLazyLoading/etc/web/WEB-INF/web.xml b/examples/Chapter5/21-detachmentWithTriggeredLazyLoading/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5d96981 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/21-detachmentWithTriggeredLazyLoading/etc/web/listEmployees.jsp b/examples/Chapter5/21-detachmentWithTriggeredLazyLoading/etc/web/listEmployees.jsp new file mode 100644 index 0000000..7da7758 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/21-detachmentWithTriggeredLazyLoading/src/model/examples/model/Department.java b/examples/Chapter5/21-detachmentWithTriggeredLazyLoading/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter5/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/Chapter5/21-detachmentWithTriggeredLazyLoading/src/model/examples/model/Employee.java b/examples/Chapter5/21-detachmentWithTriggeredLazyLoading/src/model/examples/model/Employee.java new file mode 100644 index 0000000..20746c1 --- /dev/null +++ b/examples/Chapter5/21-detachmentWithTriggeredLazyLoading/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(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/Chapter5/21-detachmentWithTriggeredLazyLoading/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/21-detachmentWithTriggeredLazyLoading/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..3c54249 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/21-detachmentWithTriggeredLazyLoading/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/21-detachmentWithTriggeredLazyLoading/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..d9ad9ca --- /dev/null +++ b/examples/Chapter5/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/Chapter5/21-detachmentWithTriggeredLazyLoading/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter5/21-detachmentWithTriggeredLazyLoading/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..623b994 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/21-detachmentWithTriggeredLazyLoading/undeploy.bat b/examples/Chapter5/21-detachmentWithTriggeredLazyLoading/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter5/21-detachmentWithTriggeredLazyLoading/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/22-detachmentWithEagerLoading/build.xml b/examples/Chapter5/22-detachmentWithEagerLoading/build.xml new file mode 100644 index 0000000..1716486 --- /dev/null +++ b/examples/Chapter5/22-detachmentWithEagerLoading/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/22-detachmentWithEagerLoading/deploy.bat b/examples/Chapter5/22-detachmentWithEagerLoading/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter5/22-detachmentWithEagerLoading/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/22-detachmentWithEagerLoading/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/22-detachmentWithEagerLoading/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..67c4b92 --- /dev/null +++ b/examples/Chapter5/22-detachmentWithEagerLoading/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/detachmentWithEagerLoading + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/22-detachmentWithEagerLoading/etc/sql/db.sql b/examples/Chapter5/22-detachmentWithEagerLoading/etc/sql/db.sql new file mode 100644 index 0000000..5e4ea5b --- /dev/null +++ b/examples/Chapter5/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/Chapter5/22-detachmentWithEagerLoading/etc/web/WEB-INF/web.xml b/examples/Chapter5/22-detachmentWithEagerLoading/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5d96981 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/22-detachmentWithEagerLoading/etc/web/listEmployees.jsp b/examples/Chapter5/22-detachmentWithEagerLoading/etc/web/listEmployees.jsp new file mode 100644 index 0000000..7da7758 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/22-detachmentWithEagerLoading/src/model/examples/model/Department.java b/examples/Chapter5/22-detachmentWithEagerLoading/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter5/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/Chapter5/22-detachmentWithEagerLoading/src/model/examples/model/Employee.java b/examples/Chapter5/22-detachmentWithEagerLoading/src/model/examples/model/Employee.java new file mode 100644 index 0000000..8b1778b --- /dev/null +++ b/examples/Chapter5/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/Chapter5/22-detachmentWithEagerLoading/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/22-detachmentWithEagerLoading/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..3c54249 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/22-detachmentWithEagerLoading/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/22-detachmentWithEagerLoading/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..3c0c0a6 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/22-detachmentWithEagerLoading/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter5/22-detachmentWithEagerLoading/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..623b994 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/22-detachmentWithEagerLoading/undeploy.bat b/examples/Chapter5/22-detachmentWithEagerLoading/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter5/22-detachmentWithEagerLoading/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/23-noDetachmentSingleTx/build.xml b/examples/Chapter5/23-noDetachmentSingleTx/build.xml new file mode 100644 index 0000000..aa949c8 --- /dev/null +++ b/examples/Chapter5/23-noDetachmentSingleTx/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/23-noDetachmentSingleTx/deploy.bat b/examples/Chapter5/23-noDetachmentSingleTx/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter5/23-noDetachmentSingleTx/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/23-noDetachmentSingleTx/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/23-noDetachmentSingleTx/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..631d1f6 --- /dev/null +++ b/examples/Chapter5/23-noDetachmentSingleTx/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/noDetachmentSingleTx + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/23-noDetachmentSingleTx/etc/sql/db.sql b/examples/Chapter5/23-noDetachmentSingleTx/etc/sql/db.sql new file mode 100644 index 0000000..5e4ea5b --- /dev/null +++ b/examples/Chapter5/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/Chapter5/23-noDetachmentSingleTx/etc/web/WEB-INF/web.xml b/examples/Chapter5/23-noDetachmentSingleTx/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5d96981 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/23-noDetachmentSingleTx/etc/web/listEmployees.jsp b/examples/Chapter5/23-noDetachmentSingleTx/etc/web/listEmployees.jsp new file mode 100644 index 0000000..7da7758 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/23-noDetachmentSingleTx/src/model/examples/model/Department.java b/examples/Chapter5/23-noDetachmentSingleTx/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter5/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/Chapter5/23-noDetachmentSingleTx/src/model/examples/model/Employee.java b/examples/Chapter5/23-noDetachmentSingleTx/src/model/examples/model/Employee.java new file mode 100644 index 0000000..6bcf568 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/23-noDetachmentSingleTx/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/23-noDetachmentSingleTx/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..3c54249 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/23-noDetachmentSingleTx/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/23-noDetachmentSingleTx/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..3c0c0a6 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/23-noDetachmentSingleTx/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter5/23-noDetachmentSingleTx/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..fec7664 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/23-noDetachmentSingleTx/undeploy.bat b/examples/Chapter5/23-noDetachmentSingleTx/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter5/23-noDetachmentSingleTx/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/24-noDetachmentAppManagedEm/build.xml b/examples/Chapter5/24-noDetachmentAppManagedEm/build.xml new file mode 100644 index 0000000..0abbe6c --- /dev/null +++ b/examples/Chapter5/24-noDetachmentAppManagedEm/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/24-noDetachmentAppManagedEm/deploy.bat b/examples/Chapter5/24-noDetachmentAppManagedEm/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter5/24-noDetachmentAppManagedEm/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/24-noDetachmentAppManagedEm/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/24-noDetachmentAppManagedEm/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..9b38469 --- /dev/null +++ b/examples/Chapter5/24-noDetachmentAppManagedEm/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/noDetachmentAppManagedEm + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/24-noDetachmentAppManagedEm/etc/sql/db.sql b/examples/Chapter5/24-noDetachmentAppManagedEm/etc/sql/db.sql new file mode 100644 index 0000000..5e4ea5b --- /dev/null +++ b/examples/Chapter5/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/Chapter5/24-noDetachmentAppManagedEm/etc/web/WEB-INF/web.xml b/examples/Chapter5/24-noDetachmentAppManagedEm/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5d96981 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/24-noDetachmentAppManagedEm/etc/web/listEmployees.jsp b/examples/Chapter5/24-noDetachmentAppManagedEm/etc/web/listEmployees.jsp new file mode 100644 index 0000000..7da7758 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/24-noDetachmentAppManagedEm/src/model/examples/model/Department.java b/examples/Chapter5/24-noDetachmentAppManagedEm/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter5/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/Chapter5/24-noDetachmentAppManagedEm/src/model/examples/model/Employee.java b/examples/Chapter5/24-noDetachmentAppManagedEm/src/model/examples/model/Employee.java new file mode 100644 index 0000000..6bcf568 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/24-noDetachmentAppManagedEm/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter5/24-noDetachmentAppManagedEm/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..b86073b --- /dev/null +++ b/examples/Chapter5/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/Chapter5/24-noDetachmentAppManagedEm/undeploy.bat b/examples/Chapter5/24-noDetachmentAppManagedEm/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter5/24-noDetachmentAppManagedEm/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/25-noDetachmentSFSBAndExtendedEm/build.xml b/examples/Chapter5/25-noDetachmentSFSBAndExtendedEm/build.xml new file mode 100644 index 0000000..56917b4 --- /dev/null +++ b/examples/Chapter5/25-noDetachmentSFSBAndExtendedEm/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/25-noDetachmentSFSBAndExtendedEm/deploy.bat b/examples/Chapter5/25-noDetachmentSFSBAndExtendedEm/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter5/25-noDetachmentSFSBAndExtendedEm/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/25-noDetachmentSFSBAndExtendedEm/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/25-noDetachmentSFSBAndExtendedEm/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..1a19278 --- /dev/null +++ b/examples/Chapter5/25-noDetachmentSFSBAndExtendedEm/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/noDetachmentSFSBAndExtendedEm + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/25-noDetachmentSFSBAndExtendedEm/etc/sql/db.sql b/examples/Chapter5/25-noDetachmentSFSBAndExtendedEm/etc/sql/db.sql new file mode 100644 index 0000000..5e4ea5b --- /dev/null +++ b/examples/Chapter5/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/Chapter5/25-noDetachmentSFSBAndExtendedEm/etc/web/WEB-INF/web.xml b/examples/Chapter5/25-noDetachmentSFSBAndExtendedEm/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5d96981 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/25-noDetachmentSFSBAndExtendedEm/etc/web/listEmployees.jsp b/examples/Chapter5/25-noDetachmentSFSBAndExtendedEm/etc/web/listEmployees.jsp new file mode 100644 index 0000000..7da7758 --- /dev/null +++ b/examples/Chapter5/25-noDetachmentSFSBAndExtendedEm/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/Chapter5/25-noDetachmentSFSBAndExtendedEm/src/model/examples/model/Department.java b/examples/Chapter5/25-noDetachmentSFSBAndExtendedEm/src/model/examples/model/Department.java new file mode 100644 index 0000000..e5b3e7d --- /dev/null +++ b/examples/Chapter5/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/Chapter5/25-noDetachmentSFSBAndExtendedEm/src/model/examples/model/Employee.java b/examples/Chapter5/25-noDetachmentSFSBAndExtendedEm/src/model/examples/model/Employee.java new file mode 100644 index 0000000..6bcf568 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/25-noDetachmentSFSBAndExtendedEm/src/model/examples/stateful/EmployeeQuery.java b/examples/Chapter5/25-noDetachmentSFSBAndExtendedEm/src/model/examples/stateful/EmployeeQuery.java new file mode 100644 index 0000000..52565ae --- /dev/null +++ b/examples/Chapter5/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/Chapter5/25-noDetachmentSFSBAndExtendedEm/src/model/examples/stateful/EmployeeQueryBean.java b/examples/Chapter5/25-noDetachmentSFSBAndExtendedEm/src/model/examples/stateful/EmployeeQueryBean.java new file mode 100644 index 0000000..25e0447 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/25-noDetachmentSFSBAndExtendedEm/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter5/25-noDetachmentSFSBAndExtendedEm/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..48dfa77 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/25-noDetachmentSFSBAndExtendedEm/undeploy.bat b/examples/Chapter5/25-noDetachmentSFSBAndExtendedEm/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter5/25-noDetachmentSFSBAndExtendedEm/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/26-editSessionExample/build.xml b/examples/Chapter5/26-editSessionExample/build.xml new file mode 100644 index 0000000..f37924b --- /dev/null +++ b/examples/Chapter5/26-editSessionExample/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter5/26-editSessionExample/deploy.bat b/examples/Chapter5/26-editSessionExample/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter5/26-editSessionExample/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter5/26-editSessionExample/etc/persistence/META-INF/persistence.xml b/examples/Chapter5/26-editSessionExample/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..8df18f6 --- /dev/null +++ b/examples/Chapter5/26-editSessionExample/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/editSessionExample + + + + + + \ No newline at end of file diff --git a/examples/Chapter5/26-editSessionExample/etc/sql/db.sql b/examples/Chapter5/26-editSessionExample/etc/sql/db.sql new file mode 100644 index 0000000..b62efcd --- /dev/null +++ b/examples/Chapter5/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/Chapter5/26-editSessionExample/etc/web/WEB-INF/web.xml b/examples/Chapter5/26-editSessionExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..c25518c --- /dev/null +++ b/examples/Chapter5/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/Chapter5/26-editSessionExample/etc/web/editEmployee.jsp b/examples/Chapter5/26-editSessionExample/etc/web/editEmployee.jsp new file mode 100644 index 0000000..02d7dc0 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/26-editSessionExample/etc/web/listEmployees.jsp b/examples/Chapter5/26-editSessionExample/etc/web/listEmployees.jsp new file mode 100644 index 0000000..e6b6a64 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/26-editSessionExample/src/model/examples/model/Employee.java b/examples/Chapter5/26-editSessionExample/src/model/examples/model/Employee.java new file mode 100644 index 0000000..0601a4c --- /dev/null +++ b/examples/Chapter5/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/Chapter5/26-editSessionExample/src/model/examples/stateful/EmployeeEdit.java b/examples/Chapter5/26-editSessionExample/src/model/examples/stateful/EmployeeEdit.java new file mode 100644 index 0000000..07ac9ca --- /dev/null +++ b/examples/Chapter5/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/Chapter5/26-editSessionExample/src/model/examples/stateful/EmployeeEditBean.java b/examples/Chapter5/26-editSessionExample/src/model/examples/stateful/EmployeeEditBean.java new file mode 100644 index 0000000..c75532c --- /dev/null +++ b/examples/Chapter5/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/Chapter5/26-editSessionExample/src/model/examples/stateless/EmployeeService.java b/examples/Chapter5/26-editSessionExample/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..3c54249 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/26-editSessionExample/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter5/26-editSessionExample/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..3c0c0a6 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/26-editSessionExample/src/servlet/examples/servlet/EmployeeEditServlet.java b/examples/Chapter5/26-editSessionExample/src/servlet/examples/servlet/EmployeeEditServlet.java new file mode 100644 index 0000000..307368c --- /dev/null +++ b/examples/Chapter5/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/Chapter5/26-editSessionExample/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter5/26-editSessionExample/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..34a7c43 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/26-editSessionExample/src/servlet/examples/servlet/EmployeeUpdateServlet.java b/examples/Chapter5/26-editSessionExample/src/servlet/examples/servlet/EmployeeUpdateServlet.java new file mode 100644 index 0000000..3281cf0 --- /dev/null +++ b/examples/Chapter5/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/Chapter5/26-editSessionExample/undeploy.bat b/examples/Chapter5/26-editSessionExample/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter5/26-editSessionExample/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter6/01-dynamicQueryExample/build.xml b/examples/Chapter6/01-dynamicQueryExample/build.xml new file mode 100644 index 0000000..7136b2e --- /dev/null +++ b/examples/Chapter6/01-dynamicQueryExample/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/01-dynamicQueryExample/deploy.bat b/examples/Chapter6/01-dynamicQueryExample/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter6/01-dynamicQueryExample/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter6/01-dynamicQueryExample/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/01-dynamicQueryExample/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..670a1d9 --- /dev/null +++ b/examples/Chapter6/01-dynamicQueryExample/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/dynamicQueryExample + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/01-dynamicQueryExample/etc/sql/db.sql b/examples/Chapter6/01-dynamicQueryExample/etc/sql/db.sql new file mode 100644 index 0000000..1d29472 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/01-dynamicQueryExample/etc/web/WEB-INF/web.xml b/examples/Chapter6/01-dynamicQueryExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..9f60be8 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/01-dynamicQueryExample/src/model/examples/model/Department.java b/examples/Chapter6/01-dynamicQueryExample/src/model/examples/model/Department.java new file mode 100644 index 0000000..5704081 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/01-dynamicQueryExample/src/model/examples/model/Employee.java b/examples/Chapter6/01-dynamicQueryExample/src/model/examples/model/Employee.java new file mode 100644 index 0000000..4bc3ecc --- /dev/null +++ b/examples/Chapter6/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/Chapter6/01-dynamicQueryExample/src/model/examples/model/Project.java b/examples/Chapter6/01-dynamicQueryExample/src/model/examples/model/Project.java new file mode 100644 index 0000000..8226327 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/01-dynamicQueryExample/src/model/examples/stateless/QueryService.java b/examples/Chapter6/01-dynamicQueryExample/src/model/examples/stateless/QueryService.java new file mode 100644 index 0000000..c8e8f00 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/01-dynamicQueryExample/src/model/examples/stateless/QueryServiceBean.java b/examples/Chapter6/01-dynamicQueryExample/src/model/examples/stateless/QueryServiceBean.java new file mode 100644 index 0000000..b0bf3d6 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/01-dynamicQueryExample/src/servlet/examples/servlet/QueryServiceServlet.java b/examples/Chapter6/01-dynamicQueryExample/src/servlet/examples/servlet/QueryServiceServlet.java new file mode 100644 index 0000000..f1660e6 --- /dev/null +++ b/examples/Chapter6/01-dynamicQueryExample/src/servlet/examples/servlet/QueryServiceServlet.java @@ -0,0 +1,91 @@ +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 6: 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. 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/Chapter6/01-dynamicQueryExample/undeploy.bat b/examples/Chapter6/01-dynamicQueryExample/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter6/01-dynamicQueryExample/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter6/02-namedQueryExample/build.xml b/examples/Chapter6/02-namedQueryExample/build.xml new file mode 100644 index 0000000..766de26 --- /dev/null +++ b/examples/Chapter6/02-namedQueryExample/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/02-namedQueryExample/deploy.bat b/examples/Chapter6/02-namedQueryExample/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter6/02-namedQueryExample/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter6/02-namedQueryExample/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/02-namedQueryExample/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..4fdb58c --- /dev/null +++ b/examples/Chapter6/02-namedQueryExample/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/namedQueryExample + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/02-namedQueryExample/etc/sql/db.sql b/examples/Chapter6/02-namedQueryExample/etc/sql/db.sql new file mode 100644 index 0000000..1d29472 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/02-namedQueryExample/etc/web/WEB-INF/web.xml b/examples/Chapter6/02-namedQueryExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/02-namedQueryExample/src/model/examples/model/Department.java b/examples/Chapter6/02-namedQueryExample/src/model/examples/model/Department.java new file mode 100644 index 0000000..5704081 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/02-namedQueryExample/src/model/examples/model/Employee.java b/examples/Chapter6/02-namedQueryExample/src/model/examples/model/Employee.java new file mode 100644 index 0000000..15af75a --- /dev/null +++ b/examples/Chapter6/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/Chapter6/02-namedQueryExample/src/model/examples/model/Project.java b/examples/Chapter6/02-namedQueryExample/src/model/examples/model/Project.java new file mode 100644 index 0000000..8226327 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/02-namedQueryExample/src/model/examples/stateless/EmployeeService.java b/examples/Chapter6/02-namedQueryExample/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..6f018fd --- /dev/null +++ b/examples/Chapter6/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/Chapter6/02-namedQueryExample/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter6/02-namedQueryExample/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..f85d9ce --- /dev/null +++ b/examples/Chapter6/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/Chapter6/02-namedQueryExample/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter6/02-namedQueryExample/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..d123cdb --- /dev/null +++ b/examples/Chapter6/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 6: 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/Chapter6/02-namedQueryExample/undeploy.bat b/examples/Chapter6/02-namedQueryExample/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter6/02-namedQueryExample/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter6/03-paramTypesExample/build.xml b/examples/Chapter6/03-paramTypesExample/build.xml new file mode 100644 index 0000000..085f15e --- /dev/null +++ b/examples/Chapter6/03-paramTypesExample/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/03-paramTypesExample/deploy.bat b/examples/Chapter6/03-paramTypesExample/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter6/03-paramTypesExample/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter6/03-paramTypesExample/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/03-paramTypesExample/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..bc76abb --- /dev/null +++ b/examples/Chapter6/03-paramTypesExample/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/paramTypesExample + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/03-paramTypesExample/etc/sql/db.sql b/examples/Chapter6/03-paramTypesExample/etc/sql/db.sql new file mode 100644 index 0000000..1d29472 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/03-paramTypesExample/etc/web/WEB-INF/web.xml b/examples/Chapter6/03-paramTypesExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/03-paramTypesExample/src/model/examples/model/Department.java b/examples/Chapter6/03-paramTypesExample/src/model/examples/model/Department.java new file mode 100644 index 0000000..9d1a2c2 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/03-paramTypesExample/src/model/examples/model/Employee.java b/examples/Chapter6/03-paramTypesExample/src/model/examples/model/Employee.java new file mode 100644 index 0000000..43f8b74 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/03-paramTypesExample/src/model/examples/model/Project.java b/examples/Chapter6/03-paramTypesExample/src/model/examples/model/Project.java new file mode 100644 index 0000000..8226327 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/03-paramTypesExample/src/model/examples/stateless/EmployeeService.java b/examples/Chapter6/03-paramTypesExample/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..3574a34 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/03-paramTypesExample/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter6/03-paramTypesExample/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..47ef78d --- /dev/null +++ b/examples/Chapter6/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/Chapter6/03-paramTypesExample/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter6/03-paramTypesExample/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..5064631 --- /dev/null +++ b/examples/Chapter6/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 6: 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/Chapter6/03-paramTypesExample/undeploy.bat b/examples/Chapter6/03-paramTypesExample/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter6/03-paramTypesExample/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter6/04-executingQueriesExample/build.xml b/examples/Chapter6/04-executingQueriesExample/build.xml new file mode 100644 index 0000000..5d9e15e --- /dev/null +++ b/examples/Chapter6/04-executingQueriesExample/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/04-executingQueriesExample/deploy.bat b/examples/Chapter6/04-executingQueriesExample/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter6/04-executingQueriesExample/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter6/04-executingQueriesExample/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/04-executingQueriesExample/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..7b641f0 --- /dev/null +++ b/examples/Chapter6/04-executingQueriesExample/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/executingQueriesExample + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/04-executingQueriesExample/etc/sql/db.sql b/examples/Chapter6/04-executingQueriesExample/etc/sql/db.sql new file mode 100644 index 0000000..1d29472 --- /dev/null +++ b/examples/Chapter6/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, 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/Chapter6/04-executingQueriesExample/etc/web/WEB-INF/web.xml b/examples/Chapter6/04-executingQueriesExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/04-executingQueriesExample/src/model/examples/model/Department.java b/examples/Chapter6/04-executingQueriesExample/src/model/examples/model/Department.java new file mode 100644 index 0000000..9d1a2c2 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/04-executingQueriesExample/src/model/examples/model/Employee.java b/examples/Chapter6/04-executingQueriesExample/src/model/examples/model/Employee.java new file mode 100644 index 0000000..8a6d57b --- /dev/null +++ b/examples/Chapter6/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/Chapter6/04-executingQueriesExample/src/model/examples/model/Project.java b/examples/Chapter6/04-executingQueriesExample/src/model/examples/model/Project.java new file mode 100644 index 0000000..8226327 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/04-executingQueriesExample/src/model/examples/stateful/ProjectManager.java b/examples/Chapter6/04-executingQueriesExample/src/model/examples/stateful/ProjectManager.java new file mode 100644 index 0000000..e2f883e --- /dev/null +++ b/examples/Chapter6/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/Chapter6/04-executingQueriesExample/src/model/examples/stateful/ProjectManagerBean.java b/examples/Chapter6/04-executingQueriesExample/src/model/examples/stateful/ProjectManagerBean.java new file mode 100644 index 0000000..597ca3c --- /dev/null +++ b/examples/Chapter6/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/Chapter6/04-executingQueriesExample/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter6/04-executingQueriesExample/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..0be2180 --- /dev/null +++ b/examples/Chapter6/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 6: 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/Chapter6/04-executingQueriesExample/undeploy.bat b/examples/Chapter6/04-executingQueriesExample/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter6/04-executingQueriesExample/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter6/05-queryResultsExample/build.xml b/examples/Chapter6/05-queryResultsExample/build.xml new file mode 100644 index 0000000..10fb60f --- /dev/null +++ b/examples/Chapter6/05-queryResultsExample/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/05-queryResultsExample/deploy.bat b/examples/Chapter6/05-queryResultsExample/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter6/05-queryResultsExample/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter6/05-queryResultsExample/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/05-queryResultsExample/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..8d81d9b --- /dev/null +++ b/examples/Chapter6/05-queryResultsExample/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/queryResultsExample + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/05-queryResultsExample/etc/sql/db.sql b/examples/Chapter6/05-queryResultsExample/etc/sql/db.sql new file mode 100644 index 0000000..1d29472 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/05-queryResultsExample/etc/web/WEB-INF/web.xml b/examples/Chapter6/05-queryResultsExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/05-queryResultsExample/src/model/examples/EmpMenu.java b/examples/Chapter6/05-queryResultsExample/src/model/examples/EmpMenu.java new file mode 100644 index 0000000..8ac9700 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/05-queryResultsExample/src/model/examples/model/Department.java b/examples/Chapter6/05-queryResultsExample/src/model/examples/model/Department.java new file mode 100644 index 0000000..9d1a2c2 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/05-queryResultsExample/src/model/examples/model/Employee.java b/examples/Chapter6/05-queryResultsExample/src/model/examples/model/Employee.java new file mode 100644 index 0000000..8a6d57b --- /dev/null +++ b/examples/Chapter6/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/Chapter6/05-queryResultsExample/src/model/examples/model/Project.java b/examples/Chapter6/05-queryResultsExample/src/model/examples/model/Project.java new file mode 100644 index 0000000..8226327 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/05-queryResultsExample/src/model/examples/stateless/QueryService.java b/examples/Chapter6/05-queryResultsExample/src/model/examples/stateless/QueryService.java new file mode 100644 index 0000000..86002db --- /dev/null +++ b/examples/Chapter6/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/Chapter6/05-queryResultsExample/src/model/examples/stateless/QueryServiceBean.java b/examples/Chapter6/05-queryResultsExample/src/model/examples/stateless/QueryServiceBean.java new file mode 100644 index 0000000..5d5c077 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/05-queryResultsExample/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter6/05-queryResultsExample/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..e77f642 --- /dev/null +++ b/examples/Chapter6/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 6: 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/Chapter6/05-queryResultsExample/undeploy.bat b/examples/Chapter6/05-queryResultsExample/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter6/05-queryResultsExample/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter6/06-queryPagingExample/build.xml b/examples/Chapter6/06-queryPagingExample/build.xml new file mode 100644 index 0000000..d0bd1ab --- /dev/null +++ b/examples/Chapter6/06-queryPagingExample/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/06-queryPagingExample/deploy.bat b/examples/Chapter6/06-queryPagingExample/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter6/06-queryPagingExample/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter6/06-queryPagingExample/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/06-queryPagingExample/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..5dd6d54 --- /dev/null +++ b/examples/Chapter6/06-queryPagingExample/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/queryPagingDB + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/06-queryPagingExample/etc/sql/db.sql b/examples/Chapter6/06-queryPagingExample/etc/sql/db.sql new file mode 100644 index 0000000..1d29472 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/06-queryPagingExample/etc/web/WEB-INF/web.xml b/examples/Chapter6/06-queryPagingExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..0c884a7 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/06-queryPagingExample/src/model/examples/model/Department.java b/examples/Chapter6/06-queryPagingExample/src/model/examples/model/Department.java new file mode 100644 index 0000000..9d1a2c2 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/06-queryPagingExample/src/model/examples/model/Employee.java b/examples/Chapter6/06-queryPagingExample/src/model/examples/model/Employee.java new file mode 100644 index 0000000..6a7f784 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/06-queryPagingExample/src/model/examples/model/Project.java b/examples/Chapter6/06-queryPagingExample/src/model/examples/model/Project.java new file mode 100644 index 0000000..8226327 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/06-queryPagingExample/src/model/examples/stateful/ResultPager.java b/examples/Chapter6/06-queryPagingExample/src/model/examples/stateful/ResultPager.java new file mode 100644 index 0000000..5c29b6e --- /dev/null +++ b/examples/Chapter6/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/Chapter6/06-queryPagingExample/src/model/examples/stateful/ResultPagerBean.java b/examples/Chapter6/06-queryPagingExample/src/model/examples/stateful/ResultPagerBean.java new file mode 100644 index 0000000..25f882c --- /dev/null +++ b/examples/Chapter6/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/Chapter6/06-queryPagingExample/src/servlet/examples/servlet/EmployeePagingServlet.java b/examples/Chapter6/06-queryPagingExample/src/servlet/examples/servlet/EmployeePagingServlet.java new file mode 100644 index 0000000..321f5b8 --- /dev/null +++ b/examples/Chapter6/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 6: 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/Chapter6/06-queryPagingExample/undeploy.bat b/examples/Chapter6/06-queryPagingExample/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter6/06-queryPagingExample/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter6/07-messageBoardExample/build.xml b/examples/Chapter6/07-messageBoardExample/build.xml new file mode 100644 index 0000000..97c0266 --- /dev/null +++ b/examples/Chapter6/07-messageBoardExample/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/07-messageBoardExample/deploy.bat b/examples/Chapter6/07-messageBoardExample/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter6/07-messageBoardExample/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter6/07-messageBoardExample/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/07-messageBoardExample/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..df63726 --- /dev/null +++ b/examples/Chapter6/07-messageBoardExample/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/messageBoardExample + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/07-messageBoardExample/etc/sql/db.sql b/examples/Chapter6/07-messageBoardExample/etc/sql/db.sql new file mode 100644 index 0000000..97e4f91 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/07-messageBoardExample/etc/web/WEB-INF/web.xml b/examples/Chapter6/07-messageBoardExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..b6ebd37 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/07-messageBoardExample/src/model/examples/model/Conversation.java b/examples/Chapter6/07-messageBoardExample/src/model/examples/model/Conversation.java new file mode 100644 index 0000000..f883074 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/07-messageBoardExample/src/model/examples/model/Message.java b/examples/Chapter6/07-messageBoardExample/src/model/examples/model/Message.java new file mode 100644 index 0000000..1854c90 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/07-messageBoardExample/src/model/examples/stateless/ConversationMaintenance.java b/examples/Chapter6/07-messageBoardExample/src/model/examples/stateless/ConversationMaintenance.java new file mode 100644 index 0000000..6cd84ee --- /dev/null +++ b/examples/Chapter6/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/Chapter6/07-messageBoardExample/src/model/examples/stateless/ConversationMaintenanceBean.java b/examples/Chapter6/07-messageBoardExample/src/model/examples/stateless/ConversationMaintenanceBean.java new file mode 100644 index 0000000..e1a8291 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/07-messageBoardExample/src/servlet/examples/servlet/MessageBoardServlet.java b/examples/Chapter6/07-messageBoardExample/src/servlet/examples/servlet/MessageBoardServlet.java new file mode 100644 index 0000000..9b6c94e --- /dev/null +++ b/examples/Chapter6/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 6: 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/Chapter6/07-messageBoardExample/undeploy.bat b/examples/Chapter6/07-messageBoardExample/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter6/07-messageBoardExample/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter6/08-bulkQueryExample/build.xml b/examples/Chapter6/08-bulkQueryExample/build.xml new file mode 100644 index 0000000..c03108f --- /dev/null +++ b/examples/Chapter6/08-bulkQueryExample/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/08-bulkQueryExample/deploy.bat b/examples/Chapter6/08-bulkQueryExample/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter6/08-bulkQueryExample/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter6/08-bulkQueryExample/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/08-bulkQueryExample/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..86b27ce --- /dev/null +++ b/examples/Chapter6/08-bulkQueryExample/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/bulkQueryExample + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/08-bulkQueryExample/etc/sql/db.sql b/examples/Chapter6/08-bulkQueryExample/etc/sql/db.sql new file mode 100644 index 0000000..1d29472 --- /dev/null +++ b/examples/Chapter6/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, 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/Chapter6/08-bulkQueryExample/etc/web/WEB-INF/web.xml b/examples/Chapter6/08-bulkQueryExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/08-bulkQueryExample/src/model/examples/model/Department.java b/examples/Chapter6/08-bulkQueryExample/src/model/examples/model/Department.java new file mode 100644 index 0000000..9d1a2c2 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/08-bulkQueryExample/src/model/examples/model/Employee.java b/examples/Chapter6/08-bulkQueryExample/src/model/examples/model/Employee.java new file mode 100644 index 0000000..0392833 --- /dev/null +++ b/examples/Chapter6/08-bulkQueryExample/src/model/examples/model/Employee.java @@ -0,0 +1,83 @@ +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() + + ", dept: " + ((getDepartment() == null) ? null : getDepartment().getName()); + } +} diff --git a/examples/Chapter6/08-bulkQueryExample/src/model/examples/model/Project.java b/examples/Chapter6/08-bulkQueryExample/src/model/examples/model/Project.java new file mode 100644 index 0000000..8226327 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/08-bulkQueryExample/src/model/examples/stateless/DepartmentService.java b/examples/Chapter6/08-bulkQueryExample/src/model/examples/stateless/DepartmentService.java new file mode 100644 index 0000000..8da256f --- /dev/null +++ b/examples/Chapter6/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/Chapter6/08-bulkQueryExample/src/model/examples/stateless/DepartmentServiceBean.java b/examples/Chapter6/08-bulkQueryExample/src/model/examples/stateless/DepartmentServiceBean.java new file mode 100644 index 0000000..93eb3ea --- /dev/null +++ b/examples/Chapter6/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/Chapter6/08-bulkQueryExample/src/model/examples/stateless/EmployeeService.java b/examples/Chapter6/08-bulkQueryExample/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..6ab3e2f --- /dev/null +++ b/examples/Chapter6/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/Chapter6/08-bulkQueryExample/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter6/08-bulkQueryExample/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..8a0bf68 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/08-bulkQueryExample/src/model/examples/stateless/ProjectService.java b/examples/Chapter6/08-bulkQueryExample/src/model/examples/stateless/ProjectService.java new file mode 100644 index 0000000..4fc65e3 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/08-bulkQueryExample/src/model/examples/stateless/ProjectServiceBean.java b/examples/Chapter6/08-bulkQueryExample/src/model/examples/stateless/ProjectServiceBean.java new file mode 100644 index 0000000..f3f0159 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/08-bulkQueryExample/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter6/08-bulkQueryExample/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..7e792ab --- /dev/null +++ b/examples/Chapter6/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/Chapter6/08-bulkQueryExample/undeploy.bat b/examples/Chapter6/08-bulkQueryExample/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter6/08-bulkQueryExample/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter6/09-queryHintsExample/build.xml b/examples/Chapter6/09-queryHintsExample/build.xml new file mode 100644 index 0000000..eb882eb --- /dev/null +++ b/examples/Chapter6/09-queryHintsExample/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter6/09-queryHintsExample/deploy.bat b/examples/Chapter6/09-queryHintsExample/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter6/09-queryHintsExample/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter6/09-queryHintsExample/etc/persistence/META-INF/persistence.xml b/examples/Chapter6/09-queryHintsExample/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..984e5cd --- /dev/null +++ b/examples/Chapter6/09-queryHintsExample/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/queryHintsExample + + + + + + \ No newline at end of file diff --git a/examples/Chapter6/09-queryHintsExample/etc/sql/db.sql b/examples/Chapter6/09-queryHintsExample/etc/sql/db.sql new file mode 100644 index 0000000..72746e4 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/09-queryHintsExample/etc/web/WEB-INF/web.xml b/examples/Chapter6/09-queryHintsExample/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..ab3ed11 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/09-queryHintsExample/src/model/examples/model/Employee.java b/examples/Chapter6/09-queryHintsExample/src/model/examples/model/Employee.java new file mode 100644 index 0000000..e9728e5 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/09-queryHintsExample/src/model/examples/stateless/EmployeeService.java b/examples/Chapter6/09-queryHintsExample/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..f01c203 --- /dev/null +++ b/examples/Chapter6/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/Chapter6/09-queryHintsExample/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter6/09-queryHintsExample/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..f2bd424 --- /dev/null +++ b/examples/Chapter6/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 oracle.toplink.essentials.queryframework.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/Chapter6/09-queryHintsExample/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter6/09-queryHintsExample/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..3d3135d --- /dev/null +++ b/examples/Chapter6/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 6: 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/Chapter6/09-queryHintsExample/undeploy.bat b/examples/Chapter6/09-queryHintsExample/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter6/09-queryHintsExample/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter7/jpqlExamples/build.xml b/examples/Chapter7/jpqlExamples/build.xml new file mode 100644 index 0000000..54ea890 --- /dev/null +++ b/examples/Chapter7/jpqlExamples/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter7/jpqlExamples/deploy.bat b/examples/Chapter7/jpqlExamples/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter7/jpqlExamples/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter7/jpqlExamples/etc/persistence/META-INF/persistence.xml b/examples/Chapter7/jpqlExamples/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..6ee1e95 --- /dev/null +++ b/examples/Chapter7/jpqlExamples/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/jpqlExamples + + + + + + \ No newline at end of file diff --git a/examples/Chapter7/jpqlExamples/etc/sql/db.sql b/examples/Chapter7/jpqlExamples/etc/sql/db.sql new file mode 100644 index 0000000..c45c7ab --- /dev/null +++ b/examples/Chapter7/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/Chapter7/jpqlExamples/etc/web/WEB-INF/web.xml b/examples/Chapter7/jpqlExamples/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..010ba31 --- /dev/null +++ b/examples/Chapter7/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/Chapter7/jpqlExamples/etc/web/index.html b/examples/Chapter7/jpqlExamples/etc/web/index.html new file mode 100644 index 0000000..4e80613 --- /dev/null +++ b/examples/Chapter7/jpqlExamples/etc/web/index.html @@ -0,0 +1,300 @@ + + +Chapterb 7: Query Language +

Chapter 7: 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/Chapter7/jpqlExamples/src/model/examples/model/Address.java b/examples/Chapter7/jpqlExamples/src/model/examples/model/Address.java new file mode 100644 index 0000000..e18406b --- /dev/null +++ b/examples/Chapter7/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/Chapter7/jpqlExamples/src/model/examples/model/Department.java b/examples/Chapter7/jpqlExamples/src/model/examples/model/Department.java new file mode 100644 index 0000000..a1ac11c --- /dev/null +++ b/examples/Chapter7/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/Chapter7/jpqlExamples/src/model/examples/model/DesignProject.java b/examples/Chapter7/jpqlExamples/src/model/examples/model/DesignProject.java new file mode 100644 index 0000000..6b9f13a --- /dev/null +++ b/examples/Chapter7/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/Chapter7/jpqlExamples/src/model/examples/model/Employee.java b/examples/Chapter7/jpqlExamples/src/model/examples/model/Employee.java new file mode 100644 index 0000000..806ef9f --- /dev/null +++ b/examples/Chapter7/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/Chapter7/jpqlExamples/src/model/examples/model/EmployeeDetails.java b/examples/Chapter7/jpqlExamples/src/model/examples/model/EmployeeDetails.java new file mode 100644 index 0000000..284aac7 --- /dev/null +++ b/examples/Chapter7/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/Chapter7/jpqlExamples/src/model/examples/model/Phone.java b/examples/Chapter7/jpqlExamples/src/model/examples/model/Phone.java new file mode 100644 index 0000000..afa5419 --- /dev/null +++ b/examples/Chapter7/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/Chapter7/jpqlExamples/src/model/examples/model/Project.java b/examples/Chapter7/jpqlExamples/src/model/examples/model/Project.java new file mode 100644 index 0000000..d1261d3 --- /dev/null +++ b/examples/Chapter7/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/Chapter7/jpqlExamples/src/model/examples/model/QualityProject.java b/examples/Chapter7/jpqlExamples/src/model/examples/model/QualityProject.java new file mode 100644 index 0000000..78d2361 --- /dev/null +++ b/examples/Chapter7/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/Chapter7/jpqlExamples/src/servlet/examples/servlet/ClientServlet.java b/examples/Chapter7/jpqlExamples/src/servlet/examples/servlet/ClientServlet.java new file mode 100644 index 0000000..4bcfb6c --- /dev/null +++ b/examples/Chapter7/jpqlExamples/src/servlet/examples/servlet/ClientServlet.java @@ -0,0 +1,350 @@ +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.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 7: Query Language"; + + @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/Chapter7/jpqlExamples/undeploy.bat b/examples/Chapter7/jpqlExamples/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter7/jpqlExamples/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter8/01-embeddedObjects/build.xml b/examples/Chapter8/01-embeddedObjects/build.xml new file mode 100644 index 0000000..a406a2c --- /dev/null +++ b/examples/Chapter8/01-embeddedObjects/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter8/01-embeddedObjects/deploy.bat b/examples/Chapter8/01-embeddedObjects/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter8/01-embeddedObjects/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter8/01-embeddedObjects/etc/persistence/META-INF/persistence.xml b/examples/Chapter8/01-embeddedObjects/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..2dc8e4a --- /dev/null +++ b/examples/Chapter8/01-embeddedObjects/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/embeddedObjects + + + + + + \ No newline at end of file diff --git a/examples/Chapter8/01-embeddedObjects/etc/sql/db.sql b/examples/Chapter8/01-embeddedObjects/etc/sql/db.sql new file mode 100644 index 0000000..e44df60 --- /dev/null +++ b/examples/Chapter8/01-embeddedObjects/etc/sql/db.sql @@ -0,0 +1,4 @@ +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/Chapter8/01-embeddedObjects/etc/web/WEB-INF/web.xml b/examples/Chapter8/01-embeddedObjects/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter8/01-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/Chapter8/01-embeddedObjects/src/model/examples/model/Address.java b/examples/Chapter8/01-embeddedObjects/src/model/examples/model/Address.java new file mode 100644 index 0000000..bfcb26b --- /dev/null +++ b/examples/Chapter8/01-embeddedObjects/src/model/examples/model/Address.java @@ -0,0 +1,52 @@ +package examples.model; + +import javax.persistence.Column; +import javax.persistence.Embeddable; + +@Embeddable +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/Chapter8/01-embeddedObjects/src/model/examples/model/Employee.java b/examples/Chapter8/01-embeddedObjects/src/model/examples/model/Employee.java new file mode 100644 index 0000000..1f3cf91 --- /dev/null +++ b/examples/Chapter8/01-embeddedObjects/src/model/examples/model/Employee.java @@ -0,0 +1,50 @@ +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 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() + + " with " + getAddress(); + } +} diff --git a/examples/Chapter8/01-embeddedObjects/src/model/examples/stateless/EmployeeService.java b/examples/Chapter8/01-embeddedObjects/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..a63a3a2 --- /dev/null +++ b/examples/Chapter8/01-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/Chapter8/01-embeddedObjects/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter8/01-embeddedObjects/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..a361287 --- /dev/null +++ b/examples/Chapter8/01-embeddedObjects/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.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/Chapter8/01-embeddedObjects/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter8/01-embeddedObjects/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..501c486 --- /dev/null +++ b/examples/Chapter8/01-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 8: Using Embedded Objects Example"; + + private final String DESCRIPTION = + "This example demonstates 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/Chapter8/01-embeddedObjects/undeploy.bat b/examples/Chapter8/01-embeddedObjects/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter8/01-embeddedObjects/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter8/02-sharingEmbeddedObjects/build.xml b/examples/Chapter8/02-sharingEmbeddedObjects/build.xml new file mode 100644 index 0000000..d681f25 --- /dev/null +++ b/examples/Chapter8/02-sharingEmbeddedObjects/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter8/02-sharingEmbeddedObjects/deploy.bat b/examples/Chapter8/02-sharingEmbeddedObjects/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter8/02-sharingEmbeddedObjects/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter8/02-sharingEmbeddedObjects/etc/persistence/META-INF/persistence.xml b/examples/Chapter8/02-sharingEmbeddedObjects/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..f813339 --- /dev/null +++ b/examples/Chapter8/02-sharingEmbeddedObjects/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/sharingEmbeddedObjects + + + + + + \ No newline at end of file diff --git a/examples/Chapter8/02-sharingEmbeddedObjects/etc/sql/db.sql b/examples/Chapter8/02-sharingEmbeddedObjects/etc/sql/db.sql new file mode 100644 index 0000000..4bf007d --- /dev/null +++ b/examples/Chapter8/02-sharingEmbeddedObjects/etc/sql/db.sql @@ -0,0 +1,7 @@ +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 (NAME VARCHAR(255) NOT NULL, STREET VARCHAR(255), CITY VARCHAR(255), STATE VARCHAR(255), + ZIP_CODE VARCHAR(255), PRIMARY KEY (NAME)); diff --git a/examples/Chapter8/02-sharingEmbeddedObjects/etc/web/WEB-INF/web.xml b/examples/Chapter8/02-sharingEmbeddedObjects/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter8/02-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/Chapter8/02-sharingEmbeddedObjects/src/model/examples/model/Address.java b/examples/Chapter8/02-sharingEmbeddedObjects/src/model/examples/model/Address.java new file mode 100644 index 0000000..bfcb26b --- /dev/null +++ b/examples/Chapter8/02-sharingEmbeddedObjects/src/model/examples/model/Address.java @@ -0,0 +1,52 @@ +package examples.model; + +import javax.persistence.Column; +import javax.persistence.Embeddable; + +@Embeddable +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/Chapter8/02-sharingEmbeddedObjects/src/model/examples/model/Company.java b/examples/Chapter8/02-sharingEmbeddedObjects/src/model/examples/model/Company.java new file mode 100644 index 0000000..db97709 --- /dev/null +++ b/examples/Chapter8/02-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 String name; + @Embedded + private Address address; + + 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 "Company name: " + getName() + + " at " + getAddress(); + } +} diff --git a/examples/Chapter8/02-sharingEmbeddedObjects/src/model/examples/model/Employee.java b/examples/Chapter8/02-sharingEmbeddedObjects/src/model/examples/model/Employee.java new file mode 100644 index 0000000..b2736c9 --- /dev/null +++ b/examples/Chapter8/02-sharingEmbeddedObjects/src/model/examples/model/Employee.java @@ -0,0 +1,59 @@ +package examples.model; + +import javax.persistence.AttributeOverride; +import javax.persistence.AttributeOverrides; +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 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() + + " with " + getAddress(); + } +} diff --git a/examples/Chapter8/02-sharingEmbeddedObjects/src/model/examples/stateless/EmployeeService.java b/examples/Chapter8/02-sharingEmbeddedObjects/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..2012fcd --- /dev/null +++ b/examples/Chapter8/02-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(String name, + String street, String city, String state, String zip); + public Collection findAllEmployees(); + public Collection findAllCompanies(); +} diff --git a/examples/Chapter8/02-sharingEmbeddedObjects/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter8/02-sharingEmbeddedObjects/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..2749a53 --- /dev/null +++ b/examples/Chapter8/02-sharingEmbeddedObjects/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,60 @@ +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.Company; +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 Company createCompanyAndAddress(String name, + String street, String city, String state, String zip) { + Company c = new Company(); + c.setName(name); + 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/Chapter8/02-sharingEmbeddedObjects/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter8/02-sharingEmbeddedObjects/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..17a240b --- /dev/null +++ b/examples/Chapter8/02-sharingEmbeddedObjects/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,126 @@ +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.stateless.EmployeeService; + +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 8: Sharing Embedded Objects Example"; + + private final String DESCRIPTION = + "This example demonstates 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("CreateEmp")) { + 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( + request.getParameter("cName"), + 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 Name:(String)
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/Chapter8/02-sharingEmbeddedObjects/undeploy.bat b/examples/Chapter8/02-sharingEmbeddedObjects/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter8/02-sharingEmbeddedObjects/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter8/03-compoundPrimaryKey/build.xml b/examples/Chapter8/03-compoundPrimaryKey/build.xml new file mode 100644 index 0000000..5c7dc76 --- /dev/null +++ b/examples/Chapter8/03-compoundPrimaryKey/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter8/03-compoundPrimaryKey/deploy.bat b/examples/Chapter8/03-compoundPrimaryKey/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter8/03-compoundPrimaryKey/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter8/03-compoundPrimaryKey/etc/persistence/META-INF/persistence.xml b/examples/Chapter8/03-compoundPrimaryKey/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..bfb064c --- /dev/null +++ b/examples/Chapter8/03-compoundPrimaryKey/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/compoundPrimaryKey + + + + + + \ No newline at end of file diff --git a/examples/Chapter8/03-compoundPrimaryKey/etc/sql/db.sql b/examples/Chapter8/03-compoundPrimaryKey/etc/sql/db.sql new file mode 100644 index 0000000..4a6607c --- /dev/null +++ b/examples/Chapter8/03-compoundPrimaryKey/etc/sql/db.sql @@ -0,0 +1,4 @@ +DROP TABLE EMPLOYEE; + +CREATE TABLE EMPLOYEE (COUNTRY VARCHAR(255) NOT NULL, EMP_ID INTEGER NOT NULL, NAME VARCHAR(255), + SALARY BIGINT, PRIMARY KEY(COUNTRY,EMP_ID)); diff --git a/examples/Chapter8/03-compoundPrimaryKey/etc/web/WEB-INF/web.xml b/examples/Chapter8/03-compoundPrimaryKey/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter8/03-compoundPrimaryKey/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/Chapter8/03-compoundPrimaryKey/src/model/examples/model/Employee.java b/examples/Chapter8/03-compoundPrimaryKey/src/model/examples/model/Employee.java new file mode 100644 index 0000000..22d1e7d --- /dev/null +++ b/examples/Chapter8/03-compoundPrimaryKey/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; +import javax.persistence.IdClass; + +@Entity +@IdClass(EmployeeId.class) +public class Employee { + @Id private String country; + @Id + @Column(name="EMP_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 getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + 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() + + " country: " + getCountry(); + } +} diff --git a/examples/Chapter8/03-compoundPrimaryKey/src/model/examples/model/EmployeeId.java b/examples/Chapter8/03-compoundPrimaryKey/src/model/examples/model/EmployeeId.java new file mode 100644 index 0000000..031521a --- /dev/null +++ b/examples/Chapter8/03-compoundPrimaryKey/src/model/examples/model/EmployeeId.java @@ -0,0 +1,28 @@ +package examples.model; + +import java.io.Serializable; + +public class EmployeeId implements Serializable { + private String country; + private int id; + + public EmployeeId() {} + public EmployeeId(String country, int id) { + this.country = country; + this.id = id; + } + + public String getCountry() { return country; } + public int getId() { return id; } + + public boolean equals(Object o) { + return ((o instanceof EmployeeId) && + country.equals(((EmployeeId)o).getCountry()) && + id == ((EmployeeId) o).getId()); + + } + + public int hashCode() { + return country.hashCode() + id; + } +} \ No newline at end of file diff --git a/examples/Chapter8/03-compoundPrimaryKey/src/model/examples/stateless/EmployeeService.java b/examples/Chapter8/03-compoundPrimaryKey/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..959a566 --- /dev/null +++ b/examples/Chapter8/03-compoundPrimaryKey/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 createEmployee(String country, int id, + String name, long salary); + public Employee findEmployee(String country, int id); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter8/03-compoundPrimaryKey/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter8/03-compoundPrimaryKey/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..02a1ae5 --- /dev/null +++ b/examples/Chapter8/03-compoundPrimaryKey/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.EmployeeId; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String country, int id, + String name, long salary) { + Employee emp = new Employee(); + emp.setCountry(country); + emp.setId(id); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + + return emp; + } + + public Employee findEmployee(String country, int id) { + return em.find(Employee.class, new EmployeeId(country, id)); + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter8/03-compoundPrimaryKey/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter8/03-compoundPrimaryKey/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..ca47fb8 --- /dev/null +++ b/examples/Chapter8/03-compoundPrimaryKey/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 8: Using Compound Primary Keys Example"; + + private final String DESCRIPTION = + "This example demonstates the basics of using compound primary keys."; + + @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.createEmployee( + request.getParameter("country"), + parseInt(request.getParameter("empId")), + request.getParameter("name"), + parseLong(request.getParameter("salary"))); + } else if (action.equals("Find")) { + Employee emp = service.findEmployee( + request.getParameter("findCountry"), + parseInt(request.getParameter("findId"))); + out.print("Found " + emp + "
"); + } + + 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 and Employee + out.println("

Create an Employee

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

Find an Employee

"); + out.println(""); + out.println(""); + out.println("" + + ""); + out.println("
Employee Country:(String)
Employee Id:(int)
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter8/03-compoundPrimaryKey/undeploy.bat b/examples/Chapter8/03-compoundPrimaryKey/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter8/03-compoundPrimaryKey/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter8/04-embeddedCompoundPrimaryKey/build.xml b/examples/Chapter8/04-embeddedCompoundPrimaryKey/build.xml new file mode 100644 index 0000000..7d4b2ce --- /dev/null +++ b/examples/Chapter8/04-embeddedCompoundPrimaryKey/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter8/04-embeddedCompoundPrimaryKey/deploy.bat b/examples/Chapter8/04-embeddedCompoundPrimaryKey/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter8/04-embeddedCompoundPrimaryKey/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter8/04-embeddedCompoundPrimaryKey/etc/persistence/META-INF/persistence.xml b/examples/Chapter8/04-embeddedCompoundPrimaryKey/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..823691c --- /dev/null +++ b/examples/Chapter8/04-embeddedCompoundPrimaryKey/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/embeddedCompoundPrimaryKey + + + + + + \ No newline at end of file diff --git a/examples/Chapter8/04-embeddedCompoundPrimaryKey/etc/sql/db.sql b/examples/Chapter8/04-embeddedCompoundPrimaryKey/etc/sql/db.sql new file mode 100644 index 0000000..4a6607c --- /dev/null +++ b/examples/Chapter8/04-embeddedCompoundPrimaryKey/etc/sql/db.sql @@ -0,0 +1,4 @@ +DROP TABLE EMPLOYEE; + +CREATE TABLE EMPLOYEE (COUNTRY VARCHAR(255) NOT NULL, EMP_ID INTEGER NOT NULL, NAME VARCHAR(255), + SALARY BIGINT, PRIMARY KEY(COUNTRY,EMP_ID)); diff --git a/examples/Chapter8/04-embeddedCompoundPrimaryKey/etc/web/WEB-INF/web.xml b/examples/Chapter8/04-embeddedCompoundPrimaryKey/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter8/04-embeddedCompoundPrimaryKey/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/Chapter8/04-embeddedCompoundPrimaryKey/src/model/examples/model/Employee.java b/examples/Chapter8/04-embeddedCompoundPrimaryKey/src/model/examples/model/Employee.java new file mode 100644 index 0000000..7c67efc --- /dev/null +++ b/examples/Chapter8/04-embeddedCompoundPrimaryKey/src/model/examples/model/Employee.java @@ -0,0 +1,45 @@ +package examples.model; + +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; + +@Entity +public class Employee { + @EmbeddedId + private EmployeeId id; + private String name; + private long salary; + + public Employee() {} + public Employee(String country, int id) { + this.id = new EmployeeId(country, id); + } + + public int getId() { + return id.getId(); + } + + public String getCountry() { + return id.getCountry(); + } + + 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() + " country: " + getCountry(); + } +} diff --git a/examples/Chapter8/04-embeddedCompoundPrimaryKey/src/model/examples/model/EmployeeId.java b/examples/Chapter8/04-embeddedCompoundPrimaryKey/src/model/examples/model/EmployeeId.java new file mode 100644 index 0000000..24c5cc5 --- /dev/null +++ b/examples/Chapter8/04-embeddedCompoundPrimaryKey/src/model/examples/model/EmployeeId.java @@ -0,0 +1,32 @@ +package examples.model; + +import javax.persistence.Column; +import javax.persistence.Embeddable; + +@Embeddable +public class EmployeeId { + private String country; + @Column(name="EMP_ID") + private int id; + + public EmployeeId() {} + public EmployeeId(String country, int id) { + this.country = country; + this.id = id; + } + + + public String getCountry() { return country; } + public int getId() { return id; } + + public boolean equals(Object o) { + return ((o instanceof EmployeeId) && + country.equals(((EmployeeId)o).getCountry()) && + id == ((EmployeeId) o).getId()); + + } + + public int hashCode() { + return country.hashCode() + id; + } +} \ No newline at end of file diff --git a/examples/Chapter8/04-embeddedCompoundPrimaryKey/src/model/examples/stateless/EmployeeService.java b/examples/Chapter8/04-embeddedCompoundPrimaryKey/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..959a566 --- /dev/null +++ b/examples/Chapter8/04-embeddedCompoundPrimaryKey/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 createEmployee(String country, int id, + String name, long salary); + public Employee findEmployee(String country, int id); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter8/04-embeddedCompoundPrimaryKey/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter8/04-embeddedCompoundPrimaryKey/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..857f7f6 --- /dev/null +++ b/examples/Chapter8/04-embeddedCompoundPrimaryKey/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,42 @@ +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 country, int id, + String name, long salary) { + Employee emp = new Employee(country, id); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + + return emp; + } + + public Employee findEmployee(String country, int id) { + return (Employee) + em.createQuery("SELECT e " + + "FROM Employee e " + + "WHERE e.id.country = ?1 AND e.id.id = ?2") + .setParameter(1, country) + .setParameter(2, id) + .getSingleResult(); + } + + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter8/04-embeddedCompoundPrimaryKey/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter8/04-embeddedCompoundPrimaryKey/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..d29ca74 --- /dev/null +++ b/examples/Chapter8/04-embeddedCompoundPrimaryKey/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 8: Using Embedded Compound Primary Keys Example"; + + private final String DESCRIPTION = + "This example demonstates the basics of using embedded compound primary keys."; + + @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.createEmployee( + request.getParameter("country"), + parseInt(request.getParameter("empId")), + request.getParameter("name"), + parseLong(request.getParameter("salary"))); + } else if (action.equals("Find")) { + Employee emp = service.findEmployee( + request.getParameter("findCountry"), + parseInt(request.getParameter("findId"))); + out.print("Found " + emp + "
"); + } + + 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 and Employee + out.println("

Create an Employee

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

Find an Employee

"); + out.println(""); + out.println(""); + out.println("" + + ""); + out.println("
Employee Country:(String)
Employee Id:(int)
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter8/04-embeddedCompoundPrimaryKey/undeploy.bat b/examples/Chapter8/04-embeddedCompoundPrimaryKey/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter8/04-embeddedCompoundPrimaryKey/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter8/05-compoundJoinColumns/build.xml b/examples/Chapter8/05-compoundJoinColumns/build.xml new file mode 100644 index 0000000..79eb6c2 --- /dev/null +++ b/examples/Chapter8/05-compoundJoinColumns/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter8/05-compoundJoinColumns/deploy.bat b/examples/Chapter8/05-compoundJoinColumns/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter8/05-compoundJoinColumns/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter8/05-compoundJoinColumns/etc/persistence/META-INF/persistence.xml b/examples/Chapter8/05-compoundJoinColumns/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..2d2749e --- /dev/null +++ b/examples/Chapter8/05-compoundJoinColumns/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/compoundJoinColumns + + + + + + \ No newline at end of file diff --git a/examples/Chapter8/05-compoundJoinColumns/etc/sql/db.sql b/examples/Chapter8/05-compoundJoinColumns/etc/sql/db.sql new file mode 100644 index 0000000..c4273e9 --- /dev/null +++ b/examples/Chapter8/05-compoundJoinColumns/etc/sql/db.sql @@ -0,0 +1,18 @@ +DROP TABLE EMP_PROJECT; +DROP TABLE EMPLOYEE; +DROP TABLE PROJECT; + +CREATE TABLE PROJECT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (COUNTRY VARCHAR(255) NOT NULL, EMP_ID INTEGER NOT NULL, NAME VARCHAR(255), + SALARY BIGINT, MGR_COUNTRY VARCHAR(255), MGR_ID INTEGER, PRIMARY KEY(COUNTRY,EMP_ID), + CONSTRAINT MGR_FK FOREIGN KEY (MGR_COUNTRY,MGR_ID) REFERENCES EMPLOYEE (COUNTRY,EMP_ID)); +CREATE TABLE EMP_PROJECT (PROJECT_ID INTEGER NOT NULL, EMP_COUNTRY VARCHAR(255) NOT NULL, EMP_ID INTEGER NOT NULL, + CONSTRAINT PROJECT_FK FOREIGN KEY (PROJECT_ID) REFERENCES PROJECT (ID), + CONSTRAINT EMPLOYEE_FK FOREIGN KEY (EMP_COUNTRY,EMP_ID) REFERENCES EMPLOYEE (COUNTRY,EMP_ID), + PRIMARY KEY (PROJECT_ID,EMP_COUNTRY,EMP_ID)); + + +INSERT INTO PROJECT (ID, NAME) VALUES (4, 'Release3'); +INSERT INTO EMPLOYEE (COUNTRY, EMP_ID, NAME, SALARY, MGR_COUNTRY, MGR_ID) VALUES ('Canada', 1, 'John', 55000, NULL, NULL); +INSERT INTO EMPLOYEE (COUNTRY, EMP_ID, NAME, SALARY, MGR_COUNTRY, MGR_ID) VALUES ('Canada', 2, 'Paul', 55000, 'Canada', 1); +INSERT INTO EMP_PROJECT (PROJECT_ID, EMP_COUNTRY, EMP_ID) VALUES (4, 'Canada', 1); diff --git a/examples/Chapter8/05-compoundJoinColumns/etc/web/WEB-INF/web.xml b/examples/Chapter8/05-compoundJoinColumns/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter8/05-compoundJoinColumns/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/Chapter8/05-compoundJoinColumns/src/model/examples/model/Employee.java b/examples/Chapter8/05-compoundJoinColumns/src/model/examples/model/Employee.java new file mode 100644 index 0000000..e43df6b --- /dev/null +++ b/examples/Chapter8/05-compoundJoinColumns/src/model/examples/model/Employee.java @@ -0,0 +1,103 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.IdClass; +import javax.persistence.JoinColumn; +import javax.persistence.JoinColumns; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; + +@Entity +@IdClass(EmployeeId.class) +public class Employee { + @Id private String country; + @Id + @Column(name="EMP_ID") + private int id; + private String name; + private long salary; + + @ManyToOne + @JoinColumns({ + @JoinColumn(name="MGR_COUNTRY", referencedColumnName="COUNTRY"), + @JoinColumn(name="MGR_ID", referencedColumnName="EMP_ID") + }) + private Employee manager; + + @OneToMany(mappedBy="manager") + private Collection directs; + + @ManyToMany + @JoinTable( + name="EMP_PROJECT", + joinColumns={ + @JoinColumn(name="EMP_COUNTRY", referencedColumnName="COUNTRY"), + @JoinColumn(name="EMP_ID", referencedColumnName="EMP_ID")}, + inverseJoinColumns=@JoinColumn(name="PROJECT_ID")) + private Collection projects; + + public Employee() { + directs = new ArrayList(); + projects = new ArrayList(); + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + 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 getDirects() { + return directs; + } + + public Employee getManager() { + return manager; + } + + public void setManager(Employee manager) { + this.manager = manager; + } + + public Collection getProjects() { + return projects; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " country: " + getCountry(); + } +} diff --git a/examples/Chapter8/05-compoundJoinColumns/src/model/examples/model/EmployeeId.java b/examples/Chapter8/05-compoundJoinColumns/src/model/examples/model/EmployeeId.java new file mode 100644 index 0000000..031521a --- /dev/null +++ b/examples/Chapter8/05-compoundJoinColumns/src/model/examples/model/EmployeeId.java @@ -0,0 +1,28 @@ +package examples.model; + +import java.io.Serializable; + +public class EmployeeId implements Serializable { + private String country; + private int id; + + public EmployeeId() {} + public EmployeeId(String country, int id) { + this.country = country; + this.id = id; + } + + public String getCountry() { return country; } + public int getId() { return id; } + + public boolean equals(Object o) { + return ((o instanceof EmployeeId) && + country.equals(((EmployeeId)o).getCountry()) && + id == ((EmployeeId) o).getId()); + + } + + public int hashCode() { + return country.hashCode() + id; + } +} \ No newline at end of file diff --git a/examples/Chapter8/05-compoundJoinColumns/src/model/examples/model/Project.java b/examples/Chapter8/05-compoundJoinColumns/src/model/examples/model/Project.java new file mode 100644 index 0000000..3a049f1 --- /dev/null +++ b/examples/Chapter8/05-compoundJoinColumns/src/model/examples/model/Project.java @@ -0,0 +1,52 @@ +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") + 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/05-compoundJoinColumns/src/model/examples/stateless/EmployeeService.java b/examples/Chapter8/05-compoundJoinColumns/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..345ce8d --- /dev/null +++ b/examples/Chapter8/05-compoundJoinColumns/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,15 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; +import examples.model.Project; + +public interface EmployeeService { + public Employee createEmployee(String country, int id, + String name, long salary); + public void setEmployeeManager(String country, int id, String mgrCountry, int mgrId); + public void addEmployeeProject(String country, int id, int projId); + public Collection findAllEmployees(); + public Collection findAllProjects(); +} diff --git a/examples/Chapter8/05-compoundJoinColumns/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter8/05-compoundJoinColumns/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..aa05651 --- /dev/null +++ b/examples/Chapter8/05-compoundJoinColumns/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,58 @@ +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.EmployeeId; +import examples.model.Project; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String country, int id, + String name, long salary) { + Employee emp = new Employee(); + emp.setCountry(country); + emp.setId(id); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + + return emp; + } + + public void setEmployeeManager(String country, int id, String mgrCountry, int mgrId) { + Employee emp = findEmployee(country, id); + Employee mgr = findEmployee(mgrCountry, mgrId); + emp.setManager(mgr); + mgr.getDirects().add(emp); + } + + public void addEmployeeProject(String country, int id, int projId) { + Employee emp = findEmployee(country, id); + Project proj = em.find(Project.class, projId); + emp.getProjects().add(proj); + proj.getEmployees().add(emp); + } + + public Employee findEmployee(String country, int id) { + return em.find(Employee.class, new EmployeeId(country, id)); + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } + + public Collection findAllProjects() { + Query query = em.createQuery("SELECT p FROM Project p"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter8/05-compoundJoinColumns/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter8/05-compoundJoinColumns/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..c3ce3d4 --- /dev/null +++ b/examples/Chapter8/05-compoundJoinColumns/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,132 @@ +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.model.Project; +import examples.stateless.EmployeeService; + +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 8: Using Compound Join Columns Example"; + + private final String DESCRIPTION = + "This example demonstates the basics of using compound join columns."; + + @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.createEmployee( + request.getParameter("country"), + parseInt(request.getParameter("empId")), + request.getParameter("name"), + parseLong(request.getParameter("salary"))); + } else if (action.equals("SetManager")) { + service.setEmployeeManager( + request.getParameter("empCountry"), + parseInt(request.getParameter("empId")), + request.getParameter("mgrCountry"), + parseInt(request.getParameter("mgrId"))); + } else if (action.equals("AddEmployeeProject")) { + service.addEmployeeProject( + request.getParameter("empCountry2"), + parseInt(request.getParameter("empId2")), + parseInt(request.getParameter("projId"))); + } + + out.println("Employees:
"); + for (Employee emp : service.findAllEmployees()) { + out.print(emp + " " + emp.getProjects().size() + "
"); + out.print(emp + " " + emp.getManager() + "
"); + } + + out.println("
Projects:
"); + for (Project p : service.findAllProjects()) { + out.print(p + " " + p.getEmployees().size() + "
"); + } + 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 + out.println("

Create an Employee

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

Set Employee Manager

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

Add Employee Project

"); + out.println(""); + out.println(""); + out.println(""); + out.println("" + + ""); + out.println("
Employee Country:(String)
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/Chapter8/05-compoundJoinColumns/undeploy.bat b/examples/Chapter8/05-compoundJoinColumns/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter8/05-compoundJoinColumns/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter8/06-idContainingRelationship/build.xml b/examples/Chapter8/06-idContainingRelationship/build.xml new file mode 100644 index 0000000..60a3c8d --- /dev/null +++ b/examples/Chapter8/06-idContainingRelationship/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter8/06-idContainingRelationship/deploy.bat b/examples/Chapter8/06-idContainingRelationship/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter8/06-idContainingRelationship/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter8/06-idContainingRelationship/etc/persistence/META-INF/persistence.xml b/examples/Chapter8/06-idContainingRelationship/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..56e66c7 --- /dev/null +++ b/examples/Chapter8/06-idContainingRelationship/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/idContainingRelationship + + + + + + \ No newline at end of file diff --git a/examples/Chapter8/06-idContainingRelationship/etc/sql/db.sql b/examples/Chapter8/06-idContainingRelationship/etc/sql/db.sql new file mode 100644 index 0000000..ee4de60 --- /dev/null +++ b/examples/Chapter8/06-idContainingRelationship/etc/sql/db.sql @@ -0,0 +1,10 @@ +DROP TABLE PROJECT; +DROP TABLE DEPARTMENT; + +CREATE TABLE DEPARTMENT(ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY(ID)); +CREATE TABLE PROJECT (DEPT_ID INTEGER NOT NULL, NAME VARCHAR(255) NOT NULL, + START_DATE DATE, END_DATE DATE, PRIMARY KEY(DEPT_ID,NAME), + CONSTRAINT DEPT_FK FOREIGN KEY (DEPT_ID) REFERENCES DEPARTMENT(ID)); + +INSERT INTO DEPARTMENT(ID, NAME) VALUES (1, 'Engineering'); +INSERT INTO PROJECT (DEPT_ID, NAME, START_DATE, END_DATE) VALUES (1, 'Release3', {d '2002-12-05'}, {d '2002-08-06'}); diff --git a/examples/Chapter8/06-idContainingRelationship/etc/web/WEB-INF/web.xml b/examples/Chapter8/06-idContainingRelationship/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..2adc48a --- /dev/null +++ b/examples/Chapter8/06-idContainingRelationship/etc/web/WEB-INF/web.xml @@ -0,0 +1,16 @@ + + + + ProjectServiceServlet + examples.servlet.ProjectServiceServlet + + + + ProjectServiceServlet + /ProjectServiceServlet + + + \ No newline at end of file diff --git a/examples/Chapter8/06-idContainingRelationship/src/model/examples/model/Department.java b/examples/Chapter8/06-idContainingRelationship/src/model/examples/model/Department.java new file mode 100644 index 0000000..fc5f1ca --- /dev/null +++ b/examples/Chapter8/06-idContainingRelationship/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 projects; + + public Department() { + 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 deptName) { + this.name = deptName; + } + + public Collection getProjects() { + return projects; + } + + public String toString() { + return "Department id: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter8/06-idContainingRelationship/src/model/examples/model/Project.java b/examples/Chapter8/06-idContainingRelationship/src/model/examples/model/Project.java new file mode 100644 index 0000000..443c46e --- /dev/null +++ b/examples/Chapter8/06-idContainingRelationship/src/model/examples/model/Project.java @@ -0,0 +1,74 @@ +package examples.model; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.IdClass; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@IdClass(ProjectId.class) +public class Project { + @Id + @Column(name="DEPT_ID", insertable=false, updatable=false) + private int deptId; + @Id private String name; + + @ManyToOne + @JoinColumn(name="DEPT_ID") + private Department department; + + @Temporal(TemporalType.DATE) + @Column(name="START_DATE") + private Date startDate; + @Temporal(TemporalType.DATE) + @Column(name="END_DATE") + private Date endDate; + + public Project() {} + public Project(Department dept) { + this.department = dept; + this.deptId = dept.getId(); + } + + public String getName() { + return name; + } + + public void setName(String projectName) { + this.name = projectName; + } + + public int getDeptId() { + return deptId; + } + + public Department getDepartment() { + return department; + } + + public Date getEndDate() { + return endDate; + } + + public void setEndDate(Date endDate) { + this.endDate = endDate; + } + + public Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public String toString() { + return "Project name: " + getName(); + } +} diff --git a/examples/Chapter8/06-idContainingRelationship/src/model/examples/model/ProjectId.java b/examples/Chapter8/06-idContainingRelationship/src/model/examples/model/ProjectId.java new file mode 100644 index 0000000..ed42813 --- /dev/null +++ b/examples/Chapter8/06-idContainingRelationship/src/model/examples/model/ProjectId.java @@ -0,0 +1,33 @@ +package examples.model; + +import java.io.Serializable; + +public class ProjectId implements Serializable { + private int deptId; + private String name; + + public ProjectId() {} + public ProjectId(int deptId, String name) { + this.deptId = deptId; + this.name = name; + } + + public String getName() { + return name; + } + + public int getId() { + return deptId; + } + + public boolean equals(Object o) { + return ((o instanceof ProjectId) && + name.equals(((ProjectId) o).getName()) && + deptId == ((ProjectId) o).getId()); + + } + + public int hashCode() { + return name.hashCode() + deptId; + } +} \ No newline at end of file diff --git a/examples/Chapter8/06-idContainingRelationship/src/model/examples/stateless/ProjectService.java b/examples/Chapter8/06-idContainingRelationship/src/model/examples/stateless/ProjectService.java new file mode 100644 index 0000000..06ac4ee --- /dev/null +++ b/examples/Chapter8/06-idContainingRelationship/src/model/examples/stateless/ProjectService.java @@ -0,0 +1,12 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Department; +import examples.model.Project; + +public interface ProjectService { + public Project createProject(String name, int deptId); + public Collection findAllProjects(); + public Collection findAllDepartments(); +} diff --git a/examples/Chapter8/06-idContainingRelationship/src/model/examples/stateless/ProjectServiceBean.java b/examples/Chapter8/06-idContainingRelationship/src/model/examples/stateless/ProjectServiceBean.java new file mode 100644 index 0000000..65ceffe --- /dev/null +++ b/examples/Chapter8/06-idContainingRelationship/src/model/examples/stateless/ProjectServiceBean.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.Department; +import examples.model.Project; + +@Stateless +public class ProjectServiceBean implements ProjectService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Project createProject(String name, int deptId) { + Project proj = new Project(findDepartment(deptId)); + proj.setName(name); + em.persist(proj); + + return proj; + } + + public Department findDepartment(int id) { + return em.find(Department.class, id); + } + + public Collection findAllProjects() { + Query query = em.createQuery("SELECT p FROM Project p"); + return (Collection) query.getResultList(); + } + + public Collection findAllDepartments() { + Query query = em.createQuery("SELECT d FROM Department d"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter8/06-idContainingRelationship/src/servlet/examples/servlet/ProjectServiceServlet.java b/examples/Chapter8/06-idContainingRelationship/src/servlet/examples/servlet/ProjectServiceServlet.java new file mode 100644 index 0000000..b76596b --- /dev/null +++ b/examples/Chapter8/06-idContainingRelationship/src/servlet/examples/servlet/ProjectServiceServlet.java @@ -0,0 +1,91 @@ +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.Department; +import examples.model.Project; +import examples.stateless.ProjectService; + +public class ProjectServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 8: Using IDs Containing Relationships Example"; + + private final String DESCRIPTION = + "This example demonstates the basics of using primary keys that include relationships."; + + @EJB ProjectService 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")) { + Project proj = service.createProject( + request.getParameter("name"), + parseInt(request.getParameter("deptId"))); + out.print("Created" + proj + "
"); + } + + out.println("Project:
"); + for (Project p : service.findAllProjects()) { + out.print(p + " " + p.getDepartment() + "
"); + } + + out.println("
Departments:
"); + for (Department d : service.findAllDepartments()) { + out.print(d + " " + d.getProjects().size() + "
"); + } + + 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 + out.println("

Create a Project

"); + out.println(""); + out.println(""); + out.println("" + + ""); + out.println("
Project Name:(String)
Department Id:(int)
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter8/06-idContainingRelationship/undeploy.bat b/examples/Chapter8/06-idContainingRelationship/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter8/06-idContainingRelationship/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter8/07-mappingRelationshipState/build.xml b/examples/Chapter8/07-mappingRelationshipState/build.xml new file mode 100644 index 0000000..7be9d77 --- /dev/null +++ b/examples/Chapter8/07-mappingRelationshipState/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter8/07-mappingRelationshipState/deploy.bat b/examples/Chapter8/07-mappingRelationshipState/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter8/07-mappingRelationshipState/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter8/07-mappingRelationshipState/etc/persistence/META-INF/persistence.xml b/examples/Chapter8/07-mappingRelationshipState/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..40f87a0 --- /dev/null +++ b/examples/Chapter8/07-mappingRelationshipState/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/mappingRelationshipState + + + + + + \ No newline at end of file diff --git a/examples/Chapter8/07-mappingRelationshipState/etc/sql/db.sql b/examples/Chapter8/07-mappingRelationshipState/etc/sql/db.sql new file mode 100644 index 0000000..22f599c --- /dev/null +++ b/examples/Chapter8/07-mappingRelationshipState/etc/sql/db.sql @@ -0,0 +1,16 @@ +DROP TABLE EMP_PROJECT; +DROP TABLE EMPLOYEE; +DROP TABLE PROJECT; + +CREATE TABLE PROJECT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, PRIMARY KEY(ID)); +CREATE TABLE EMP_PROJECT (PROJECT_ID INTEGER NOT NULL, EMP_ID INTEGER NOT NULL, START_DATE DATE, + CONSTRAINT PROJECT_FK FOREIGN KEY (PROJECT_ID) REFERENCES PROJECT (ID), + CONSTRAINT EMPLOYEE_FK FOREIGN KEY (EMP_ID) REFERENCES EMPLOYEE (ID), + PRIMARY KEY (PROJECT_ID,EMP_ID)); + + +INSERT INTO PROJECT (ID, NAME) VALUES (3, 'Release2'); +INSERT INTO PROJECT (ID, NAME) VALUES (4, 'Release3'); +INSERT INTO EMPLOYEE (ID, NAME, SALARY) VALUES (1, 'John', 55000); +INSERT INTO EMP_PROJECT (PROJECT_ID, EMP_ID, START_DATE) VALUES (4, 1, {d '2002-08-06'}); diff --git a/examples/Chapter8/07-mappingRelationshipState/etc/web/WEB-INF/web.xml b/examples/Chapter8/07-mappingRelationshipState/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter8/07-mappingRelationshipState/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/Chapter8/07-mappingRelationshipState/src/model/examples/model/Employee.java b/examples/Chapter8/07-mappingRelationshipState/src/model/examples/model/Employee.java new file mode 100644 index 0000000..c81e0f7 --- /dev/null +++ b/examples/Chapter8/07-mappingRelationshipState/src/model/examples/model/Employee.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.OneToMany; + +@Entity +public class Employee { + @Id private int id; + + private String name; + private long salary; + + @OneToMany(mappedBy="employee") + private Collection assignments; + + public Employee() { + assignments = 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 Collection getAssignments() { + return assignments; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter8/07-mappingRelationshipState/src/model/examples/model/Project.java b/examples/Chapter8/07-mappingRelationshipState/src/model/examples/model/Project.java new file mode 100644 index 0000000..cb83e25 --- /dev/null +++ b/examples/Chapter8/07-mappingRelationshipState/src/model/examples/model/Project.java @@ -0,0 +1,47 @@ +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 Project { + @Id private int id; + private String name; + + @OneToMany(mappedBy="project") + private Collection assignments; + + public Project() { + assignments = 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 getAssignments() { + return assignments; + } + + public String toString() { + return getClass().getName().substring(getClass().getName().lastIndexOf('.')+1) + + " no: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter8/07-mappingRelationshipState/src/model/examples/model/ProjectAssignment.java b/examples/Chapter8/07-mappingRelationshipState/src/model/examples/model/ProjectAssignment.java new file mode 100644 index 0000000..6e7662e --- /dev/null +++ b/examples/Chapter8/07-mappingRelationshipState/src/model/examples/model/ProjectAssignment.java @@ -0,0 +1,69 @@ +package examples.model; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.IdClass; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@Table(name="EMP_PROJECT") +@IdClass(ProjectAssignmentId.class) +public class ProjectAssignment { + @Id + @Column(name="EMP_ID", insertable=false, updatable=false) + private int empId; + @Id + @Column(name="PROJECT_ID", insertable=false, updatable=false) + private int projectId; + + @ManyToOne + @JoinColumn(name="EMP_ID") + Employee employee; + @ManyToOne + @JoinColumn(name="PROJECT_ID") + Project project; + + @Temporal(TemporalType.DATE) + @Column(name="START_DATE", updatable=false) + private Date startDate; + + public ProjectAssignment() {} + public ProjectAssignment(Employee emp, Project proj) { + this.empId = emp.getId(); + this.employee = emp; + this.projectId = proj.getId(); + this.project = proj; + } + + public int getEmpId() { + return empId; + } + + public Employee getEmployee() { + return employee; + } + + public int getProjectId() { + return projectId; + } + + public Project getProject() { + return project; + } + + public Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } +} + diff --git a/examples/Chapter8/07-mappingRelationshipState/src/model/examples/model/ProjectAssignmentId.java b/examples/Chapter8/07-mappingRelationshipState/src/model/examples/model/ProjectAssignmentId.java new file mode 100644 index 0000000..68175e7 --- /dev/null +++ b/examples/Chapter8/07-mappingRelationshipState/src/model/examples/model/ProjectAssignmentId.java @@ -0,0 +1,32 @@ +package examples.model; + +import java.io.Serializable; + +public class ProjectAssignmentId implements Serializable { + private int empId; + private int projectId; + + public ProjectAssignmentId() {} + public ProjectAssignmentId(int empId, int projectId) { + this.empId = empId; + this.projectId = projectId; + } + + public int getEmpId() { + return empId; + } + + public int getProjectId() { + return projectId; + } + + public boolean equals(Object o) { + return ((o instanceof ProjectAssignmentId) && + empId == ((ProjectAssignmentId)o).getEmpId() && + projectId == ((ProjectAssignmentId) o).getProjectId()); + } + + public int hashCode() { + return empId + projectId; + } +} diff --git a/examples/Chapter8/07-mappingRelationshipState/src/model/examples/stateless/EmployeeService.java b/examples/Chapter8/07-mappingRelationshipState/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..18eedce --- /dev/null +++ b/examples/Chapter8/07-mappingRelationshipState/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,14 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; +import examples.model.Project; + +public interface EmployeeService { + public Employee createEmployee(String country, int id, + String name, long salary); + public void addEmployeeProject(int id, int projId); + public Collection findAllEmployees(); + public Collection findAllProjects(); +} diff --git a/examples/Chapter8/07-mappingRelationshipState/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter8/07-mappingRelationshipState/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..6c04145 --- /dev/null +++ b/examples/Chapter8/07-mappingRelationshipState/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,54 @@ +package examples.stateless; + +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; +import examples.model.Project; +import examples.model.ProjectAssignment; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String country, 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 void addEmployeeProject(int id, int projId) { + Employee emp = findEmployee(id); + Project proj = em.find(Project.class, projId); + ProjectAssignment assign = new ProjectAssignment(emp, proj); + assign.setStartDate(new Date()); + em.persist(assign); + emp.getAssignments().add(assign); + proj.getAssignments().add(assign); + } + + 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(); + } + + public Collection findAllProjects() { + Query query = em.createQuery("SELECT p FROM Project p"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter8/07-mappingRelationshipState/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter8/07-mappingRelationshipState/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..95c6660 --- /dev/null +++ b/examples/Chapter8/07-mappingRelationshipState/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,113 @@ +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.model.Project; +import examples.stateless.EmployeeService; + +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 8: Using Relationships with state Example"; + + private final String DESCRIPTION = + "This example demonstates the basics of mapping relationships that contain state."; + + @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.createEmployee( + request.getParameter("country"), + parseInt(request.getParameter("empId")), + request.getParameter("name"), + parseLong(request.getParameter("salary"))); + } else if (action.equals("AddEmployeeProject")) { + service.addEmployeeProject( + parseInt(request.getParameter("empId2")), + parseInt(request.getParameter("projId"))); + } + + out.println("Employees:
"); + for (Employee emp : service.findAllEmployees()) { + out.print(emp + " with " + emp.getAssignments().size() + " assignments
"); + } + + out.println("
Projects:
"); + for (Project p : service.findAllProjects()) { + out.print(p + " with " + p.getAssignments().size() + " assignments
"); + } + 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 + out.println("

Create an Employee

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

Add Employee 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/Chapter8/07-mappingRelationshipState/undeploy.bat b/examples/Chapter8/07-mappingRelationshipState/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter8/07-mappingRelationshipState/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter8/08-multipleTables/build.xml b/examples/Chapter8/08-multipleTables/build.xml new file mode 100644 index 0000000..221e807 --- /dev/null +++ b/examples/Chapter8/08-multipleTables/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter8/08-multipleTables/deploy.bat b/examples/Chapter8/08-multipleTables/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter8/08-multipleTables/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter8/08-multipleTables/etc/persistence/META-INF/persistence.xml b/examples/Chapter8/08-multipleTables/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..00781e4 --- /dev/null +++ b/examples/Chapter8/08-multipleTables/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/multipleTables + + + + + + \ No newline at end of file diff --git a/examples/Chapter8/08-multipleTables/etc/sql/db.sql b/examples/Chapter8/08-multipleTables/etc/sql/db.sql new file mode 100644 index 0000000..4e065b2 --- /dev/null +++ b/examples/Chapter8/08-multipleTables/etc/sql/db.sql @@ -0,0 +1,6 @@ +DROP TABLE EMP; +DROP TABLE EMP_ADDRESS; + +CREATE TABLE EMP (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, PRIMARY KEY (ID)); +CREATE TABLE EMP_ADDRESS (EMP_ID INTEGER NOT NULL, STREET VARCHAR(255), + CITY VARCHAR(255), STATE VARCHAR(255), ZIP_CODE VARCHAR(255), PRIMARY KEY (EMP_ID)); diff --git a/examples/Chapter8/08-multipleTables/etc/web/WEB-INF/web.xml b/examples/Chapter8/08-multipleTables/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter8/08-multipleTables/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/Chapter8/08-multipleTables/src/model/examples/model/Employee.java b/examples/Chapter8/08-multipleTables/src/model/examples/model/Employee.java new file mode 100644 index 0000000..8484462 --- /dev/null +++ b/examples/Chapter8/08-multipleTables/src/model/examples/model/Employee.java @@ -0,0 +1,87 @@ +package examples.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.PrimaryKeyJoinColumn; +import javax.persistence.SecondaryTable; +import javax.persistence.Table; + +@Entity +@Table(name="EMP") +@SecondaryTable(name="EMP_ADDRESS", + pkJoinColumns=@PrimaryKeyJoinColumn(name="EMP_ID")) +public class Employee { + @Id private int id; + private String name; + private long salary; + @Column(table="EMP_ADDRESS") + private String street; + @Column(table="EMP_ADDRESS") + private String city; + @Column(table="EMP_ADDRESS") + private String state; + @Column(name="ZIP_CODE", table="EMP_ADDRESS") + private String zip; + + + 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 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 getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getZip() { + return zip; + } + + public void setZip(String zip) { + this.zip = zip; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter8/08-multipleTables/src/model/examples/stateless/EmployeeService.java b/examples/Chapter8/08-multipleTables/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..a63a3a2 --- /dev/null +++ b/examples/Chapter8/08-multipleTables/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/Chapter8/08-multipleTables/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter8/08-multipleTables/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..ceb8800 --- /dev/null +++ b/examples/Chapter8/08-multipleTables/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 javax.persistence.Query; + +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); + emp.setStreet(street); + emp.setCity(city); + emp.setState(state); + emp.setZip(zip); + 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/Chapter8/08-multipleTables/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter8/08-multipleTables/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..6e6419f --- /dev/null +++ b/examples/Chapter8/08-multipleTables/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 8: Using Multiple Tables Example"; + + private final String DESCRIPTION = + "This example demonstates the basics of using multiple tables for an Entity."; + + @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/Chapter8/08-multipleTables/undeploy.bat b/examples/Chapter8/08-multipleTables/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter8/08-multipleTables/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter8/09-embeddedObjectsMultipleTables/build.xml b/examples/Chapter8/09-embeddedObjectsMultipleTables/build.xml new file mode 100644 index 0000000..d51ac37 --- /dev/null +++ b/examples/Chapter8/09-embeddedObjectsMultipleTables/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter8/09-embeddedObjectsMultipleTables/deploy.bat b/examples/Chapter8/09-embeddedObjectsMultipleTables/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter8/09-embeddedObjectsMultipleTables/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter8/09-embeddedObjectsMultipleTables/etc/persistence/META-INF/persistence.xml b/examples/Chapter8/09-embeddedObjectsMultipleTables/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..6ce397c --- /dev/null +++ b/examples/Chapter8/09-embeddedObjectsMultipleTables/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/embeddedObjectsMultipleTables + + + + + + \ No newline at end of file diff --git a/examples/Chapter8/09-embeddedObjectsMultipleTables/etc/sql/db.sql b/examples/Chapter8/09-embeddedObjectsMultipleTables/etc/sql/db.sql new file mode 100644 index 0000000..4e065b2 --- /dev/null +++ b/examples/Chapter8/09-embeddedObjectsMultipleTables/etc/sql/db.sql @@ -0,0 +1,6 @@ +DROP TABLE EMP; +DROP TABLE EMP_ADDRESS; + +CREATE TABLE EMP (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, PRIMARY KEY (ID)); +CREATE TABLE EMP_ADDRESS (EMP_ID INTEGER NOT NULL, STREET VARCHAR(255), + CITY VARCHAR(255), STATE VARCHAR(255), ZIP_CODE VARCHAR(255), PRIMARY KEY (EMP_ID)); diff --git a/examples/Chapter8/09-embeddedObjectsMultipleTables/etc/web/WEB-INF/web.xml b/examples/Chapter8/09-embeddedObjectsMultipleTables/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter8/09-embeddedObjectsMultipleTables/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/Chapter8/09-embeddedObjectsMultipleTables/src/model/examples/model/Address.java b/examples/Chapter8/09-embeddedObjectsMultipleTables/src/model/examples/model/Address.java new file mode 100644 index 0000000..bfcb26b --- /dev/null +++ b/examples/Chapter8/09-embeddedObjectsMultipleTables/src/model/examples/model/Address.java @@ -0,0 +1,52 @@ +package examples.model; + +import javax.persistence.Column; +import javax.persistence.Embeddable; + +@Embeddable +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/Chapter8/09-embeddedObjectsMultipleTables/src/model/examples/model/Employee.java b/examples/Chapter8/09-embeddedObjectsMultipleTables/src/model/examples/model/Employee.java new file mode 100644 index 0000000..8746e2c --- /dev/null +++ b/examples/Chapter8/09-embeddedObjectsMultipleTables/src/model/examples/model/Employee.java @@ -0,0 +1,68 @@ +package examples.model; + +import javax.persistence.AttributeOverride; +import javax.persistence.AttributeOverrides; +import javax.persistence.Column; +import javax.persistence.Embedded; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.PrimaryKeyJoinColumn; +import javax.persistence.SecondaryTable; +import javax.persistence.Table; + +@Entity +@Table(name="EMP") +@SecondaryTable(name="EMP_ADDRESS", + pkJoinColumns=@PrimaryKeyJoinColumn(name="EMP_ID")) +public class Employee { + @Id private int id; + private String name; + private long salary; + @Embedded + @AttributeOverrides({ + @AttributeOverride(name="street", column=@Column(table="EMP_ADDRESS")), + @AttributeOverride(name="city", column=@Column(name="CITY", table="EMP_ADDRESS")), + @AttributeOverride(name="state", column=@Column(name="STATE", table="EMP_ADDRESS")), + @AttributeOverride(name="zip", + column=@Column(name="ZIP_CODE", table="EMP_ADDRESS")) + }) + 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() + + " with " + getAddress(); + } +} diff --git a/examples/Chapter8/09-embeddedObjectsMultipleTables/src/model/examples/stateless/EmployeeService.java b/examples/Chapter8/09-embeddedObjectsMultipleTables/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..a63a3a2 --- /dev/null +++ b/examples/Chapter8/09-embeddedObjectsMultipleTables/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/Chapter8/09-embeddedObjectsMultipleTables/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter8/09-embeddedObjectsMultipleTables/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..a361287 --- /dev/null +++ b/examples/Chapter8/09-embeddedObjectsMultipleTables/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.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/Chapter8/09-embeddedObjectsMultipleTables/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter8/09-embeddedObjectsMultipleTables/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..d254fee --- /dev/null +++ b/examples/Chapter8/09-embeddedObjectsMultipleTables/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 8: Using Embedded Objects with Multiple Tables Example"; + + private final String DESCRIPTION = + "This example demonstates the basics of using embedded objects with multiple tables."; + + @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/Chapter8/09-embeddedObjectsMultipleTables/undeploy.bat b/examples/Chapter8/09-embeddedObjectsMultipleTables/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter8/09-embeddedObjectsMultipleTables/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter8/10-multipleTableCompoundPrimaryKey/build.xml b/examples/Chapter8/10-multipleTableCompoundPrimaryKey/build.xml new file mode 100644 index 0000000..0cdb7f9 --- /dev/null +++ b/examples/Chapter8/10-multipleTableCompoundPrimaryKey/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter8/10-multipleTableCompoundPrimaryKey/deploy.bat b/examples/Chapter8/10-multipleTableCompoundPrimaryKey/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter8/10-multipleTableCompoundPrimaryKey/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter8/10-multipleTableCompoundPrimaryKey/etc/persistence/META-INF/persistence.xml b/examples/Chapter8/10-multipleTableCompoundPrimaryKey/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..1f5e804 --- /dev/null +++ b/examples/Chapter8/10-multipleTableCompoundPrimaryKey/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/multipleTableCompoundPrimaryKey + + + + + + \ No newline at end of file diff --git a/examples/Chapter8/10-multipleTableCompoundPrimaryKey/etc/sql/db.sql b/examples/Chapter8/10-multipleTableCompoundPrimaryKey/etc/sql/db.sql new file mode 100644 index 0000000..ec038e4 --- /dev/null +++ b/examples/Chapter8/10-multipleTableCompoundPrimaryKey/etc/sql/db.sql @@ -0,0 +1,20 @@ +DROP TABLE ORG_STRUCTURE; +DROP TABLE EMP_LOB; +DROP TABLE EMPLOYEE; + +CREATE TABLE EMPLOYEE (COUNTRY VARCHAR(255) NOT NULL, EMP_ID INTEGER NOT NULL, NAME VARCHAR(255), + SALARY BIGINT, PRIMARY KEY(COUNTRY,EMP_ID)); +CREATE TABLE EMP_LOB (COUNTRY VARCHAR(255) NOT NULL, ID INTEGER NOT NULL, PHOTO BLOB, COMMENTS CLOB, + PRIMARY KEY(COUNTRY,ID), + CONSTRAINT EMPLOYEE_FK FOREIGN KEY (COUNTRY,ID) REFERENCES EMPLOYEE (COUNTRY,EMP_ID)); +CREATE TABLE ORG_STRUCTURE (COUNTRY VARCHAR(255) NOT NULL, EMP_ID INTEGER NOT NULL, + MGR_COUNTRY VARCHAR(255), MGR_ID INTEGER, PRIMARY KEY(COUNTRY,EMP_ID), + CONSTRAINT MGR_FK FOREIGN KEY (MGR_COUNTRY,MGR_ID) REFERENCES EMPLOYEE (COUNTRY,EMP_ID), + CONSTRAINT EMPLOYEE_FK2 FOREIGN KEY (COUNTRY,EMP_ID) REFERENCES EMPLOYEE (COUNTRY,EMP_ID)); + +INSERT INTO EMPLOYEE (COUNTRY, EMP_ID, NAME, SALARY) VALUES ('Canada', 1, 'John', 55000); +INSERT INTO EMPLOYEE (COUNTRY, EMP_ID, NAME, SALARY) VALUES ('Canada', 2, 'Paul', 55000); +INSERT INTO EMP_LOB (COUNTRY, ID, PHOTO, COMMENTS) VALUES ('Canada', 1, NULL, NULL); +INSERT INTO EMP_LOB (COUNTRY, ID, PHOTO, COMMENTS) VALUES ('Canada', 2, NULL, NULL); +INSERT INTO ORG_STRUCTURE (COUNTRY, EMP_ID, MGR_COUNTRY, MGR_ID) VALUES ('Canada', 1, NULL, NULL); +INSERT INTO ORG_STRUCTURE (COUNTRY, EMP_ID, MGR_COUNTRY, MGR_ID) VALUES ('Canada', 2, 'Canada', 1); diff --git a/examples/Chapter8/10-multipleTableCompoundPrimaryKey/etc/web/WEB-INF/web.xml b/examples/Chapter8/10-multipleTableCompoundPrimaryKey/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter8/10-multipleTableCompoundPrimaryKey/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/Chapter8/10-multipleTableCompoundPrimaryKey/src/model/examples/model/Employee.java b/examples/Chapter8/10-multipleTableCompoundPrimaryKey/src/model/examples/model/Employee.java new file mode 100644 index 0000000..db2b4ab --- /dev/null +++ b/examples/Chapter8/10-multipleTableCompoundPrimaryKey/src/model/examples/model/Employee.java @@ -0,0 +1,113 @@ +package examples.model; + +import javax.persistence.Basic; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.Id; +import javax.persistence.IdClass; +import javax.persistence.JoinColumn; +import javax.persistence.JoinColumns; +import javax.persistence.Lob; +import javax.persistence.ManyToOne; +import javax.persistence.PrimaryKeyJoinColumn; +import javax.persistence.SecondaryTable; +import javax.persistence.SecondaryTables; + +@Entity +@IdClass(EmployeeId.class) +@SecondaryTables({ + @SecondaryTable(name="ORG_STRUCTURE", pkJoinColumns={ + @PrimaryKeyJoinColumn(name="COUNTRY", referencedColumnName="COUNTRY"), + @PrimaryKeyJoinColumn(name="EMP_ID", referencedColumnName="EMP_ID")}), + @SecondaryTable(name="EMP_LOB", pkJoinColumns={ + @PrimaryKeyJoinColumn(name="COUNTRY", referencedColumnName="COUNTRY"), + @PrimaryKeyJoinColumn(name="ID", referencedColumnName="EMP_ID")}) +}) +public class Employee { + @Id private String country; + @Id + @Column(name="EMP_ID") + private int id; + private String name; + private long salary; + @Basic(fetch=FetchType.LAZY) + @Lob + @Column(table="EMP_LOB") + private byte[] photo; + + @Basic(fetch=FetchType.LAZY) + @Lob + @Column(table="EMP_LOB") + private char[] comments; + + @ManyToOne + @JoinColumns({ + @JoinColumn(name="MGR_COUNTRY", referencedColumnName="COUNTRY", + table="ORG_STRUCTURE"), + @JoinColumn(name="MGR_ID", referencedColumnName="EMP_ID", + table="ORG_STRUCTURE") + }) + private Employee manager; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + 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 char[] getComments() { + return comments; + } + + public void setComments(char[] comments) { + this.comments = comments; + } + + public Employee getManager() { + return manager; + } + + public void setManager(Employee manager) { + this.manager = manager; + } + + public byte[] getPhoto() { + return photo; + } + + public void setPhoto(byte[] photo) { + this.photo = photo; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " country: " + getCountry(); + } +} diff --git a/examples/Chapter8/10-multipleTableCompoundPrimaryKey/src/model/examples/model/EmployeeId.java b/examples/Chapter8/10-multipleTableCompoundPrimaryKey/src/model/examples/model/EmployeeId.java new file mode 100644 index 0000000..031521a --- /dev/null +++ b/examples/Chapter8/10-multipleTableCompoundPrimaryKey/src/model/examples/model/EmployeeId.java @@ -0,0 +1,28 @@ +package examples.model; + +import java.io.Serializable; + +public class EmployeeId implements Serializable { + private String country; + private int id; + + public EmployeeId() {} + public EmployeeId(String country, int id) { + this.country = country; + this.id = id; + } + + public String getCountry() { return country; } + public int getId() { return id; } + + public boolean equals(Object o) { + return ((o instanceof EmployeeId) && + country.equals(((EmployeeId)o).getCountry()) && + id == ((EmployeeId) o).getId()); + + } + + public int hashCode() { + return country.hashCode() + id; + } +} \ No newline at end of file diff --git a/examples/Chapter8/10-multipleTableCompoundPrimaryKey/src/model/examples/stateless/EmployeeService.java b/examples/Chapter8/10-multipleTableCompoundPrimaryKey/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..959a566 --- /dev/null +++ b/examples/Chapter8/10-multipleTableCompoundPrimaryKey/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 createEmployee(String country, int id, + String name, long salary); + public Employee findEmployee(String country, int id); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter8/10-multipleTableCompoundPrimaryKey/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter8/10-multipleTableCompoundPrimaryKey/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..02a1ae5 --- /dev/null +++ b/examples/Chapter8/10-multipleTableCompoundPrimaryKey/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.EmployeeId; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public Employee createEmployee(String country, int id, + String name, long salary) { + Employee emp = new Employee(); + emp.setCountry(country); + emp.setId(id); + emp.setName(name); + emp.setSalary(salary); + em.persist(emp); + + return emp; + } + + public Employee findEmployee(String country, int id) { + return em.find(Employee.class, new EmployeeId(country, id)); + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter8/10-multipleTableCompoundPrimaryKey/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter8/10-multipleTableCompoundPrimaryKey/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..397cf38 --- /dev/null +++ b/examples/Chapter8/10-multipleTableCompoundPrimaryKey/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,99 @@ +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 8: Using Compound Primary Keys and Multile Tables Example"; + + private final String DESCRIPTION = + "This example demonstates the basics of using compound primary keys with multiple tables."; + + @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.createEmployee( + request.getParameter("country"), + parseInt(request.getParameter("empId")), + request.getParameter("name"), + parseLong(request.getParameter("salary"))); + } + + out.println("Employees:
"); + for (Employee emp : service.findAllEmployees()) { + out.print(emp + "
"); + out.print(emp.getManager() + "
"); + emp.getComments(); + out.print(emp.getPhoto() + "
"); + } + + 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 + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("" + + ""); + out.println("
Employee Country:(String)
Employee Id:(int)
Employee Name:(String)
Employee Salary:(long)
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter8/10-multipleTableCompoundPrimaryKey/undeploy.bat b/examples/Chapter8/10-multipleTableCompoundPrimaryKey/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter8/10-multipleTableCompoundPrimaryKey/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter8/11-singleTableInheritance/build.xml b/examples/Chapter8/11-singleTableInheritance/build.xml new file mode 100644 index 0000000..9de3cdf --- /dev/null +++ b/examples/Chapter8/11-singleTableInheritance/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter8/11-singleTableInheritance/deploy.bat b/examples/Chapter8/11-singleTableInheritance/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter8/11-singleTableInheritance/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter8/11-singleTableInheritance/etc/persistence/META-INF/persistence.xml b/examples/Chapter8/11-singleTableInheritance/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..9897b53 --- /dev/null +++ b/examples/Chapter8/11-singleTableInheritance/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/singleTableInheritance + + + + + + \ No newline at end of file diff --git a/examples/Chapter8/11-singleTableInheritance/etc/sql/db.sql b/examples/Chapter8/11-singleTableInheritance/etc/sql/db.sql new file mode 100644 index 0000000..091ae24 --- /dev/null +++ b/examples/Chapter8/11-singleTableInheritance/etc/sql/db.sql @@ -0,0 +1,27 @@ +DROP TABLE EMP; + +CREATE TABLE EMP (ID INTEGER NOT NULL, NAME VARCHAR(255), S_DATE DATE, D_RATE INTEGER, TERM INTEGER, + VACATION INTEGER, H_RATE FLOAT, SALARY BIGINT, PENSION BIGINT, EMP_TYPE VARCHAR(32), + PRIMARY KEY (ID)); + +INSERT INTO EMP (ID, NAME, S_DATE, D_RATE, TERM, VACATION, H_RATE, SALARY, PENSION, EMP_TYPE) + VALUES (1, 'John', {d '2001-01-01'}, 500, 12, NULL, NULL, NULL, NULL, 'ContractEmployee'); +INSERT INTO EMP (ID, NAME, S_DATE, D_RATE, TERM, VACATION, H_RATE, SALARY, PENSION, EMP_TYPE) + VALUES (2, 'Paul', {d '2002-04-08'}, 600, 24, NULL, NULL, NULL, NULL, 'ContractEmployee'); +INSERT INTO EMP (ID, NAME, S_DATE, D_RATE, TERM, VACATION, H_RATE, SALARY, PENSION, EMP_TYPE) + VALUES (3, 'Sarah', {d '2003-06-10'}, 700, 18, NULL, NULL, NULL, NULL, 'ContractEmployee'); + +INSERT INTO EMP (ID, NAME, S_DATE, D_RATE, TERM, VACATION, H_RATE, SALARY, PENSION, EMP_TYPE) + VALUES (4, 'Patrick', {d '2004-07-01'}, NULL, NULL, 15, NULL, 55000, 100000, 'FTEmp'); +INSERT INTO EMP (ID, NAME, S_DATE, D_RATE, TERM, VACATION, H_RATE, SALARY, PENSION, EMP_TYPE) + VALUES (5, 'Joan', {d '2003-09-09'}, NULL, NULL, 15, NULL, 59000, 200000, 'FTEmp'); +INSERT INTO EMP (ID, NAME, S_DATE, D_RATE, TERM, VACATION, H_RATE, SALARY, PENSION, EMP_TYPE) + VALUES (6, 'Samantha', {d '2000-03-12'}, NULL, NULL, 20, NULL, 60000, 450000, 'FTEmp'); + +INSERT INTO EMP (ID, NAME, S_DATE, D_RATE, TERM, VACATION, H_RATE, SALARY, PENSION, EMP_TYPE) + VALUES (7, 'Mark', {d '2004-11-01'}, NULL, NULL, 15, 17.0, NULL, NULL, 'PTEmp'); +INSERT INTO EMP (ID, NAME, S_DATE, D_RATE, TERM, VACATION, H_RATE, SALARY, PENSION, EMP_TYPE) + VALUES (8, 'Ryan', {d '2005-12-05'}, NULL, NULL, 15, 16.0, NULL, NULL, 'PTEmp'); +INSERT INTO EMP (ID, NAME, S_DATE, D_RATE, TERM, VACATION, H_RATE, SALARY, PENSION, EMP_TYPE) + VALUES (9, 'Jackie', {d '2006-01-03'}, NULL, NULL, 10, 15.0, NULL, NULL, 'PTEmp'); + diff --git a/examples/Chapter8/11-singleTableInheritance/etc/web/WEB-INF/web.xml b/examples/Chapter8/11-singleTableInheritance/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter8/11-singleTableInheritance/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/Chapter8/11-singleTableInheritance/src/model/examples/model/CachedEntity.java b/examples/Chapter8/11-singleTableInheritance/src/model/examples/model/CachedEntity.java new file mode 100644 index 0000000..c98d419 --- /dev/null +++ b/examples/Chapter8/11-singleTableInheritance/src/model/examples/model/CachedEntity.java @@ -0,0 +1,13 @@ +package examples.model; + +public abstract class CachedEntity { + private long createTime; + + public CachedEntity() { + createTime = System.currentTimeMillis(); + } + + public long getCacheAge() { + return System.currentTimeMillis() - createTime; + } +} diff --git a/examples/Chapter8/11-singleTableInheritance/src/model/examples/model/CompanyEmployee.java b/examples/Chapter8/11-singleTableInheritance/src/model/examples/model/CompanyEmployee.java new file mode 100644 index 0000000..4483a62 --- /dev/null +++ b/examples/Chapter8/11-singleTableInheritance/src/model/examples/model/CompanyEmployee.java @@ -0,0 +1,16 @@ +package examples.model; + +import javax.persistence.MappedSuperclass; + +@MappedSuperclass +public abstract class CompanyEmployee extends Employee { + private int vacation; + + public int getVacation() { + return vacation; + } + + public void setVacation(int vacation) { + this.vacation = vacation; + } +} diff --git a/examples/Chapter8/11-singleTableInheritance/src/model/examples/model/ContractEmployee.java b/examples/Chapter8/11-singleTableInheritance/src/model/examples/model/ContractEmployee.java new file mode 100644 index 0000000..e32d79c --- /dev/null +++ b/examples/Chapter8/11-singleTableInheritance/src/model/examples/model/ContractEmployee.java @@ -0,0 +1,31 @@ +package examples.model; + +import javax.persistence.Column; +import javax.persistence.Entity; + +@Entity +public class ContractEmployee extends Employee { + @Column(name="D_RATE") + private int dailyRate; + private int term; + + public int getDailyRate() { + return dailyRate; + } + + public void setDailyRate(int dailyRate) { + this.dailyRate = dailyRate; + } + + public int getTerm() { + return term; + } + + public void setTerm(int term) { + this.term = term; + } + + public String toString() { + return "ContractEmployee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter8/11-singleTableInheritance/src/model/examples/model/Employee.java b/examples/Chapter8/11-singleTableInheritance/src/model/examples/model/Employee.java new file mode 100644 index 0000000..e3df177 --- /dev/null +++ b/examples/Chapter8/11-singleTableInheritance/src/model/examples/model/Employee.java @@ -0,0 +1,52 @@ +package examples.model; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.DiscriminatorColumn; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@Table(name="EMP") +@Inheritance +@DiscriminatorColumn(name="EMP_TYPE") +public abstract class Employee extends CachedEntity { + @Id private int id; + private String name; + @Temporal(TemporalType.DATE) + @Column(name="S_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 Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter8/11-singleTableInheritance/src/model/examples/model/FullTimeEmployee.java b/examples/Chapter8/11-singleTableInheritance/src/model/examples/model/FullTimeEmployee.java new file mode 100644 index 0000000..bec3b48 --- /dev/null +++ b/examples/Chapter8/11-singleTableInheritance/src/model/examples/model/FullTimeEmployee.java @@ -0,0 +1,31 @@ +package examples.model; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; + +@Entity +@DiscriminatorValue("FTEmp") +public class FullTimeEmployee extends CompanyEmployee { + private long salary; + private long pension; + + public long getPension() { + return pension; + } + + public void setPension(long pension) { + this.pension = pension; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public String toString() { + return "FullTimeEmployee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter8/11-singleTableInheritance/src/model/examples/model/PartTimeEmployee.java b/examples/Chapter8/11-singleTableInheritance/src/model/examples/model/PartTimeEmployee.java new file mode 100644 index 0000000..d724426 --- /dev/null +++ b/examples/Chapter8/11-singleTableInheritance/src/model/examples/model/PartTimeEmployee.java @@ -0,0 +1,24 @@ +package examples.model; + +import javax.persistence.Column; +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; + +@Entity(name="PTEmp") +@DiscriminatorValue("PTEmp") +public class PartTimeEmployee extends CompanyEmployee { + @Column(name="H_RATE") + private float hourlyRate; + + public float getHourlyRate() { + return hourlyRate; + } + + public void setHourlyRate(float hourlyRate) { + this.hourlyRate = hourlyRate; + } + + public String toString() { + return "PartTimeEmployee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter8/11-singleTableInheritance/src/model/examples/stateless/EmployeeService.java b/examples/Chapter8/11-singleTableInheritance/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..6e47457 --- /dev/null +++ b/examples/Chapter8/11-singleTableInheritance/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 void createEmployee(Employee emp); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter8/11-singleTableInheritance/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter8/11-singleTableInheritance/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..97740b1 --- /dev/null +++ b/examples/Chapter8/11-singleTableInheritance/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,25 @@ +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 void createEmployee(Employee emp) { + em.persist(emp); + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter8/11-singleTableInheritance/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter8/11-singleTableInheritance/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..054024f --- /dev/null +++ b/examples/Chapter8/11-singleTableInheritance/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,97 @@ +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.*; +import examples.stateless.EmployeeService; + +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 8: Using Single Table Inheritance Example"; + + private final String DESCRIPTION = + "This example demonstates the basics of using single table inheritance."; + + @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 = null; + if (request.getParameter("type").equals("Full")) { + emp = new FullTimeEmployee(); + } else if (request.getParameter("type").equals("Part")) { + emp = new PartTimeEmployee(); + } else { + emp = new ContractEmployee(); + } + emp.setId(parseInt(request.getParameter("empId"))); + emp.setName(request.getParameter("name")); + service.createEmployee(emp); + } + + 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 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 + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
Employee Name:(String)
Empoyee Type:"); + out.println(" Full Time
"); + out.println(" Part Time
"); + out.println(" Contract"); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter8/11-singleTableInheritance/undeploy.bat b/examples/Chapter8/11-singleTableInheritance/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter8/11-singleTableInheritance/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter8/12-joinedTableInheritance/build.xml b/examples/Chapter8/12-joinedTableInheritance/build.xml new file mode 100644 index 0000000..8a12624 --- /dev/null +++ b/examples/Chapter8/12-joinedTableInheritance/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter8/12-joinedTableInheritance/deploy.bat b/examples/Chapter8/12-joinedTableInheritance/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter8/12-joinedTableInheritance/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter8/12-joinedTableInheritance/etc/persistence/META-INF/persistence.xml b/examples/Chapter8/12-joinedTableInheritance/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..1b57055 --- /dev/null +++ b/examples/Chapter8/12-joinedTableInheritance/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/joinedTableInheritance + + + + + + \ No newline at end of file diff --git a/examples/Chapter8/12-joinedTableInheritance/etc/sql/db.sql b/examples/Chapter8/12-joinedTableInheritance/etc/sql/db.sql new file mode 100644 index 0000000..f424b18 --- /dev/null +++ b/examples/Chapter8/12-joinedTableInheritance/etc/sql/db.sql @@ -0,0 +1,36 @@ +DROP TABLE CONTRACT_EMP; +DROP TABLE PT_EMP; +DROP TABLE FT_EMP; +DROP TABLE EMP; + +CREATE TABLE EMP (ID INTEGER NOT NULL, NAME VARCHAR(255), S_DATE DATE, EMP_TYPE INTEGER, PRIMARY KEY (ID)); +CREATE TABLE FT_EMP (ID INTEGER NOT NULL, VACATION INTEGER, SALARY BIGINT, PENSION BIGINT, PRIMARY KEY (ID), + CONSTRAINT FT_EMP_FK FOREIGN KEY (ID) REFERENCES EMP(ID)); +CREATE TABLE PT_EMP (ID INTEGER NOT NULL, VACATION INTEGER, H_RATE FLOAT, PRIMARY KEY (ID), + CONSTRAINT PT_EMP_FK FOREIGN KEY (ID) REFERENCES EMP(ID)); +CREATE TABLE CONTRACT_EMP (ID INTEGER NOT NULL, D_RATE INTEGER, TERM INTEGER, PRIMARY KEY (ID), + CONSTRAINT CONTRACT_EMP_FK FOREIGN KEY (ID) REFERENCES EMP(ID)); + + +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (1, 'John', {d '2001-01-01'}, 1); +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (2, 'Paul', {d '2002-04-08'}, 1); +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (3, 'Sarah', {d '2003-06-10'}, 1); +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (4, 'Patrick', {d '2004-07-01'}, 2); +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (5, 'Joan', {d '2003-09-09'}, 2); +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (6, 'Samantha', {d '2000-03-12'}, 2); +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (7, 'Mark', {d '2004-11-01'}, 3); +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (8, 'Ryan', {d '2005-12-05'}, 3); +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (9, 'Jackie', {d '2006-01-03'}, 3); + +INSERT INTO CONTRACT_EMP (ID, D_RATE, TERM) VALUES (1, 500, 12); +INSERT INTO CONTRACT_EMP (ID, D_RATE, TERM) VALUES (2, 600, 24); +INSERT INTO CONTRACT_EMP (ID, D_RATE, TERM) VALUES (3, 700, 18); + +INSERT INTO FT_EMP (ID, VACATION, SALARY, PENSION) VALUES (4, 15, 55000, 100000); +INSERT INTO FT_EMP (ID, VACATION, SALARY, PENSION) VALUES (5, 15, 59000, 200000); +INSERT INTO FT_EMP (ID, VACATION, SALARY, PENSION) VALUES (6, 20, 60000, 450000); + +INSERT INTO PT_EMP (ID, VACATION, H_RATE) VALUES (7, 15, 17.0); +INSERT INTO PT_EMP (ID, VACATION, H_RATE) VALUES (8, 15, 16.0); +INSERT INTO PT_EMP (ID, VACATION, H_RATE) VALUES (9, 10, 15.0); + diff --git a/examples/Chapter8/12-joinedTableInheritance/etc/web/WEB-INF/web.xml b/examples/Chapter8/12-joinedTableInheritance/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter8/12-joinedTableInheritance/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/Chapter8/12-joinedTableInheritance/src/model/examples/model/CachedEntity.java b/examples/Chapter8/12-joinedTableInheritance/src/model/examples/model/CachedEntity.java new file mode 100644 index 0000000..c98d419 --- /dev/null +++ b/examples/Chapter8/12-joinedTableInheritance/src/model/examples/model/CachedEntity.java @@ -0,0 +1,13 @@ +package examples.model; + +public abstract class CachedEntity { + private long createTime; + + public CachedEntity() { + createTime = System.currentTimeMillis(); + } + + public long getCacheAge() { + return System.currentTimeMillis() - createTime; + } +} diff --git a/examples/Chapter8/12-joinedTableInheritance/src/model/examples/model/CompanyEmployee.java b/examples/Chapter8/12-joinedTableInheritance/src/model/examples/model/CompanyEmployee.java new file mode 100644 index 0000000..4483a62 --- /dev/null +++ b/examples/Chapter8/12-joinedTableInheritance/src/model/examples/model/CompanyEmployee.java @@ -0,0 +1,16 @@ +package examples.model; + +import javax.persistence.MappedSuperclass; + +@MappedSuperclass +public abstract class CompanyEmployee extends Employee { + private int vacation; + + public int getVacation() { + return vacation; + } + + public void setVacation(int vacation) { + this.vacation = vacation; + } +} diff --git a/examples/Chapter8/12-joinedTableInheritance/src/model/examples/model/ContractEmployee.java b/examples/Chapter8/12-joinedTableInheritance/src/model/examples/model/ContractEmployee.java new file mode 100644 index 0000000..9d0c11d --- /dev/null +++ b/examples/Chapter8/12-joinedTableInheritance/src/model/examples/model/ContractEmployee.java @@ -0,0 +1,35 @@ +package examples.model; + +import javax.persistence.Column; +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; +import javax.persistence.Table; + +@Entity +@Table(name="CONTRACT_EMP") +@DiscriminatorValue("1") +public class ContractEmployee extends Employee { + @Column(name="D_RATE") + private int dailyRate; + private int term; + + public int getDailyRate() { + return dailyRate; + } + + public void setDailyRate(int dailyRate) { + this.dailyRate = dailyRate; + } + + public int getTerm() { + return term; + } + + public void setTerm(int term) { + this.term = term; + } + + public String toString() { + return "ContractEmployee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter8/12-joinedTableInheritance/src/model/examples/model/Employee.java b/examples/Chapter8/12-joinedTableInheritance/src/model/examples/model/Employee.java new file mode 100644 index 0000000..c50d5ee --- /dev/null +++ b/examples/Chapter8/12-joinedTableInheritance/src/model/examples/model/Employee.java @@ -0,0 +1,54 @@ +package examples.model; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.DiscriminatorColumn; +import javax.persistence.DiscriminatorType; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@Table(name="EMP") +@Inheritance(strategy=InheritanceType.JOINED) +@DiscriminatorColumn(name="EMP_TYPE", discriminatorType=DiscriminatorType.INTEGER) +public abstract class Employee extends CachedEntity { + @Id private int id; + private String name; + @Temporal(TemporalType.DATE) + @Column(name="S_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 Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter8/12-joinedTableInheritance/src/model/examples/model/FullTimeEmployee.java b/examples/Chapter8/12-joinedTableInheritance/src/model/examples/model/FullTimeEmployee.java new file mode 100644 index 0000000..761ed00 --- /dev/null +++ b/examples/Chapter8/12-joinedTableInheritance/src/model/examples/model/FullTimeEmployee.java @@ -0,0 +1,33 @@ +package examples.model; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; +import javax.persistence.Table; + +@Entity +@Table(name="FT_EMP") +@DiscriminatorValue("2") +public class FullTimeEmployee extends CompanyEmployee { + private long salary; + private long pension; + + public long getPension() { + return pension; + } + + public void setPension(long pension) { + this.pension = pension; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public String toString() { + return "FullTimeEmployee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter8/12-joinedTableInheritance/src/model/examples/model/PartTimeEmployee.java b/examples/Chapter8/12-joinedTableInheritance/src/model/examples/model/PartTimeEmployee.java new file mode 100644 index 0000000..6d6247d --- /dev/null +++ b/examples/Chapter8/12-joinedTableInheritance/src/model/examples/model/PartTimeEmployee.java @@ -0,0 +1,26 @@ +package examples.model; + +import javax.persistence.Column; +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; +import javax.persistence.Table; + +@Entity +@Table(name="PT_EMP") +@DiscriminatorValue("3") +public class PartTimeEmployee extends CompanyEmployee { + @Column(name="H_RATE") + private float hourlyRate; + + public float getHourlyRate() { + return hourlyRate; + } + + public void setHourlyRate(float hourlyRate) { + this.hourlyRate = hourlyRate; + } + + public String toString() { + return "PartTimeEmployee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter8/12-joinedTableInheritance/src/model/examples/stateless/EmployeeService.java b/examples/Chapter8/12-joinedTableInheritance/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..6e47457 --- /dev/null +++ b/examples/Chapter8/12-joinedTableInheritance/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 void createEmployee(Employee emp); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter8/12-joinedTableInheritance/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter8/12-joinedTableInheritance/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..97740b1 --- /dev/null +++ b/examples/Chapter8/12-joinedTableInheritance/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,25 @@ +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 void createEmployee(Employee emp) { + em.persist(emp); + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter8/12-joinedTableInheritance/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter8/12-joinedTableInheritance/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..7277ca9 --- /dev/null +++ b/examples/Chapter8/12-joinedTableInheritance/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,97 @@ +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.*; +import examples.stateless.EmployeeService; + +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 8: Using Joined Table Inheritance Example"; + + private final String DESCRIPTION = + "This example demonstates the basics of using joined table inheritance."; + + @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 = null; + if (request.getParameter("type").equals("Full")) { + emp = new FullTimeEmployee(); + } else if (request.getParameter("type").equals("Part")) { + emp = new PartTimeEmployee(); + } else { + emp = new ContractEmployee(); + } + emp.setId(parseInt(request.getParameter("empId"))); + emp.setName(request.getParameter("name")); + service.createEmployee(emp); + } + + 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 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 + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
Employee Name:(String)
Empoyee Type:"); + out.println(" Full Time
"); + out.println(" Part Time
"); + out.println(" Contract"); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter8/12-joinedTableInheritance/undeploy.bat b/examples/Chapter8/12-joinedTableInheritance/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter8/12-joinedTableInheritance/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter8/13-tablePerConcreteClass/build.xml b/examples/Chapter8/13-tablePerConcreteClass/build.xml new file mode 100644 index 0000000..efc1f20 --- /dev/null +++ b/examples/Chapter8/13-tablePerConcreteClass/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter8/13-tablePerConcreteClass/deploy.bat b/examples/Chapter8/13-tablePerConcreteClass/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter8/13-tablePerConcreteClass/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter8/13-tablePerConcreteClass/etc/persistence/META-INF/persistence.xml b/examples/Chapter8/13-tablePerConcreteClass/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..45c7696 --- /dev/null +++ b/examples/Chapter8/13-tablePerConcreteClass/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/tablePerConcreteClass + + + + + + \ No newline at end of file diff --git a/examples/Chapter8/13-tablePerConcreteClass/etc/sql/db.sql b/examples/Chapter8/13-tablePerConcreteClass/etc/sql/db.sql new file mode 100644 index 0000000..31bd337 --- /dev/null +++ b/examples/Chapter8/13-tablePerConcreteClass/etc/sql/db.sql @@ -0,0 +1,22 @@ +DROP TABLE CONTRACT_EMP; +DROP TABLE PT_EMP; +DROP TABLE FT_EMP; + +CREATE TABLE FT_EMP (ID INTEGER NOT NULL, NAME VARCHAR(255), S_DATE DATE, VACATION INTEGER, + SALARY BIGINT, PENSION BIGINT, MANAGER INTEGER, PRIMARY KEY (ID)); +CREATE TABLE PT_EMP (ID INTEGER NOT NULL, NAME VARCHAR(255), S_DATE DATE, VACATION INTEGER, + H_RATE FLOAT, MGR INTEGER, PRIMARY KEY (ID)); +CREATE TABLE CONTRACT_EMP (ID INTEGER NOT NULL, NAME VARCHAR(255), S_DATE DATE, D_RATE INTEGER, TERM INTEGER, PRIMARY KEY (ID)); + + +INSERT INTO CONTRACT_EMP (ID, NAME, S_DATE, D_RATE, TERM) VALUES (1, 'John', {d '2001-01-01'}, 500, 12); +INSERT INTO CONTRACT_EMP (ID, NAME, S_DATE, D_RATE, TERM) VALUES (2, 'Paul', {d '2002-04-08'}, 600, 24); +INSERT INTO CONTRACT_EMP (ID, NAME, S_DATE, D_RATE, TERM) VALUES (3, 'Sarah', {d '2003-06-10'}, 700, 18); +INSERT INTO FT_EMP (ID, NAME, S_DATE, VACATION, SALARY, PENSION) VALUES (4, 'Patrick', {d '2004-07-01'}, 15, 55000, 100000); +INSERT INTO FT_EMP (ID, NAME, S_DATE, VACATION, SALARY, PENSION) VALUES (5, 'Joan', {d '2003-09-09'}, 15, 59000, 200000); +INSERT INTO FT_EMP (ID, NAME, S_DATE, VACATION, SALARY, PENSION) VALUES (6, 'Samantha', {d '2000-03-12'}, 20, 60000, 450000); +INSERT INTO PT_EMP (ID, NAME, S_DATE, VACATION, H_RATE) VALUES (7, 'Mark', {d '2004-11-01'}, 15, 17.0); +INSERT INTO PT_EMP (ID, NAME, S_DATE, VACATION, H_RATE) VALUES (8, 'Ryan', {d '2005-12-05'}, 15, 16.0); +INSERT INTO PT_EMP (ID, NAME, S_DATE, VACATION, H_RATE) VALUES (9, 'Jackie', {d '2006-01-03'}, 10, 15.0); + + diff --git a/examples/Chapter8/13-tablePerConcreteClass/etc/web/WEB-INF/web.xml b/examples/Chapter8/13-tablePerConcreteClass/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter8/13-tablePerConcreteClass/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/Chapter8/13-tablePerConcreteClass/src/model/examples/model/CachedEntity.java b/examples/Chapter8/13-tablePerConcreteClass/src/model/examples/model/CachedEntity.java new file mode 100644 index 0000000..c98d419 --- /dev/null +++ b/examples/Chapter8/13-tablePerConcreteClass/src/model/examples/model/CachedEntity.java @@ -0,0 +1,13 @@ +package examples.model; + +public abstract class CachedEntity { + private long createTime; + + public CachedEntity() { + createTime = System.currentTimeMillis(); + } + + public long getCacheAge() { + return System.currentTimeMillis() - createTime; + } +} diff --git a/examples/Chapter8/13-tablePerConcreteClass/src/model/examples/model/CompanyEmployee.java b/examples/Chapter8/13-tablePerConcreteClass/src/model/examples/model/CompanyEmployee.java new file mode 100644 index 0000000..d38b409 --- /dev/null +++ b/examples/Chapter8/13-tablePerConcreteClass/src/model/examples/model/CompanyEmployee.java @@ -0,0 +1,27 @@ +package examples.model; + +import javax.persistence.ManyToOne; +import javax.persistence.MappedSuperclass; + +@MappedSuperclass +public abstract class CompanyEmployee extends Employee { + private int vacation; + @ManyToOne + private Employee manager; + + public int getVacation() { + return vacation; + } + + public void setVacation(int vacation) { + this.vacation = vacation; + } + + public Employee getManager() { + return manager; + } + + public void setManager(Employee manager) { + this.manager = manager; + } +} diff --git a/examples/Chapter8/13-tablePerConcreteClass/src/model/examples/model/ContractEmployee.java b/examples/Chapter8/13-tablePerConcreteClass/src/model/examples/model/ContractEmployee.java new file mode 100644 index 0000000..526f316 --- /dev/null +++ b/examples/Chapter8/13-tablePerConcreteClass/src/model/examples/model/ContractEmployee.java @@ -0,0 +1,40 @@ +package examples.model; + +import javax.persistence.AttributeOverride; +import javax.persistence.AttributeOverrides; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; + +@Entity +@Table(name="CONTRACT_EMP") +@AttributeOverrides({ + @AttributeOverride(name="name", column=@Column(name="FULLNAME")), + @AttributeOverride(name="startDate", column=@Column(name="SDATE")) +}) +public class ContractEmployee extends Employee { + @Column(name="D_RATE") + private int dailyRate; + private int term; + + + public int getDailyRate() { + return dailyRate; + } + + public void setDailyRate(int dailyRate) { + this.dailyRate = dailyRate; + } + + public int getTerm() { + return term; + } + + public void setTerm(int term) { + this.term = term; + } + + public String toString() { + return "ContractEmployee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter8/13-tablePerConcreteClass/src/model/examples/model/Employee.java b/examples/Chapter8/13-tablePerConcreteClass/src/model/examples/model/Employee.java new file mode 100644 index 0000000..226fb7c --- /dev/null +++ b/examples/Chapter8/13-tablePerConcreteClass/src/model/examples/model/Employee.java @@ -0,0 +1,49 @@ +package examples.model; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) +public abstract class Employee extends CachedEntity { + @Id private int id; + private String name; + @Temporal(TemporalType.DATE) + @Column(name="S_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 Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter8/13-tablePerConcreteClass/src/model/examples/model/FullTimeEmployee.java b/examples/Chapter8/13-tablePerConcreteClass/src/model/examples/model/FullTimeEmployee.java new file mode 100644 index 0000000..ef297a9 --- /dev/null +++ b/examples/Chapter8/13-tablePerConcreteClass/src/model/examples/model/FullTimeEmployee.java @@ -0,0 +1,32 @@ +package examples.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; + +@Entity @Table(name="FT_EMP") +public class FullTimeEmployee extends CompanyEmployee { + private long salary; + @Column(name="PENSION") + private long pensionContribution; + + public long getPensionContribution() { + return pensionContribution; + } + + public void setPensionContribution(long pension) { + this.pensionContribution = pension; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public String toString() { + return "FullTimeEmployee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter8/13-tablePerConcreteClass/src/model/examples/model/PartTimeEmployee.java b/examples/Chapter8/13-tablePerConcreteClass/src/model/examples/model/PartTimeEmployee.java new file mode 100644 index 0000000..bedae9f --- /dev/null +++ b/examples/Chapter8/13-tablePerConcreteClass/src/model/examples/model/PartTimeEmployee.java @@ -0,0 +1,28 @@ +package examples.model; + +import javax.persistence.AssociationOverride; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.JoinColumn; +import javax.persistence.Table; + +@Entity +@Table(name="PT_EMP") +@AssociationOverride(name="manager", + joinColumns=@JoinColumn(name="MGR")) +public class PartTimeEmployee extends CompanyEmployee { + @Column(name="H_RATE") + private float hourlyRate; + + public float getHourlyRate() { + return hourlyRate; + } + + public void setHourlyRate(float hourlyRate) { + this.hourlyRate = hourlyRate; + } + + public String toString() { + return "PartTimeEmployee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter8/13-tablePerConcreteClass/src/model/examples/stateless/EmployeeService.java b/examples/Chapter8/13-tablePerConcreteClass/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..6e47457 --- /dev/null +++ b/examples/Chapter8/13-tablePerConcreteClass/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 void createEmployee(Employee emp); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter8/13-tablePerConcreteClass/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter8/13-tablePerConcreteClass/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..97740b1 --- /dev/null +++ b/examples/Chapter8/13-tablePerConcreteClass/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,25 @@ +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 void createEmployee(Employee emp) { + em.persist(emp); + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter8/13-tablePerConcreteClass/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter8/13-tablePerConcreteClass/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..cec0939 --- /dev/null +++ b/examples/Chapter8/13-tablePerConcreteClass/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,97 @@ +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.*; +import examples.stateless.EmployeeService; + +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 8: Using Table per Class Inheritance Example"; + + private final String DESCRIPTION = + "This example demonstates the basics of using separate table for each entity in the inheritance hierarchy."; + + @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 = null; + if (request.getParameter("type").equals("Full")) { + emp = new FullTimeEmployee(); + } else if (request.getParameter("type").equals("Part")) { + emp = new PartTimeEmployee(); + } else { + emp = new ContractEmployee(); + } + emp.setId(parseInt(request.getParameter("empId"))); + emp.setName(request.getParameter("name")); + service.createEmployee(emp); + } + + 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 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 + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
Employee Name:(String)
Empoyee Type:"); + out.println(" Full Time
"); + out.println(" Part Time
"); + out.println(" Contract"); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter8/13-tablePerConcreteClass/undeploy.bat b/examples/Chapter8/13-tablePerConcreteClass/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter8/13-tablePerConcreteClass/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter8/14-mixedInheritance/build.xml b/examples/Chapter8/14-mixedInheritance/build.xml new file mode 100644 index 0000000..6f41abf --- /dev/null +++ b/examples/Chapter8/14-mixedInheritance/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter8/14-mixedInheritance/deploy.bat b/examples/Chapter8/14-mixedInheritance/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter8/14-mixedInheritance/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter8/14-mixedInheritance/etc/persistence/META-INF/persistence.xml b/examples/Chapter8/14-mixedInheritance/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..1de3edd --- /dev/null +++ b/examples/Chapter8/14-mixedInheritance/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/mixedInheritance + + + + + + \ No newline at end of file diff --git a/examples/Chapter8/14-mixedInheritance/etc/sql/db.sql b/examples/Chapter8/14-mixedInheritance/etc/sql/db.sql new file mode 100644 index 0000000..0c873ff --- /dev/null +++ b/examples/Chapter8/14-mixedInheritance/etc/sql/db.sql @@ -0,0 +1,34 @@ +DROP TABLE CONTRACT_EMP; +DROP TABLE PT_EMP; +DROP TABLE FT_EMP; +DROP TABLE EMP; + +CREATE TABLE EMP (ID INTEGER NOT NULL, NAME VARCHAR(255), S_DATE DATE, EMP_TYPE VARCHAR(32), PRIMARY KEY (ID)); +CREATE TABLE CONTRACT_EMP (ID INTEGER NOT NULL, D_RATE INTEGER, TERM INTEGER, PRIMARY KEY (ID), + CONSTRAINT CONTRACT_EMP_FK FOREIGN KEY (ID) REFERENCES EMP(ID)); +CREATE TABLE COMPANY_EMP (ID INTEGER NOT NULL, VACATION INTEGER, SALARY BIGINT, PENSION BIGINT, H_RATE FLOAT, PRIMARY KEY (ID), + CONSTRAINT FT_EMP_FK FOREIGN KEY (ID) REFERENCES EMP(ID)); + + +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (1, 'John', {d '2001-01-01'}, 'ContractEmployee'); +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (2, 'Paul', {d '2002-04-08'}, 'ContractEmployee'); +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (3, 'Sarah', {d '2003-06-10'}, 'ContractEmployee'); +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (4, 'Patrick', {d '2004-07-01'}, 'FTEmp'); +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (5, 'Joan', {d '2003-09-09'}, 'FTEmp'); +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (6, 'Samantha', {d '2000-03-12'}, 'FTEmp'); +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (7, 'Mark', {d '2004-11-01'}, 'PTEmp'); +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (8, 'Ryan', {d '2005-12-05'}, 'PTEmp'); +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (9, 'Jackie', {d '2006-01-03'}, 'PTEmp'); + +INSERT INTO CONTRACT_EMP (ID, D_RATE, TERM) VALUES (1, 500, 12); +INSERT INTO CONTRACT_EMP (ID, D_RATE, TERM) VALUES (2, 600, 24); +INSERT INTO CONTRACT_EMP (ID, D_RATE, TERM) VALUES (3, 700, 18); + +INSERT INTO COMPANY_EMP (ID, VACATION, SALARY, PENSION, H_RATE) VALUES (4, 15, 55000, 100000, NULL); +INSERT INTO COMPANY_EMP (ID, VACATION, SALARY, PENSION, H_RATE) VALUES (5, 15, 59000, 200000, NULL); +INSERT INTO COMPANY_EMP (ID, VACATION, SALARY, PENSION, H_RATE) VALUES (6, 20, 60000, 450000, NULL); + +INSERT INTO COMPANY_EMP (ID, VACATION, SALARY, PENSION, H_RATE) VALUES (7, 15, NULL, NULL, 17.0); +INSERT INTO COMPANY_EMP (ID, VACATION, SALARY, PENSION, H_RATE) VALUES (8, 15, NULL, NULL, 16.0); +INSERT INTO COMPANY_EMP (ID, VACATION, SALARY, PENSION, H_RATE) VALUES (9, 10, NULL, NULL, 15.0); + diff --git a/examples/Chapter8/14-mixedInheritance/etc/web/WEB-INF/web.xml b/examples/Chapter8/14-mixedInheritance/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter8/14-mixedInheritance/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/Chapter8/14-mixedInheritance/src/model/examples/model/CachedEntity.java b/examples/Chapter8/14-mixedInheritance/src/model/examples/model/CachedEntity.java new file mode 100644 index 0000000..c98d419 --- /dev/null +++ b/examples/Chapter8/14-mixedInheritance/src/model/examples/model/CachedEntity.java @@ -0,0 +1,13 @@ +package examples.model; + +public abstract class CachedEntity { + private long createTime; + + public CachedEntity() { + createTime = System.currentTimeMillis(); + } + + public long getCacheAge() { + return System.currentTimeMillis() - createTime; + } +} diff --git a/examples/Chapter8/14-mixedInheritance/src/model/examples/model/CompanyEmployee.java b/examples/Chapter8/14-mixedInheritance/src/model/examples/model/CompanyEmployee.java new file mode 100644 index 0000000..2e2521a --- /dev/null +++ b/examples/Chapter8/14-mixedInheritance/src/model/examples/model/CompanyEmployee.java @@ -0,0 +1,22 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; +import javax.persistence.Table; + +@Entity +@Table(name="COMPANY_EMP") +@Inheritance(strategy=InheritanceType.SINGLE_TABLE) +public abstract class CompanyEmployee extends Employee { + private int vacation; + + + public int getVacation() { + return vacation; + } + + public void setVacation(int vacation) { + this.vacation = vacation; + } +} diff --git a/examples/Chapter8/14-mixedInheritance/src/model/examples/model/ContractEmployee.java b/examples/Chapter8/14-mixedInheritance/src/model/examples/model/ContractEmployee.java new file mode 100644 index 0000000..4e7a666 --- /dev/null +++ b/examples/Chapter8/14-mixedInheritance/src/model/examples/model/ContractEmployee.java @@ -0,0 +1,33 @@ +package examples.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Table; + +@Entity +@Table(name="CONTRACT_EMP") +public class ContractEmployee extends Employee { + @Column(name="D_RATE") private int dailyRate; + private int term; + + + public int getDailyRate() { + return dailyRate; + } + + public void setDailyRate(int dailyRate) { + this.dailyRate = dailyRate; + } + + public int getTerm() { + return term; + } + + public void setTerm(int term) { + this.term = term; + } + + public String toString() { + return "ContractEmployee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter8/14-mixedInheritance/src/model/examples/model/Employee.java b/examples/Chapter8/14-mixedInheritance/src/model/examples/model/Employee.java new file mode 100644 index 0000000..000b9ce --- /dev/null +++ b/examples/Chapter8/14-mixedInheritance/src/model/examples/model/Employee.java @@ -0,0 +1,54 @@ +package examples.model; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.DiscriminatorColumn; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@Table(name="EMP") +@Inheritance(strategy=InheritanceType.JOINED) +@DiscriminatorColumn(name="EMP_TYPE") +public abstract class Employee { + @Id private int id; + private String name; + @Temporal(TemporalType.DATE) + @Column(name="S_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 Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter8/14-mixedInheritance/src/model/examples/model/FullTimeEmployee.java b/examples/Chapter8/14-mixedInheritance/src/model/examples/model/FullTimeEmployee.java new file mode 100644 index 0000000..9dba133 --- /dev/null +++ b/examples/Chapter8/14-mixedInheritance/src/model/examples/model/FullTimeEmployee.java @@ -0,0 +1,31 @@ +package examples.model; + +import javax.persistence.Column; +import javax.persistence.Entity; + +@Entity +public class FullTimeEmployee extends CompanyEmployee { + private long salary; + @Column(name="PENSION") + private long pensionContribution; + + public long getPensionContribution() { + return pensionContribution; + } + + public void setPensionContribution(long pension) { + this.pensionContribution = pension; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public String toString() { + return "FullTimeEmployee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter8/14-mixedInheritance/src/model/examples/model/PartTimeEmployee.java b/examples/Chapter8/14-mixedInheritance/src/model/examples/model/PartTimeEmployee.java new file mode 100644 index 0000000..68a2bd5 --- /dev/null +++ b/examples/Chapter8/14-mixedInheritance/src/model/examples/model/PartTimeEmployee.java @@ -0,0 +1,23 @@ +package examples.model; + +import javax.persistence.Column; +import javax.persistence.Entity; + +@Entity +public class PartTimeEmployee extends CompanyEmployee { + @Column(name="H_RATE") + private float hourlyRate; + + + public float getHourlyRate() { + return hourlyRate; + } + + public void setHourlyRate(float hourlyRate) { + this.hourlyRate = hourlyRate; + } + + public String toString() { + return "PartTimeEmployee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter8/14-mixedInheritance/src/model/examples/stateless/EmployeeService.java b/examples/Chapter8/14-mixedInheritance/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..6e47457 --- /dev/null +++ b/examples/Chapter8/14-mixedInheritance/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 void createEmployee(Employee emp); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter8/14-mixedInheritance/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter8/14-mixedInheritance/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..97740b1 --- /dev/null +++ b/examples/Chapter8/14-mixedInheritance/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,25 @@ +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 void createEmployee(Employee emp) { + em.persist(emp); + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter8/14-mixedInheritance/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter8/14-mixedInheritance/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..3ca6c47 --- /dev/null +++ b/examples/Chapter8/14-mixedInheritance/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,97 @@ +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.*; +import examples.stateless.EmployeeService; + +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 8: Using a Mixed Inheritance Hierarchy Example"; + + private final String DESCRIPTION = + "This example demonstates the basics of mixed inheritance strategies in the same hierarchy."; + + @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 = null; + if (request.getParameter("type").equals("Full")) { + emp = new FullTimeEmployee(); + } else if (request.getParameter("type").equals("Part")) { + emp = new PartTimeEmployee(); + } else { + emp = new ContractEmployee(); + } + emp.setId(parseInt(request.getParameter("empId"))); + emp.setName(request.getParameter("name")); + service.createEmployee(emp); + } + + 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 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 + out.println("

Create an Employee

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
Employee Name:(String)
Empoyee Type:"); + out.println(" Full Time
"); + out.println(" Part Time
"); + out.println(" Contract"); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter8/14-mixedInheritance/undeploy.bat b/examples/Chapter8/14-mixedInheritance/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter8/14-mixedInheritance/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter9/01-nativeQueries/build.xml b/examples/Chapter9/01-nativeQueries/build.xml new file mode 100644 index 0000000..368ffe5 --- /dev/null +++ b/examples/Chapter9/01-nativeQueries/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter9/01-nativeQueries/deploy.bat b/examples/Chapter9/01-nativeQueries/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter9/01-nativeQueries/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter9/01-nativeQueries/etc/persistence/META-INF/persistence.xml b/examples/Chapter9/01-nativeQueries/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..7d86a43 --- /dev/null +++ b/examples/Chapter9/01-nativeQueries/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/nativeQueries + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/01-nativeQueries/etc/sql/db.sql b/examples/Chapter9/01-nativeQueries/etc/sql/db.sql new file mode 100644 index 0000000..317f6ef --- /dev/null +++ b/examples/Chapter9/01-nativeQueries/etc/sql/db.sql @@ -0,0 +1,39 @@ +DROP TABLE EMP; +DROP TABLE DEPARTMENT; +DROP TABLE ADDRESS; + +CREATE TABLE DEPARTMENT (ID INTEGER, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE ADDRESS (ID INTEGER NOT NULL, STREET VARCHAR(255), CITY VARCHAR(255), + STATE VARCHAR(255), ZIP VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMP (EMP_ID INTEGER, NAME VARCHAR(255), SALARY BIGINT, + MANAGER_ID INTEGER, DEPT_ID INTEGER, ADDRESS_ID INTEGER, PRIMARY KEY (EMP_ID), + CONSTRAINT MGR_FK FOREIGN KEY (MANAGER_ID) REFERENCES EMP (EMP_ID), + CONSTRAINT ADDRESS_FK FOREIGN KEY (ADDRESS_ID) REFERENCES ADDRESS (ID), + CONSTRAINT DEPT_FK FOREIGN KEY (DEPT_ID) REFERENCES DEPARTMENT (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 EMP (EMP_ID, NAME, SALARY, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (2, 'Joan', 59000, 10, 1, NULL); +INSERT INTO EMP (EMP_ID, NAME, SALARY, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (1, 'Sarah', 52000, 9, 2, 1); +INSERT INTO EMP (EMP_ID, NAME, SALARY, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (3, 'John', 55000, 1, 2, 2); +INSERT INTO EMP (EMP_ID, NAME, SALARY, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (4, 'Rob', 53000, 2, 2, 2); +INSERT INTO EMP (EMP_ID, NAME, SALARY, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (5, 'Peter', 50000, 3, 2, 2); +INSERT INTO EMP (EMP_ID, NAME, SALARY, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (6, 'Frank', 51000, 4, 1, 1); +INSERT INTO EMP (EMP_ID, NAME, SALARY, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (7, 'Scott', 60000, 5, 1, 1); +INSERT INTO EMP (EMP_ID, NAME, SALARY, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (8, 'Sue', 62000, 6, 1, 1); +INSERT INTO EMP (EMP_ID, NAME, SALARY, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (9, 'Stephanie', 54000, 7, 1, 1); +INSERT INTO EMP (EMP_ID, NAME, SALARY, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (10, 'Jennifer', 55000, 8, 1, NULL); +INSERT INTO EMP (EMP_ID, NAME, SALARY, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (11, 'Marcus', 35000, NULL, NULL, NULL); diff --git a/examples/Chapter9/01-nativeQueries/etc/web/WEB-INF/web.xml b/examples/Chapter9/01-nativeQueries/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter9/01-nativeQueries/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/Chapter9/01-nativeQueries/src/model/examples/model/Address.java b/examples/Chapter9/01-nativeQueries/src/model/examples/model/Address.java new file mode 100644 index 0000000..e18406b --- /dev/null +++ b/examples/Chapter9/01-nativeQueries/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/Chapter9/01-nativeQueries/src/model/examples/model/Department.java b/examples/Chapter9/01-nativeQueries/src/model/examples/model/Department.java new file mode 100644 index 0000000..42e0787 --- /dev/null +++ b/examples/Chapter9/01-nativeQueries/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/Chapter9/01-nativeQueries/src/model/examples/model/Employee.java b/examples/Chapter9/01-nativeQueries/src/model/examples/model/Employee.java new file mode 100644 index 0000000..5679ae4 --- /dev/null +++ b/examples/Chapter9/01-nativeQueries/src/model/examples/model/Employee.java @@ -0,0 +1,117 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedNativeQuery; +import javax.persistence.OneToMany; +import javax.persistence.OneToOne; +import javax.persistence.Table; + +@Entity +@Table(name="EMP") +@NamedNativeQuery( + name="orgStructureReportingTo", +// Oracle-specific SQL string +// query="SELECT emp_id, name, salary, manager_id, dept_id, address_id " + +// "FROM emp " + +// "START WITH manager_id = ? " + +// "CONNECT BY PRIOR emp_id = manager_id", + query = "SELECT emp1.emp_id, emp1.name, emp1.salary, emp1.manager_id, " + + "emp1.dept_id, emp1.address_id " + + "FROM EMP emp1, EMP emp2 " + + "WHERE ((emp2.EMP_ID = ?) AND (emp2.EMP_ID = emp1.MANAGER_ID))", + resultClass=Employee.class +) +public class Employee { + @Id + @Column(name="EMP_ID") + private int id; + private String name; + private long salary; + + @OneToOne + private Address address; + + @ManyToOne + @JoinColumn(name="DEPT_ID") + private Department department; + + @ManyToOne + @JoinColumn(name="MANAGER_ID") + private Employee manager; + + @OneToMany(mappedBy="manager") + private Collection directs = 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 Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + 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 String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " with MgrId: " + (getManager() == null ? null : getManager().getId()); + } +} diff --git a/examples/Chapter9/01-nativeQueries/src/model/examples/stateless/JdbcOrgStructureBean.java b/examples/Chapter9/01-nativeQueries/src/model/examples/stateless/JdbcOrgStructureBean.java new file mode 100644 index 0000000..e7bc81d --- /dev/null +++ b/examples/Chapter9/01-nativeQueries/src/model/examples/stateless/JdbcOrgStructureBean.java @@ -0,0 +1,60 @@ +package examples.stateless; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +import javax.annotation.Resource; +import javax.ejb.EJBException; +import javax.ejb.Stateless; +import javax.sql.DataSource; + +import examples.model.Employee; + +@Stateless +public class JdbcOrgStructureBean implements OrgStructure { +// Oracle-specific SQL string +// private static final String ORG_QUERY = +// "SELECT emp_id, name, salary " + +// "FROM emp " + +// "START WITH manager_id = ? " + +// "CONNECT BY PRIOR emp_id = manager_id"; + private static final String ORG_QUERY = + "SELECT emp1.emp_id, emp1.name, emp1.salary, emp1.manager_id, " + + "emp1.dept_id, emp1.address_id " + + "FROM EMP emp1, EMP emp2 " + + "WHERE ((emp2.EMP_ID = ?) AND (emp2.EMP_ID = emp1.MANAGER_ID))"; + + @Resource(mappedName="jdbc/nativeQueries") + DataSource hrDs; + + public List findEmployeesReportingTo(int managerId) { + Connection conn = null; + PreparedStatement sth = null; + try { + conn = hrDs.getConnection(); + sth = conn.prepareStatement(ORG_QUERY); + sth.setLong(1, managerId); + ResultSet rs = sth.executeQuery(); + + ArrayList result = new ArrayList(); + while (rs.next()) { + Employee emp = new Employee(); + emp.setId(rs.getInt(1)); + emp.setName(rs.getString(2)); + emp.setSalary(rs.getLong(3)); + result.add(emp); + } + return result; + } catch (SQLException e) { + throw new EJBException(e); + } + } + + public List findAllEmployees() { + throw new EJBException("Not implemented!"); + } + } diff --git a/examples/Chapter9/01-nativeQueries/src/model/examples/stateless/NamedQueryOrgStructureBean.java b/examples/Chapter9/01-nativeQueries/src/model/examples/stateless/NamedQueryOrgStructureBean.java new file mode 100644 index 0000000..fddefed --- /dev/null +++ b/examples/Chapter9/01-nativeQueries/src/model/examples/stateless/NamedQueryOrgStructureBean.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 javax.persistence.Query; + +@Stateless +public class NamedQueryOrgStructureBean implements OrgStructure { + @PersistenceContext(unitName="EmployeeService") + EntityManager em; + + public List findEmployeesReportingTo(int managerId) { + return em.createNamedQuery("orgStructureReportingTo") + .setParameter(1, managerId) + .getResultList(); + } + + public List findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return query.getResultList(); + } +} + diff --git a/examples/Chapter9/01-nativeQueries/src/model/examples/stateless/OrgStructure.java b/examples/Chapter9/01-nativeQueries/src/model/examples/stateless/OrgStructure.java new file mode 100644 index 0000000..36ccd4f --- /dev/null +++ b/examples/Chapter9/01-nativeQueries/src/model/examples/stateless/OrgStructure.java @@ -0,0 +1,8 @@ +package examples.stateless; + +import java.util.List; + +public interface OrgStructure { + public List findEmployeesReportingTo(int managerId); + public List findAllEmployees(); +} diff --git a/examples/Chapter9/01-nativeQueries/src/model/examples/stateless/QueryOrgStructureBean.java b/examples/Chapter9/01-nativeQueries/src/model/examples/stateless/QueryOrgStructureBean.java new file mode 100644 index 0000000..7404ac7 --- /dev/null +++ b/examples/Chapter9/01-nativeQueries/src/model/examples/stateless/QueryOrgStructureBean.java @@ -0,0 +1,40 @@ +package examples.stateless; + +import java.util.List; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Employee; + +@Stateless +public class QueryOrgStructureBean implements OrgStructure { +// Oracle-specific SQL string +// private static final String ORG_QUERY = +// "SELECT emp_id, name, salary " + +// "FROM emp " + +// "START WITH manager_id = ? " + +// "CONNECT BY PRIOR emp_id = manager_id"; + private static final String ORG_QUERY = + "SELECT emp1.emp_id, emp1.name, emp1.salary, emp1.manager_id, " + + "emp1.dept_id, emp1.address_id " + + "FROM EMP emp1, EMP emp2 " + + "WHERE ((emp2.EMP_ID = ?) AND (emp2.EMP_ID = emp1.MANAGER_ID))"; + + @PersistenceContext(unitName="EmployeeService") + EntityManager em; + + public List findEmployeesReportingTo(int managerId) { + return em.createNativeQuery(ORG_QUERY, Employee.class) + .setParameter(1, managerId) + .getResultList(); + } + + public List findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return query.getResultList(); + } +} + diff --git a/examples/Chapter9/01-nativeQueries/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter9/01-nativeQueries/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..68d06d5 --- /dev/null +++ b/examples/Chapter9/01-nativeQueries/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,108 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; +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.OrgStructure; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 9: Native Queries Example"; + + private final String DESCRIPTION = + "This example demonstates the basic usage of native " + + "queries. It compares jdbc to native queries."; + + + @EJB (beanName="JdbcOrgStructureBean") + OrgStructure jdbcOrgStructure; + @EJB (beanName="QueryOrgStructureBean") + OrgStructure queryOrgStructure; + @EJB (beanName="NamedQueryOrgStructureBean") + OrgStructure namedQueryOrgStructure; + + 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("SqlAndJdbc")) { + List emps = jdbcOrgStructure.findEmployeesReportingTo( + parseInt(request.getParameter("mgrId"))); + out.println("Found using JDBC:
"); + printCollection(emps, out); + } else if (action.equals("SqlAndQuery")) { + List emps = queryOrgStructure.findEmployeesReportingTo( + parseInt(request.getParameter("mgrId"))); + out.println("Found using NativeQuery:
"); + printCollection(emps, out); + } else if (action.equals("SqlAndNamedQuery")) { + List emps = namedQueryOrgStructure.findEmployeesReportingTo( + parseInt(request.getParameter("mgrId"))); + out.println("Found using NamedNativeQuery:
"); + printCollection(emps, out); + } + out.println("
All Employees:
"); + List emps = queryOrgStructure.findAllEmployees(); + printCollection(emps, 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.println(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 create and Employee and Department + out.println("

Find Employees Reporting to:

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println("
Manager Id:(int)
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter9/01-nativeQueries/undeploy.bat b/examples/Chapter9/01-nativeQueries/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter9/01-nativeQueries/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter9/02-sqlInsertDelete/build.xml b/examples/Chapter9/02-sqlInsertDelete/build.xml new file mode 100644 index 0000000..6836b1a --- /dev/null +++ b/examples/Chapter9/02-sqlInsertDelete/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter9/02-sqlInsertDelete/deploy.bat b/examples/Chapter9/02-sqlInsertDelete/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter9/02-sqlInsertDelete/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter9/02-sqlInsertDelete/etc/persistence/META-INF/persistence.xml b/examples/Chapter9/02-sqlInsertDelete/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..ef9ac50 --- /dev/null +++ b/examples/Chapter9/02-sqlInsertDelete/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/sqlInsertDelete + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/02-sqlInsertDelete/etc/sql/db.sql b/examples/Chapter9/02-sqlInsertDelete/etc/sql/db.sql new file mode 100644 index 0000000..4af3588 --- /dev/null +++ b/examples/Chapter9/02-sqlInsertDelete/etc/sql/db.sql @@ -0,0 +1,4 @@ +DROP TABLE MESSAGE_LOG; + +CREATE TABLE MESSAGE_LOG (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), + MESSAGE VARCHAR(255), LOG_DTTM TIMESTAMP, PRIMARY KEY (ID)); diff --git a/examples/Chapter9/02-sqlInsertDelete/etc/web/WEB-INF/web.xml b/examples/Chapter9/02-sqlInsertDelete/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..eb06402 --- /dev/null +++ b/examples/Chapter9/02-sqlInsertDelete/etc/web/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + LoggerServlet + examples.servlet.LoggerServlet + + + + LoggerServlet + /LoggerServlet + + \ No newline at end of file diff --git a/examples/Chapter9/02-sqlInsertDelete/src/model/examples/model/MessageLog.java b/examples/Chapter9/02-sqlInsertDelete/src/model/examples/model/MessageLog.java new file mode 100644 index 0000000..8573647 --- /dev/null +++ b/examples/Chapter9/02-sqlInsertDelete/src/model/examples/model/MessageLog.java @@ -0,0 +1,41 @@ +package examples.model; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@Table(name="MESSAGE_LOG") +public class MessageLog { + @Id + private int id; + private String message; + @Temporal(TemporalType.TIMESTAMP) + @Column(name="LOG_DTTM") + private Date logDateTime; + + public int getId() { + return id; + } + + public Date getLogDateTime() { + return logDateTime; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String toString() { + return "Message: " + getMessage() + " logged: " + getLogDateTime(); + } +} diff --git a/examples/Chapter9/02-sqlInsertDelete/src/model/examples/stateless/Logger.java b/examples/Chapter9/02-sqlInsertDelete/src/model/examples/stateless/Logger.java new file mode 100644 index 0000000..9e6ce9f --- /dev/null +++ b/examples/Chapter9/02-sqlInsertDelete/src/model/examples/stateless/Logger.java @@ -0,0 +1,9 @@ +package examples.stateless; + +import java.util.List; + +public interface Logger { + public void logMessage(String message); + public void clearMessageLog(); + public List findAllMessages(); +} diff --git a/examples/Chapter9/02-sqlInsertDelete/src/model/examples/stateless/LoggerBean.java b/examples/Chapter9/02-sqlInsertDelete/src/model/examples/stateless/LoggerBean.java new file mode 100644 index 0000000..41ff659 --- /dev/null +++ b/examples/Chapter9/02-sqlInsertDelete/src/model/examples/stateless/LoggerBean.java @@ -0,0 +1,43 @@ +package examples.stateless; + +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; + +@Stateless +@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) +public class LoggerBean implements Logger { +// Oracle-specific SQL string +// private static final String INSERT_SQL = +// "INSERT INTO message_log (id, message, log_dttm) " + +// " VALUES(id_seq.nextval, ?, SYSDATE)"; + private static final String INSERT_SQL = + "INSERT INTO message_log (message, log_dttm) " + + " VALUES(?, CURRENT TIMESTAMP)"; + private static final String DELETE_SQL = + "DELETE FROM message_log"; + + @PersistenceContext(unitName="Logger") + private EntityManager em; + + public void logMessage(String message) { + em.createNativeQuery(INSERT_SQL) + .setParameter(1, message) + .executeUpdate(); + } + + public void clearMessageLog() { + em.createNativeQuery(DELETE_SQL) + .executeUpdate(); + } + + public List findAllMessages() { + Query query = em.createQuery("SELECT m FROM MessageLog m"); + return query.getResultList(); + } +} diff --git a/examples/Chapter9/02-sqlInsertDelete/src/servlet/examples/servlet/LoggerServlet.java b/examples/Chapter9/02-sqlInsertDelete/src/servlet/examples/servlet/LoggerServlet.java new file mode 100644 index 0000000..8fcde1c --- /dev/null +++ b/examples/Chapter9/02-sqlInsertDelete/src/servlet/examples/servlet/LoggerServlet.java @@ -0,0 +1,86 @@ +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.Logger; + +public class LoggerServlet extends HttpServlet { + + private final String TITLE = + "Chapter 9: Sql INSERT/DELETE Example"; + + private final String DESCRIPTION = + "This example demonstates the basic usage of native " + + "queries for INSERT/DELETE operations."; + + + @EJB + Logger logger; + + 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("Log")) { + logger.logMessage(request.getParameter("message")); + } else if (action.equals("Clear")) { + logger.clearMessageLog(); + } + out.println("
All Messages:
"); + printCollection(logger.findAllMessages(), out); + + 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.println(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 create and Employee and Department + out.println("

Log Message:

"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Message:(String)
"); + out.println("
"); + out.println("

Clear All Messages:

"); + 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/02-sqlInsertDelete/undeploy.bat b/examples/Chapter9/02-sqlInsertDelete/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter9/02-sqlInsertDelete/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter9/03-sqlResultSetMappings/build.xml b/examples/Chapter9/03-sqlResultSetMappings/build.xml new file mode 100644 index 0000000..76cb48d --- /dev/null +++ b/examples/Chapter9/03-sqlResultSetMappings/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter9/03-sqlResultSetMappings/deploy.bat b/examples/Chapter9/03-sqlResultSetMappings/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter9/03-sqlResultSetMappings/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter9/03-sqlResultSetMappings/etc/persistence/META-INF/persistence.xml b/examples/Chapter9/03-sqlResultSetMappings/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..1eea466 --- /dev/null +++ b/examples/Chapter9/03-sqlResultSetMappings/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/sqlResultSetMappings + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/03-sqlResultSetMappings/etc/sql/db.sql b/examples/Chapter9/03-sqlResultSetMappings/etc/sql/db.sql new file mode 100644 index 0000000..317f6ef --- /dev/null +++ b/examples/Chapter9/03-sqlResultSetMappings/etc/sql/db.sql @@ -0,0 +1,39 @@ +DROP TABLE EMP; +DROP TABLE DEPARTMENT; +DROP TABLE ADDRESS; + +CREATE TABLE DEPARTMENT (ID INTEGER, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE ADDRESS (ID INTEGER NOT NULL, STREET VARCHAR(255), CITY VARCHAR(255), + STATE VARCHAR(255), ZIP VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMP (EMP_ID INTEGER, NAME VARCHAR(255), SALARY BIGINT, + MANAGER_ID INTEGER, DEPT_ID INTEGER, ADDRESS_ID INTEGER, PRIMARY KEY (EMP_ID), + CONSTRAINT MGR_FK FOREIGN KEY (MANAGER_ID) REFERENCES EMP (EMP_ID), + CONSTRAINT ADDRESS_FK FOREIGN KEY (ADDRESS_ID) REFERENCES ADDRESS (ID), + CONSTRAINT DEPT_FK FOREIGN KEY (DEPT_ID) REFERENCES DEPARTMENT (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 EMP (EMP_ID, NAME, SALARY, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (2, 'Joan', 59000, 10, 1, NULL); +INSERT INTO EMP (EMP_ID, NAME, SALARY, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (1, 'Sarah', 52000, 9, 2, 1); +INSERT INTO EMP (EMP_ID, NAME, SALARY, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (3, 'John', 55000, 1, 2, 2); +INSERT INTO EMP (EMP_ID, NAME, SALARY, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (4, 'Rob', 53000, 2, 2, 2); +INSERT INTO EMP (EMP_ID, NAME, SALARY, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (5, 'Peter', 50000, 3, 2, 2); +INSERT INTO EMP (EMP_ID, NAME, SALARY, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (6, 'Frank', 51000, 4, 1, 1); +INSERT INTO EMP (EMP_ID, NAME, SALARY, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (7, 'Scott', 60000, 5, 1, 1); +INSERT INTO EMP (EMP_ID, NAME, SALARY, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (8, 'Sue', 62000, 6, 1, 1); +INSERT INTO EMP (EMP_ID, NAME, SALARY, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (9, 'Stephanie', 54000, 7, 1, 1); +INSERT INTO EMP (EMP_ID, NAME, SALARY, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (10, 'Jennifer', 55000, 8, 1, NULL); +INSERT INTO EMP (EMP_ID, NAME, SALARY, ADDRESS_ID, DEPT_ID, MANAGER_ID) VALUES (11, 'Marcus', 35000, NULL, NULL, NULL); diff --git a/examples/Chapter9/03-sqlResultSetMappings/etc/web/WEB-INF/web.xml b/examples/Chapter9/03-sqlResultSetMappings/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter9/03-sqlResultSetMappings/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/Chapter9/03-sqlResultSetMappings/src/model/examples/model/Address.java b/examples/Chapter9/03-sqlResultSetMappings/src/model/examples/model/Address.java new file mode 100644 index 0000000..e18406b --- /dev/null +++ b/examples/Chapter9/03-sqlResultSetMappings/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/Chapter9/03-sqlResultSetMappings/src/model/examples/model/Department.java b/examples/Chapter9/03-sqlResultSetMappings/src/model/examples/model/Department.java new file mode 100644 index 0000000..42e0787 --- /dev/null +++ b/examples/Chapter9/03-sqlResultSetMappings/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/Chapter9/03-sqlResultSetMappings/src/model/examples/model/Employee.java b/examples/Chapter9/03-sqlResultSetMappings/src/model/examples/model/Employee.java new file mode 100644 index 0000000..23a19b0 --- /dev/null +++ b/examples/Chapter9/03-sqlResultSetMappings/src/model/examples/model/Employee.java @@ -0,0 +1,137 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Column; +import javax.persistence.ColumnResult; +import javax.persistence.Entity; +import javax.persistence.EntityResult; +import javax.persistence.FieldResult; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.OneToOne; +import javax.persistence.SqlResultSetMapping; +import javax.persistence.SqlResultSetMappings; +import javax.persistence.Table; + +@Entity +@Table(name="EMP") +@SqlResultSetMappings({ + @SqlResultSetMapping( + name="employeeResult", + entities=@EntityResult(entityClass=Employee.class)), + @SqlResultSetMapping( + name="EmployeeWithAddress", + entities={@EntityResult(entityClass=Employee.class), + @EntityResult(entityClass=Address.class)} + ), + @SqlResultSetMapping( + name="EmployeeWithAddressColumnAlias", + entities={@EntityResult(entityClass=Employee.class, + fields=@FieldResult(name="id", column="EMP_ID")), + @EntityResult(entityClass=Address.class)} + ), + @SqlResultSetMapping( + name="EmployeeAndManager", + columns={@ColumnResult(name="EMP_NAME"), + @ColumnResult(name="MANAGER_NAME")} + ), + @SqlResultSetMapping( + name="DepartmentSummary", + entities={@EntityResult(entityClass=Department.class, + fields=@FieldResult(name="name", column="DEPT_NAME")), + @EntityResult(entityClass=Employee.class)}, + columns={@ColumnResult(name="TOT_EMP"), + @ColumnResult(name="AVG_SAL")} + ) +}) +public class Employee { + @Id + @Column(name="EMP_ID") + private int id; + private String name; + private long salary; + + @OneToOne + private Address address; + + @ManyToOne + @JoinColumn(name="DEPT_ID") + private Department department; + + @ManyToOne + @JoinColumn(name="MANAGER_ID") + private Employee manager; + + @OneToMany(mappedBy="manager") + private Collection directs = 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 Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public Department getDepartment() { + return department; + } + + public void setDepartment(Department department) { + this.department = department; + } + + 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 String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " with MgrId: " + (getManager() == null ? null : getManager().getId()); + } +} diff --git a/examples/Chapter9/03-sqlResultSetMappings/src/model/examples/stateless/OrgStructure.java b/examples/Chapter9/03-sqlResultSetMappings/src/model/examples/stateless/OrgStructure.java new file mode 100644 index 0000000..d31de9b --- /dev/null +++ b/examples/Chapter9/03-sqlResultSetMappings/src/model/examples/stateless/OrgStructure.java @@ -0,0 +1,11 @@ +package examples.stateless; + +import java.util.List; + +public interface OrgStructure { + public List findAllEmployees(); + public List findEmployeeWithAddress(); + public List findEmployeeWithAddressColumnAlias(); + public List findEmployeeWithManager(); + public List findDepartmentSummary(); +} diff --git a/examples/Chapter9/03-sqlResultSetMappings/src/model/examples/stateless/OrgStructureBean.java b/examples/Chapter9/03-sqlResultSetMappings/src/model/examples/stateless/OrgStructureBean.java new file mode 100644 index 0000000..1d05f90 --- /dev/null +++ b/examples/Chapter9/03-sqlResultSetMappings/src/model/examples/stateless/OrgStructureBean.java @@ -0,0 +1,98 @@ +package examples.stateless; + +import java.util.List; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +@Stateless +public class OrgStructureBean implements OrgStructure { + @PersistenceContext(unitName="EmployeeService") + EntityManager em; + + + public List findAllEmployees() { +// Oracle-specific SQL string +// Query query = em.createNativeQuery( +// "SELECT emp_id, name, salary, manager_id, dept_id, address_id " + +// "FROM emp " + +// "START WITH manager_id IS NULL " + +// "CONNECT BY PRIOR emp_id = manager_id", +// "employeeResult"); + Query query = em.createNativeQuery( + "SELECT emp_id, name, salary, manager_id, " + + "dept_id, address_id " + + "FROM EMP ", + "employeeResult"); + return query.getResultList(); + } + + public List findEmployeeWithAddress() { + Query query = em.createNativeQuery( + "SELECT emp_id, name, salary, manager_id, dept_id, address_id, " + + "id, street, city, state, zip " + + "FROM emp, address " + + "WHERE address_id = id", + "EmployeeWithAddress"); + return query.getResultList(); + } + + public List findEmployeeWithAddressColumnAlias() { + Query query = em.createNativeQuery( + "SELECT emp.emp_id AS emp_id, name, salary, manager_id, dept_id, address_id, " + + "address.id, street, city, state, zip " + + "FROM emp, address " + + "WHERE address_id = id", + "EmployeeWithAddressColumnAlias"); + return query.getResultList(); + } + + public List findEmployeeWithManager() { +// Oracle-specific SQL string +// Query query = em.createNativeQuery( +// "SELECT e.name AS emp_name, m.name AS manager_name " + +// "FROM emp e, emp m " + +// "WHERE e.manager_id = m.emp_id (+) " + +// "START WITH e.manager_id IS NULL " + +// "CONNECT BY PRIOR e.emp_id = e.manager_id", +// "EmployeeWithManager"); +// Derby SQL string (not the equivalent to above) + Query query = em.createNativeQuery( + "SELECT e.name AS emp_name, m.name AS manager_name " + + "FROM emp e, emp m " + + "WHERE e.manager_id = m.emp_id", + "EmployeeAndManager"); + return query.getResultList(); + } + + public List findDepartmentSummary() { +/* Query query = em.createNativeQuery( + "SELECT d.id, d.name AS dept_name, " + + "e.emp_id, e.name, e.salary, e.manager_id, e.dept_id, e.address_id, " + + "s.tot_emp, s.avg_sal " + + "FROM dept d, " + + "(SELECT * " + + "FROM emp e " + + "WHERE EXISTS(SELECT 1 FROM emp WHERE manager_id = e.emp_id)) e, " + + "(SELECT d.id, COUNT(*) AS tot_emp, AVG(e.salary) AS avg_sal " + + "FROM dept d, emp e " + + "WHERE d.id = e.dept_id (+) " + + "GROUP BY d.id) s " + + "WHERE d.id = e.dept_id (+) AND " + + "d.id = s.id", + "DepartmentSummary"); +*/ + Query query = em.createQuery( + "SELECT d, m, COUNT(e), AVG(e.salary) " + +"FROM Department d LEFT JOIN e.employees e " + +"LEFT JOIN e.employees m " + +"WHERE m IS NULL OR m IN (SELECT de.manager " + + "FROM Employee de " + + "WHERE de.department = d) " + +"GROUP BY d, m"); + return query.getResultList(); + } +} + diff --git a/examples/Chapter9/03-sqlResultSetMappings/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter9/03-sqlResultSetMappings/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..9d8660c --- /dev/null +++ b/examples/Chapter9/03-sqlResultSetMappings/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,105 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; +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.OrgStructure; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 9: SqlResultSetMappings Example"; + + private final String DESCRIPTION = + "This example demonstates various SqlResultSetMapping constructs."; + + + @EJB + OrgStructure orgStructure; + + 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("FindAll")) { + List emps = orgStructure.findAllEmployees(); + out.println("Found All:
"); + printCollection(emps, out); + } else if (action.equals("FindEmployeeWithAddress")) { + List emps = orgStructure.findEmployeeWithAddress(); + out.println("Found All:
"); + printCollection(emps, out); + } else if (action.equals("FindEmployeeWithAddressColumnAlias")) { + List emps = orgStructure.findEmployeeWithAddressColumnAlias(); + out.println("Found All:
"); + printCollection(emps, out); + } else if (action.equals("FindEmployeeWithManager")) { + List emps = orgStructure.findEmployeeWithManager(); + out.println("Found Employees with Manager:
"); + printCollection(emps, out); + } else if (action.equals("FindDepartmentSummary")) { + List emps = orgStructure.findDepartmentSummary(); + out.println("Found Department Summaries:
"); + printCollection(emps, out); + } + + 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) { + if (o instanceof Object[]) { + for (Object o2 : (Object[])o) { + out.println(o2 + " : "); + } + out.println("
"); + } else { + out.println(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 create and Employee and Department + out.println("

Find Employees:

"); + out.println(""); + out.println(""); + 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/Chapter9/03-sqlResultSetMappings/undeploy.bat b/examples/Chapter9/03-sqlResultSetMappings/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter9/03-sqlResultSetMappings/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter9/04-idClassResultMapping/build.xml b/examples/Chapter9/04-idClassResultMapping/build.xml new file mode 100644 index 0000000..693b86a --- /dev/null +++ b/examples/Chapter9/04-idClassResultMapping/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter9/04-idClassResultMapping/deploy.bat b/examples/Chapter9/04-idClassResultMapping/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter9/04-idClassResultMapping/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter9/04-idClassResultMapping/etc/persistence/META-INF/persistence.xml b/examples/Chapter9/04-idClassResultMapping/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..cd231dd --- /dev/null +++ b/examples/Chapter9/04-idClassResultMapping/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/idClassResultMapping + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/04-idClassResultMapping/etc/sql/db.sql b/examples/Chapter9/04-idClassResultMapping/etc/sql/db.sql new file mode 100644 index 0000000..216d09a --- /dev/null +++ b/examples/Chapter9/04-idClassResultMapping/etc/sql/db.sql @@ -0,0 +1,17 @@ +DROP TABLE EMP; + +CREATE TABLE EMP (COUNTRY VARCHAR(255) NOT NULL, EMP_ID INTEGER NOT NULL, NAME VARCHAR(255), + SALARY BIGINT, MANAGER_COUNTRY VARCHAR(255), MANAGER_ID INTEGER, PRIMARY KEY(COUNTRY,EMP_ID), + CONSTRAINT MGR_FK FOREIGN KEY (MANAGER_COUNTRY,MANAGER_ID) REFERENCES EMP (COUNTRY,EMP_ID)); + +INSERT INTO EMP (COUNTRY, EMP_ID, NAME, SALARY, MANAGER_COUNTRY, MANAGER_ID) VALUES ('Canada', 1, 'Joan', 59000, NULL, NULL); +INSERT INTO EMP (COUNTRY, EMP_ID, NAME, SALARY, MANAGER_COUNTRY, MANAGER_ID) VALUES ('US', 2, 'Sarah', 52000, 'Canada', 1); +INSERT INTO EMP (COUNTRY, EMP_ID, NAME, SALARY, MANAGER_COUNTRY, MANAGER_ID) VALUES ('US', 3, 'John', 55000, 'US', 2); +INSERT INTO EMP (COUNTRY, EMP_ID, NAME, SALARY, MANAGER_COUNTRY, MANAGER_ID) VALUES ('US', 4, 'Rob', 53000, 'US', 2); +INSERT INTO EMP (COUNTRY, EMP_ID, NAME, SALARY, MANAGER_COUNTRY, MANAGER_ID) VALUES ('US', 5, 'Peter', 50000, 'US', 2); +INSERT INTO EMP (COUNTRY, EMP_ID, NAME, SALARY, MANAGER_COUNTRY, MANAGER_ID) VALUES ('Canada', 6, 'Frank', 51000, 'Canada', 1); +INSERT INTO EMP (COUNTRY, EMP_ID, NAME, SALARY, MANAGER_COUNTRY, MANAGER_ID) VALUES ('US', 7, 'Scott', 60000, 'Canada', 1); +INSERT INTO EMP (COUNTRY, EMP_ID, NAME, SALARY, MANAGER_COUNTRY, MANAGER_ID) VALUES ('Canada', 8, 'Sue', 62000, 'Canada', 1); +INSERT INTO EMP (COUNTRY, EMP_ID, NAME, SALARY, MANAGER_COUNTRY, MANAGER_ID) VALUES ('US', 9, 'Stephanie', 54000, 'Canada', 1); +INSERT INTO EMP (COUNTRY, EMP_ID, NAME, SALARY, MANAGER_COUNTRY, MANAGER_ID) VALUES ('Canada', 10, 'Jennifer', 55000, NULL, NULL); +INSERT INTO EMP (COUNTRY, EMP_ID, NAME, SALARY, MANAGER_COUNTRY, MANAGER_ID) VALUES ('Canada', 11, 'Marcus', 35000, NULL, NULL); diff --git a/examples/Chapter9/04-idClassResultMapping/etc/web/WEB-INF/web.xml b/examples/Chapter9/04-idClassResultMapping/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter9/04-idClassResultMapping/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/Chapter9/04-idClassResultMapping/src/model/examples/model/Employee.java b/examples/Chapter9/04-idClassResultMapping/src/model/examples/model/Employee.java new file mode 100644 index 0000000..e6d12b6 --- /dev/null +++ b/examples/Chapter9/04-idClassResultMapping/src/model/examples/model/Employee.java @@ -0,0 +1,115 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EntityResult; +import javax.persistence.FieldResult; +import javax.persistence.Id; +import javax.persistence.IdClass; +import javax.persistence.JoinColumn; +import javax.persistence.JoinColumns; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.SqlResultSetMapping; +import javax.persistence.Table; + +@Entity +@Table(name="EMP") +@IdClass(EmployeeId.class) +@SqlResultSetMapping( + name="EmployeeAndManager", + entities={ + @EntityResult(entityClass=Employee.class), + @EntityResult( + entityClass=Employee.class, + fields={ + @FieldResult(name="country", column="MGR_COUNTRY"), + @FieldResult(name="id", column="MGR_ID"), + @FieldResult(name="name", column="MGR_NAME"), + @FieldResult(name="salary", column="MGR_SALARY"), + @FieldResult(name="manager.country", column="MGR_MGR_COUNTRY"), + @FieldResult(name="manager.id", column="MGR_MGR_ID") + } + ) + } +) +public class Employee { + @Id private String country; + @Id + @Column(name="EMP_ID") + private int id; + private String name; + private long salary; + + @ManyToOne + @JoinColumns({ + @JoinColumn(name="MANAGER_COUNTRY", referencedColumnName="COUNTRY"), + @JoinColumn(name="MANAGER_ID", referencedColumnName="EMP_ID") + }) + private Employee manager; + + @OneToMany(mappedBy="manager") + private Collection directs = new ArrayList(); + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + 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 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 String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " country: " + getCountry(); + } +} diff --git a/examples/Chapter9/04-idClassResultMapping/src/model/examples/model/EmployeeId.java b/examples/Chapter9/04-idClassResultMapping/src/model/examples/model/EmployeeId.java new file mode 100644 index 0000000..031521a --- /dev/null +++ b/examples/Chapter9/04-idClassResultMapping/src/model/examples/model/EmployeeId.java @@ -0,0 +1,28 @@ +package examples.model; + +import java.io.Serializable; + +public class EmployeeId implements Serializable { + private String country; + private int id; + + public EmployeeId() {} + public EmployeeId(String country, int id) { + this.country = country; + this.id = id; + } + + public String getCountry() { return country; } + public int getId() { return id; } + + public boolean equals(Object o) { + return ((o instanceof EmployeeId) && + country.equals(((EmployeeId)o).getCountry()) && + id == ((EmployeeId) o).getId()); + + } + + public int hashCode() { + return country.hashCode() + id; + } +} \ No newline at end of file diff --git a/examples/Chapter9/04-idClassResultMapping/src/model/examples/stateless/EmployeeService.java b/examples/Chapter9/04-idClassResultMapping/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..76504e4 --- /dev/null +++ b/examples/Chapter9/04-idClassResultMapping/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,7 @@ +package examples.stateless; + +import java.util.List; + +public interface EmployeeService { + public List findEmployeeWithManager(); +} diff --git a/examples/Chapter9/04-idClassResultMapping/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter9/04-idClassResultMapping/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..2358814 --- /dev/null +++ b/examples/Chapter9/04-idClassResultMapping/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,27 @@ +package examples.stateless; + +import java.util.List; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public List findEmployeeWithManager() { + Query query = em.createNativeQuery( + "SELECT e.country, e.emp_id, e.name, e.salary, " + + "e.manager_country, e.manager_id, m.country AS mgr_country, " + + "m.emp_id AS mgr_id, m.name AS mgr_name, m.salary AS mgr_salary, " + + "m.manager_country AS mgr_mgr_country, m.manager_id AS mgr_mgr_id " + + "FROM emp e, emp m " + + "WHERE e.manager_country = m.country AND " + + "e.manager_id = m.emp_id ", + "EmployeeAndManager"); + return query.getResultList(); + } +} diff --git a/examples/Chapter9/04-idClassResultMapping/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter9/04-idClassResultMapping/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..43a7cab --- /dev/null +++ b/examples/Chapter9/04-idClassResultMapping/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,84 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; +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 EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 9: Using SqlResultSetMapping with a Compound Primary Key Example"; + + private final String DESCRIPTION = + "This example demonstates the basics of using SqlResultSetMappings with " + + "compound primary keys."; + + @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("Find")) { + List emps = service.findEmployeeWithManager(); + out.println("Found Employees with Manager:
"); + printCollection(emps, out); + } + + 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) { + if (o instanceof Object[]) { + for (Object o2 : (Object[])o) { + out.println(o2 + " : "); + } + out.println("
"); + } else { + out.println(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 create and Employee + out.println("

Find all Employees with Manager

"); + 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-idClassResultMapping/undeploy.bat b/examples/Chapter9/04-idClassResultMapping/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter9/04-idClassResultMapping/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter9/05-embeddedIdResultMapping/build.xml b/examples/Chapter9/05-embeddedIdResultMapping/build.xml new file mode 100644 index 0000000..44b82d2 --- /dev/null +++ b/examples/Chapter9/05-embeddedIdResultMapping/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter9/05-embeddedIdResultMapping/deploy.bat b/examples/Chapter9/05-embeddedIdResultMapping/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter9/05-embeddedIdResultMapping/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter9/05-embeddedIdResultMapping/etc/persistence/META-INF/persistence.xml b/examples/Chapter9/05-embeddedIdResultMapping/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..9a9fca4 --- /dev/null +++ b/examples/Chapter9/05-embeddedIdResultMapping/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/embeddedIdResultMapping + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/05-embeddedIdResultMapping/etc/sql/db.sql b/examples/Chapter9/05-embeddedIdResultMapping/etc/sql/db.sql new file mode 100644 index 0000000..216d09a --- /dev/null +++ b/examples/Chapter9/05-embeddedIdResultMapping/etc/sql/db.sql @@ -0,0 +1,17 @@ +DROP TABLE EMP; + +CREATE TABLE EMP (COUNTRY VARCHAR(255) NOT NULL, EMP_ID INTEGER NOT NULL, NAME VARCHAR(255), + SALARY BIGINT, MANAGER_COUNTRY VARCHAR(255), MANAGER_ID INTEGER, PRIMARY KEY(COUNTRY,EMP_ID), + CONSTRAINT MGR_FK FOREIGN KEY (MANAGER_COUNTRY,MANAGER_ID) REFERENCES EMP (COUNTRY,EMP_ID)); + +INSERT INTO EMP (COUNTRY, EMP_ID, NAME, SALARY, MANAGER_COUNTRY, MANAGER_ID) VALUES ('Canada', 1, 'Joan', 59000, NULL, NULL); +INSERT INTO EMP (COUNTRY, EMP_ID, NAME, SALARY, MANAGER_COUNTRY, MANAGER_ID) VALUES ('US', 2, 'Sarah', 52000, 'Canada', 1); +INSERT INTO EMP (COUNTRY, EMP_ID, NAME, SALARY, MANAGER_COUNTRY, MANAGER_ID) VALUES ('US', 3, 'John', 55000, 'US', 2); +INSERT INTO EMP (COUNTRY, EMP_ID, NAME, SALARY, MANAGER_COUNTRY, MANAGER_ID) VALUES ('US', 4, 'Rob', 53000, 'US', 2); +INSERT INTO EMP (COUNTRY, EMP_ID, NAME, SALARY, MANAGER_COUNTRY, MANAGER_ID) VALUES ('US', 5, 'Peter', 50000, 'US', 2); +INSERT INTO EMP (COUNTRY, EMP_ID, NAME, SALARY, MANAGER_COUNTRY, MANAGER_ID) VALUES ('Canada', 6, 'Frank', 51000, 'Canada', 1); +INSERT INTO EMP (COUNTRY, EMP_ID, NAME, SALARY, MANAGER_COUNTRY, MANAGER_ID) VALUES ('US', 7, 'Scott', 60000, 'Canada', 1); +INSERT INTO EMP (COUNTRY, EMP_ID, NAME, SALARY, MANAGER_COUNTRY, MANAGER_ID) VALUES ('Canada', 8, 'Sue', 62000, 'Canada', 1); +INSERT INTO EMP (COUNTRY, EMP_ID, NAME, SALARY, MANAGER_COUNTRY, MANAGER_ID) VALUES ('US', 9, 'Stephanie', 54000, 'Canada', 1); +INSERT INTO EMP (COUNTRY, EMP_ID, NAME, SALARY, MANAGER_COUNTRY, MANAGER_ID) VALUES ('Canada', 10, 'Jennifer', 55000, NULL, NULL); +INSERT INTO EMP (COUNTRY, EMP_ID, NAME, SALARY, MANAGER_COUNTRY, MANAGER_ID) VALUES ('Canada', 11, 'Marcus', 35000, NULL, NULL); diff --git a/examples/Chapter9/05-embeddedIdResultMapping/etc/web/WEB-INF/web.xml b/examples/Chapter9/05-embeddedIdResultMapping/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter9/05-embeddedIdResultMapping/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/Chapter9/05-embeddedIdResultMapping/src/model/examples/model/Employee.java b/examples/Chapter9/05-embeddedIdResultMapping/src/model/examples/model/Employee.java new file mode 100644 index 0000000..2c98f24 --- /dev/null +++ b/examples/Chapter9/05-embeddedIdResultMapping/src/model/examples/model/Employee.java @@ -0,0 +1,106 @@ +package examples.model; + +import java.util.ArrayList; +import java.util.Collection; + +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; +import javax.persistence.EntityResult; +import javax.persistence.FieldResult; +import javax.persistence.JoinColumn; +import javax.persistence.JoinColumns; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; +import javax.persistence.SqlResultSetMapping; +import javax.persistence.Table; + +@Entity +@Table(name="EMP") +@SqlResultSetMapping( + name="EmployeeAndManager", + entities={ + @EntityResult(entityClass=Employee.class), + @EntityResult( + entityClass=Employee.class, + fields={ + @FieldResult(name="id.country", column="MGR_COUNTRY"), + @FieldResult(name="id.id", column="MGR_ID"), + @FieldResult(name="name", column="MGR_NAME"), + @FieldResult(name="salary", column="MGR_SALARY"), + @FieldResult(name="manager.id.country", column="MGR_MGR_COUNTRY"), + @FieldResult(name="manager.id.id", column="MGR_MGR_ID") + } + ) + } +) +public class Employee { + @EmbeddedId + private EmployeeId id; + private String name; + private long salary; + + @ManyToOne + @JoinColumns({ + @JoinColumn(name="MANAGER_COUNTRY", referencedColumnName="COUNTRY"), + @JoinColumn(name="MANAGER_ID", referencedColumnName="EMP_ID") + }) + private Employee manager; + + @OneToMany(mappedBy="manager") + private Collection directs = new ArrayList(); + + public Employee() {} + public Employee(String country, int id) { + this.id = new EmployeeId(country, id); + } + + public int getId() { + return id.getId(); + } + + public String getCountry() { + return id.getCountry(); + } + + 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 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 String toString() { + return "Employee id: " + getId() + " name: " + getName() + " country: " + getCountry(); + } +} diff --git a/examples/Chapter9/05-embeddedIdResultMapping/src/model/examples/model/EmployeeId.java b/examples/Chapter9/05-embeddedIdResultMapping/src/model/examples/model/EmployeeId.java new file mode 100644 index 0000000..24c5cc5 --- /dev/null +++ b/examples/Chapter9/05-embeddedIdResultMapping/src/model/examples/model/EmployeeId.java @@ -0,0 +1,32 @@ +package examples.model; + +import javax.persistence.Column; +import javax.persistence.Embeddable; + +@Embeddable +public class EmployeeId { + private String country; + @Column(name="EMP_ID") + private int id; + + public EmployeeId() {} + public EmployeeId(String country, int id) { + this.country = country; + this.id = id; + } + + + public String getCountry() { return country; } + public int getId() { return id; } + + public boolean equals(Object o) { + return ((o instanceof EmployeeId) && + country.equals(((EmployeeId)o).getCountry()) && + id == ((EmployeeId) o).getId()); + + } + + public int hashCode() { + return country.hashCode() + id; + } +} \ No newline at end of file diff --git a/examples/Chapter9/05-embeddedIdResultMapping/src/model/examples/stateless/EmployeeService.java b/examples/Chapter9/05-embeddedIdResultMapping/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..76504e4 --- /dev/null +++ b/examples/Chapter9/05-embeddedIdResultMapping/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,7 @@ +package examples.stateless; + +import java.util.List; + +public interface EmployeeService { + public List findEmployeeWithManager(); +} diff --git a/examples/Chapter9/05-embeddedIdResultMapping/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter9/05-embeddedIdResultMapping/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..2358814 --- /dev/null +++ b/examples/Chapter9/05-embeddedIdResultMapping/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,27 @@ +package examples.stateless; + +import java.util.List; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public List findEmployeeWithManager() { + Query query = em.createNativeQuery( + "SELECT e.country, e.emp_id, e.name, e.salary, " + + "e.manager_country, e.manager_id, m.country AS mgr_country, " + + "m.emp_id AS mgr_id, m.name AS mgr_name, m.salary AS mgr_salary, " + + "m.manager_country AS mgr_mgr_country, m.manager_id AS mgr_mgr_id " + + "FROM emp e, emp m " + + "WHERE e.manager_country = m.country AND " + + "e.manager_id = m.emp_id ", + "EmployeeAndManager"); + return query.getResultList(); + } +} diff --git a/examples/Chapter9/05-embeddedIdResultMapping/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter9/05-embeddedIdResultMapping/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..f2b17f4 --- /dev/null +++ b/examples/Chapter9/05-embeddedIdResultMapping/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,84 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; +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 EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 9: Using SqlResultSetMapping with an Embedded Id Example"; + + private final String DESCRIPTION = + "This example demonstates the basics of using SqlResultSetMappings with " + + "embedded ids."; + + @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("Find")) { + List emps = service.findEmployeeWithManager(); + out.println("Found Employees with Manager:
"); + printCollection(emps, out); + } + + 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) { + if (o instanceof Object[]) { + for (Object o2 : (Object[])o) { + out.println(o2 + " : "); + } + out.println("
"); + } else { + out.println(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 create and Employee + out.println("

Find all Employees with Manager

"); + 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/05-embeddedIdResultMapping/undeploy.bat b/examples/Chapter9/05-embeddedIdResultMapping/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter9/05-embeddedIdResultMapping/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter9/06-inheritanceResultMapping/build.xml b/examples/Chapter9/06-inheritanceResultMapping/build.xml new file mode 100644 index 0000000..1e32e15 --- /dev/null +++ b/examples/Chapter9/06-inheritanceResultMapping/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter9/06-inheritanceResultMapping/deploy.bat b/examples/Chapter9/06-inheritanceResultMapping/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter9/06-inheritanceResultMapping/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter9/06-inheritanceResultMapping/etc/persistence/META-INF/persistence.xml b/examples/Chapter9/06-inheritanceResultMapping/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..c007cef --- /dev/null +++ b/examples/Chapter9/06-inheritanceResultMapping/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/inheritanceResultMapping + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/06-inheritanceResultMapping/etc/sql/db.sql b/examples/Chapter9/06-inheritanceResultMapping/etc/sql/db.sql new file mode 100644 index 0000000..64aaea7 --- /dev/null +++ b/examples/Chapter9/06-inheritanceResultMapping/etc/sql/db.sql @@ -0,0 +1,27 @@ +DROP TABLE EMPLOYEE_STAGE; + +CREATE TABLE EMPLOYEE_STAGE (ID INTEGER NOT NULL, NAME VARCHAR(255), START_DATE DATE, DAILY_RATE INTEGER, TERM INTEGER, + VACATION INTEGER, HOURLY_RATE FLOAT, SALARY BIGINT, PENSION BIGINT, TYPE VARCHAR(32), + PRIMARY KEY (ID)); + +INSERT INTO EMPLOYEE_STAGE (ID, NAME, START_DATE, DAILY_RATE, TERM, VACATION, HOURLY_RATE, SALARY, PENSION, TYPE) + VALUES (1, 'John', {d '2001-01-01'}, 500, 12, NULL, NULL, NULL, NULL, 'ContractEmployee'); +INSERT INTO EMPLOYEE_STAGE (ID, NAME, START_DATE, DAILY_RATE, TERM, VACATION, HOURLY_RATE, SALARY, PENSION, TYPE) + VALUES (2, 'Paul', {d '2002-04-08'}, 600, 24, NULL, NULL, NULL, NULL, 'ContractEmployee'); +INSERT INTO EMPLOYEE_STAGE (ID, NAME, START_DATE, DAILY_RATE, TERM, VACATION, HOURLY_RATE, SALARY, PENSION, TYPE) + VALUES (3, 'Sarah', {d '2003-06-10'}, 700, 18, NULL, NULL, NULL, NULL, 'ContractEmployee'); + +INSERT INTO EMPLOYEE_STAGE (ID, NAME, START_DATE, DAILY_RATE, TERM, VACATION, HOURLY_RATE, SALARY, PENSION, TYPE) + VALUES (4, 'Patrick', {d '2004-07-01'}, NULL, NULL, 15, NULL, 55000, 100000, 'FTEmp'); +INSERT INTO EMPLOYEE_STAGE (ID, NAME, START_DATE, DAILY_RATE, TERM, VACATION, HOURLY_RATE, SALARY, PENSION, TYPE) + VALUES (5, 'Joan', {d '2003-09-09'}, NULL, NULL, 15, NULL, 59000, 200000, 'FTEmp'); +INSERT INTO EMPLOYEE_STAGE (ID, NAME, START_DATE, DAILY_RATE, TERM, VACATION, HOURLY_RATE, SALARY, PENSION, TYPE) + VALUES (6, 'Samantha', {d '2000-03-12'}, NULL, NULL, 20, NULL, 60000, 450000, 'FTEmp'); + +INSERT INTO EMPLOYEE_STAGE (ID, NAME, START_DATE, DAILY_RATE, TERM, VACATION, HOURLY_RATE, SALARY, PENSION, TYPE) + VALUES (7, 'Mark', {d '2004-11-01'}, NULL, NULL, 15, 17.0, NULL, NULL, 'PTEmp'); +INSERT INTO EMPLOYEE_STAGE (ID, NAME, START_DATE, DAILY_RATE, TERM, VACATION, HOURLY_RATE, SALARY, PENSION, TYPE) + VALUES (8, 'Ryan', {d '2005-12-05'}, NULL, NULL, 15, 16.0, NULL, NULL, 'PTEmp'); +INSERT INTO EMPLOYEE_STAGE (ID, NAME, START_DATE, DAILY_RATE, TERM, VACATION, HOURLY_RATE, SALARY, PENSION, TYPE) + VALUES (9, 'Jackie', {d '2006-01-03'}, NULL, NULL, 10, 15.0, NULL, NULL, 'PTEmp'); + diff --git a/examples/Chapter9/06-inheritanceResultMapping/etc/web/WEB-INF/web.xml b/examples/Chapter9/06-inheritanceResultMapping/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter9/06-inheritanceResultMapping/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/Chapter9/06-inheritanceResultMapping/src/model/examples/model/CachedEntity.java b/examples/Chapter9/06-inheritanceResultMapping/src/model/examples/model/CachedEntity.java new file mode 100644 index 0000000..c98d419 --- /dev/null +++ b/examples/Chapter9/06-inheritanceResultMapping/src/model/examples/model/CachedEntity.java @@ -0,0 +1,13 @@ +package examples.model; + +public abstract class CachedEntity { + private long createTime; + + public CachedEntity() { + createTime = System.currentTimeMillis(); + } + + public long getCacheAge() { + return System.currentTimeMillis() - createTime; + } +} diff --git a/examples/Chapter9/06-inheritanceResultMapping/src/model/examples/model/CompanyEmployee.java b/examples/Chapter9/06-inheritanceResultMapping/src/model/examples/model/CompanyEmployee.java new file mode 100644 index 0000000..4483a62 --- /dev/null +++ b/examples/Chapter9/06-inheritanceResultMapping/src/model/examples/model/CompanyEmployee.java @@ -0,0 +1,16 @@ +package examples.model; + +import javax.persistence.MappedSuperclass; + +@MappedSuperclass +public abstract class CompanyEmployee extends Employee { + private int vacation; + + public int getVacation() { + return vacation; + } + + public void setVacation(int vacation) { + this.vacation = vacation; + } +} diff --git a/examples/Chapter9/06-inheritanceResultMapping/src/model/examples/model/ContractEmployee.java b/examples/Chapter9/06-inheritanceResultMapping/src/model/examples/model/ContractEmployee.java new file mode 100644 index 0000000..4f5fa92 --- /dev/null +++ b/examples/Chapter9/06-inheritanceResultMapping/src/model/examples/model/ContractEmployee.java @@ -0,0 +1,31 @@ +package examples.model; + +import javax.persistence.Column; +import javax.persistence.Entity; + +@Entity +public class ContractEmployee extends Employee { + @Column(name="DAILY_RATE") + private int dailyRate; + private int term; + + public int getDailyRate() { + return dailyRate; + } + + public void setDailyRate(int dailyRate) { + this.dailyRate = dailyRate; + } + + public int getTerm() { + return term; + } + + public void setTerm(int term) { + this.term = term; + } + + public String toString() { + return "ContractEmployee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter9/06-inheritanceResultMapping/src/model/examples/model/Employee.java b/examples/Chapter9/06-inheritanceResultMapping/src/model/examples/model/Employee.java new file mode 100644 index 0000000..9ba60f4 --- /dev/null +++ b/examples/Chapter9/06-inheritanceResultMapping/src/model/examples/model/Employee.java @@ -0,0 +1,68 @@ +package examples.model; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.DiscriminatorColumn; +import javax.persistence.Entity; +import javax.persistence.EntityResult; +import javax.persistence.FieldResult; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.SqlResultSetMapping; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@Table(name="EMPLOYEE_STAGE") +@Inheritance +@DiscriminatorColumn(name="EMP_TYPE") +@SqlResultSetMapping( + name="EmployeeStageMapping", + entities= + @EntityResult( + entityClass=Employee.class, + discriminatorColumn="TYPE", + fields={ + @FieldResult(name="startDate", column="START_DATE"), + @FieldResult(name="dailyRate", column="DAILY_RATE"), + @FieldResult(name="hourlyRate", column="HOURLY_RATE") + } + ) +) +public abstract class Employee extends CachedEntity { + @Id private int id; + private String name; + @Temporal(TemporalType.DATE) + @Column(name="START_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 Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter9/06-inheritanceResultMapping/src/model/examples/model/FullTimeEmployee.java b/examples/Chapter9/06-inheritanceResultMapping/src/model/examples/model/FullTimeEmployee.java new file mode 100644 index 0000000..bec3b48 --- /dev/null +++ b/examples/Chapter9/06-inheritanceResultMapping/src/model/examples/model/FullTimeEmployee.java @@ -0,0 +1,31 @@ +package examples.model; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; + +@Entity +@DiscriminatorValue("FTEmp") +public class FullTimeEmployee extends CompanyEmployee { + private long salary; + private long pension; + + public long getPension() { + return pension; + } + + public void setPension(long pension) { + this.pension = pension; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public String toString() { + return "FullTimeEmployee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter9/06-inheritanceResultMapping/src/model/examples/model/PartTimeEmployee.java b/examples/Chapter9/06-inheritanceResultMapping/src/model/examples/model/PartTimeEmployee.java new file mode 100644 index 0000000..c981ca6 --- /dev/null +++ b/examples/Chapter9/06-inheritanceResultMapping/src/model/examples/model/PartTimeEmployee.java @@ -0,0 +1,24 @@ +package examples.model; + +import javax.persistence.Column; +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; + +@Entity(name="PTEmp") +@DiscriminatorValue("PTEmp") +public class PartTimeEmployee extends CompanyEmployee { + @Column(name="HOURLY_RATE") + private float hourlyRate; + + public float getHourlyRate() { + return hourlyRate; + } + + public void setHourlyRate(float hourlyRate) { + this.hourlyRate = hourlyRate; + } + + public String toString() { + return "PartTimeEmployee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter9/06-inheritanceResultMapping/src/model/examples/stateless/EmployeeService.java b/examples/Chapter9/06-inheritanceResultMapping/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..4cd577d --- /dev/null +++ b/examples/Chapter9/06-inheritanceResultMapping/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,7 @@ +package examples.stateless; + +import java.util.List; + +public interface EmployeeService { + public List findAllEmployees(); +} diff --git a/examples/Chapter9/06-inheritanceResultMapping/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter9/06-inheritanceResultMapping/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..1bb2df7 --- /dev/null +++ b/examples/Chapter9/06-inheritanceResultMapping/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,23 @@ +package examples.stateless; + +import java.util.List; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public List findAllEmployees() { + Query query = em.createNativeQuery( + "SELECT id, name, start_date, daily_rate, term, vacation, " + + "hourly_rate, salary, pension, type " + + "FROM employee_stage", + "EmployeeStageMapping"); + return query.getResultList(); + } +} diff --git a/examples/Chapter9/06-inheritanceResultMapping/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter9/06-inheritanceResultMapping/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..1779c2f --- /dev/null +++ b/examples/Chapter9/06-inheritanceResultMapping/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,85 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Collection; +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.stateless.EmployeeService; + +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 9: Using SqlResultSetMapping with a Inheritance Example"; + + private final String DESCRIPTION = + "This example demonstates the basics of using SqlResultSetMappings with " + + "inheritance."; + + @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("Find")) { + List emps = service.findAllEmployees(); + out.println("Found All:
"); + printCollection(emps, out); + } + + 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) { + if (o instanceof Object[]) { + for (Object o2 : (Object[])o) { + out.println(o2 + " : "); + } + out.println("
"); + } else { + out.println(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 create and Employee + out.println("

Find all Employees

"); + 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-inheritanceResultMapping/undeploy.bat b/examples/Chapter9/06-inheritanceResultMapping/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter9/06-inheritanceResultMapping/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter9/07-lifecycleCallbacks/build.xml b/examples/Chapter9/07-lifecycleCallbacks/build.xml new file mode 100644 index 0000000..42a0553 --- /dev/null +++ b/examples/Chapter9/07-lifecycleCallbacks/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter9/07-lifecycleCallbacks/deploy.bat b/examples/Chapter9/07-lifecycleCallbacks/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter9/07-lifecycleCallbacks/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter9/07-lifecycleCallbacks/etc/persistence/META-INF/persistence.xml b/examples/Chapter9/07-lifecycleCallbacks/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..87afb01 --- /dev/null +++ b/examples/Chapter9/07-lifecycleCallbacks/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/lifecycleCallbacks + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/07-lifecycleCallbacks/etc/sql/db.sql b/examples/Chapter9/07-lifecycleCallbacks/etc/sql/db.sql new file mode 100644 index 0000000..bbfe507 --- /dev/null +++ b/examples/Chapter9/07-lifecycleCallbacks/etc/sql/db.sql @@ -0,0 +1,3 @@ +DROP TABLE EMPLOYEE; + +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); \ No newline at end of file diff --git a/examples/Chapter9/07-lifecycleCallbacks/etc/web/WEB-INF/web.xml b/examples/Chapter9/07-lifecycleCallbacks/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter9/07-lifecycleCallbacks/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/Chapter9/07-lifecycleCallbacks/src/model/examples/model/Employee.java b/examples/Chapter9/07-lifecycleCallbacks/src/model/examples/model/Employee.java new file mode 100644 index 0000000..9085a92 --- /dev/null +++ b/examples/Chapter9/07-lifecycleCallbacks/src/model/examples/model/Employee.java @@ -0,0 +1,49 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.EntityListeners; +import javax.persistence.Id; +import javax.persistence.PostLoad; +import javax.persistence.PostPersist; +import javax.persistence.PostUpdate; +import javax.persistence.Transient; + +@Entity +@EntityListeners({EmployeeDebugListener.class, NameValidator.class}) +public class Employee implements NamedEntity { + @Id private int id; + private String name; + @Transient private long syncTime; + + @PostPersist + @PostUpdate + @PostLoad + private void resetSyncTime() { + syncTime = System.currentTimeMillis(); + System.out.println("Employee.resetSyncTime called on employee id: " + getId()); + } + + public long getCachedAge() { + return System.currentTimeMillis() - syncTime; + } + + 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 String toString() { + return "Employee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter9/07-lifecycleCallbacks/src/model/examples/model/EmployeeDebugListener.java b/examples/Chapter9/07-lifecycleCallbacks/src/model/examples/model/EmployeeDebugListener.java new file mode 100644 index 0000000..b00e8de --- /dev/null +++ b/examples/Chapter9/07-lifecycleCallbacks/src/model/examples/model/EmployeeDebugListener.java @@ -0,0 +1,29 @@ +package examples.model; + +import javax.persistence.PostLoad; +import javax.persistence.PrePersist; +import javax.persistence.PreRemove; +import javax.persistence.PreUpdate; + +public class EmployeeDebugListener { + @PrePersist + public void prePersist(Employee emp) { + System.out.println("EmployeeDebugListener.Persist called on employee id: " + emp.getId()); + } + + @PreUpdate + public void preUpdate(Employee emp) { + System.out.println("EmployeeDebugListener.Update called on employee id: " + emp.getId()); +} + + @PreRemove + public void preRemove(Employee emp) { + System.out.println("EmployeeDebugListener.Remove called on employee id: " + emp.getId()); +} + + @PostLoad + public void postLoad(Employee emp) { + System.out.println("EmployeeDebugListener.Load called on employee id: " + emp.getId()); +} +} + diff --git a/examples/Chapter9/07-lifecycleCallbacks/src/model/examples/model/NameValidator.java b/examples/Chapter9/07-lifecycleCallbacks/src/model/examples/model/NameValidator.java new file mode 100644 index 0000000..6d938d1 --- /dev/null +++ b/examples/Chapter9/07-lifecycleCallbacks/src/model/examples/model/NameValidator.java @@ -0,0 +1,15 @@ +package examples.model; + +import javax.persistence.PrePersist; + +public class NameValidator { + static final int MAX_NAME_LEN = 40; + + @PrePersist + public void validate(NamedEntity obj) { + System.out.println("NameValidator.validate called on employee name: " + obj.getName()); + if (obj.getName().length() > MAX_NAME_LEN) + throw new ValidationException("Identifier out of range"); + } +} + diff --git a/examples/Chapter9/07-lifecycleCallbacks/src/model/examples/model/NamedEntity.java b/examples/Chapter9/07-lifecycleCallbacks/src/model/examples/model/NamedEntity.java new file mode 100644 index 0000000..4473d59 --- /dev/null +++ b/examples/Chapter9/07-lifecycleCallbacks/src/model/examples/model/NamedEntity.java @@ -0,0 +1,6 @@ +package examples.model; + +public interface NamedEntity { + public String getName(); +} + diff --git a/examples/Chapter9/07-lifecycleCallbacks/src/model/examples/model/ValidationException.java b/examples/Chapter9/07-lifecycleCallbacks/src/model/examples/model/ValidationException.java new file mode 100644 index 0000000..c4a402b --- /dev/null +++ b/examples/Chapter9/07-lifecycleCallbacks/src/model/examples/model/ValidationException.java @@ -0,0 +1,7 @@ +package examples.model; + +public class ValidationException extends RuntimeException { + public ValidationException(String message) { + super(message); + } +} diff --git a/examples/Chapter9/07-lifecycleCallbacks/src/model/examples/stateless/EmployeeService.java b/examples/Chapter9/07-lifecycleCallbacks/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..40d7bba --- /dev/null +++ b/examples/Chapter9/07-lifecycleCallbacks/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 createEmployee(int id, String name); + public void removeEmployee(int id); + public Employee changeEmployeeName(int id, String newName); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter9/07-lifecycleCallbacks/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter9/07-lifecycleCallbacks/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..d9f76c1 --- /dev/null +++ b/examples/Chapter9/07-lifecycleCallbacks/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.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public EntityManager getEntityManager() { + return em; + } + + public Employee createEmployee(int id, String name) { + Employee emp = new Employee(); + emp.setId(id); + emp.setName(name); + getEntityManager().persist(emp); + return emp; + } + + public void removeEmployee(int id) { + Employee emp = findEmployee(id); + if (emp != null) { + getEntityManager().remove(emp); + } + } + + public Employee changeEmployeeName(int id, String newName) { + Employee emp = findEmployee(id); + if (emp != null) { + emp.setName(newName); + } + 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/Chapter9/07-lifecycleCallbacks/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter9/07-lifecycleCallbacks/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..b40e46a --- /dev/null +++ b/examples/Chapter9/07-lifecycleCallbacks/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,93 @@ +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 9: Using Lifecycle Callbacks Example"; + + private final String DESCRIPTION = + "This example demonstates the basics of using entity lifecycle callbacks."; + + @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.createEmployee( + parseInt(request.getParameter("empId")), + request.getParameter("name")); + } else if (action.equals("Update")) { + service.changeEmployeeName( + parseInt(request.getParameter("empId")), + request.getParameter("name")); + } else if (action.equals("Remove")) { + service.removeEmployee( + parseInt(request.getParameter("empId"))); + } + + 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 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 + out.println("

Create/Update/Remove Employees

"); + out.println(""); + out.println(""); + out.println(""); + out.println(" "); + out.println(" "); + out.println(""); + out.println("
Employee Id:(int)
Employee Name:(String)
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter9/07-lifecycleCallbacks/undeploy.bat b/examples/Chapter9/07-lifecycleCallbacks/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter9/07-lifecycleCallbacks/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter9/08-lifecycleCallbackInheritance/build.xml b/examples/Chapter9/08-lifecycleCallbackInheritance/build.xml new file mode 100644 index 0000000..9b40740 --- /dev/null +++ b/examples/Chapter9/08-lifecycleCallbackInheritance/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter9/08-lifecycleCallbackInheritance/deploy.bat b/examples/Chapter9/08-lifecycleCallbackInheritance/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter9/08-lifecycleCallbackInheritance/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter9/08-lifecycleCallbackInheritance/etc/persistence/META-INF/orm.xml b/examples/Chapter9/08-lifecycleCallbackInheritance/etc/persistence/META-INF/orm.xml new file mode 100644 index 0000000..74fdfeb --- /dev/null +++ b/examples/Chapter9/08-lifecycleCallbackInheritance/etc/persistence/META-INF/orm.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/08-lifecycleCallbackInheritance/etc/persistence/META-INF/persistence.xml b/examples/Chapter9/08-lifecycleCallbackInheritance/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..078d9e7 --- /dev/null +++ b/examples/Chapter9/08-lifecycleCallbackInheritance/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/lifecycleCallbackInheritance + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/08-lifecycleCallbackInheritance/etc/sql/db.sql b/examples/Chapter9/08-lifecycleCallbackInheritance/etc/sql/db.sql new file mode 100644 index 0000000..f424b18 --- /dev/null +++ b/examples/Chapter9/08-lifecycleCallbackInheritance/etc/sql/db.sql @@ -0,0 +1,36 @@ +DROP TABLE CONTRACT_EMP; +DROP TABLE PT_EMP; +DROP TABLE FT_EMP; +DROP TABLE EMP; + +CREATE TABLE EMP (ID INTEGER NOT NULL, NAME VARCHAR(255), S_DATE DATE, EMP_TYPE INTEGER, PRIMARY KEY (ID)); +CREATE TABLE FT_EMP (ID INTEGER NOT NULL, VACATION INTEGER, SALARY BIGINT, PENSION BIGINT, PRIMARY KEY (ID), + CONSTRAINT FT_EMP_FK FOREIGN KEY (ID) REFERENCES EMP(ID)); +CREATE TABLE PT_EMP (ID INTEGER NOT NULL, VACATION INTEGER, H_RATE FLOAT, PRIMARY KEY (ID), + CONSTRAINT PT_EMP_FK FOREIGN KEY (ID) REFERENCES EMP(ID)); +CREATE TABLE CONTRACT_EMP (ID INTEGER NOT NULL, D_RATE INTEGER, TERM INTEGER, PRIMARY KEY (ID), + CONSTRAINT CONTRACT_EMP_FK FOREIGN KEY (ID) REFERENCES EMP(ID)); + + +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (1, 'John', {d '2001-01-01'}, 1); +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (2, 'Paul', {d '2002-04-08'}, 1); +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (3, 'Sarah', {d '2003-06-10'}, 1); +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (4, 'Patrick', {d '2004-07-01'}, 2); +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (5, 'Joan', {d '2003-09-09'}, 2); +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (6, 'Samantha', {d '2000-03-12'}, 2); +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (7, 'Mark', {d '2004-11-01'}, 3); +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (8, 'Ryan', {d '2005-12-05'}, 3); +INSERT INTO EMP (ID, NAME, S_DATE, EMP_TYPE) VALUES (9, 'Jackie', {d '2006-01-03'}, 3); + +INSERT INTO CONTRACT_EMP (ID, D_RATE, TERM) VALUES (1, 500, 12); +INSERT INTO CONTRACT_EMP (ID, D_RATE, TERM) VALUES (2, 600, 24); +INSERT INTO CONTRACT_EMP (ID, D_RATE, TERM) VALUES (3, 700, 18); + +INSERT INTO FT_EMP (ID, VACATION, SALARY, PENSION) VALUES (4, 15, 55000, 100000); +INSERT INTO FT_EMP (ID, VACATION, SALARY, PENSION) VALUES (5, 15, 59000, 200000); +INSERT INTO FT_EMP (ID, VACATION, SALARY, PENSION) VALUES (6, 20, 60000, 450000); + +INSERT INTO PT_EMP (ID, VACATION, H_RATE) VALUES (7, 15, 17.0); +INSERT INTO PT_EMP (ID, VACATION, H_RATE) VALUES (8, 15, 16.0); +INSERT INTO PT_EMP (ID, VACATION, H_RATE) VALUES (9, 10, 15.0); + diff --git a/examples/Chapter9/08-lifecycleCallbackInheritance/etc/web/WEB-INF/web.xml b/examples/Chapter9/08-lifecycleCallbackInheritance/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter9/08-lifecycleCallbackInheritance/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/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/CompanyEmployee.java b/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/CompanyEmployee.java new file mode 100644 index 0000000..a038545 --- /dev/null +++ b/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/CompanyEmployee.java @@ -0,0 +1,27 @@ +package examples.model; + +import javax.persistence.EntityListeners; +import javax.persistence.MappedSuperclass; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; + +@MappedSuperclass +@EntityListeners(EmployeeAudit.class) +public abstract class CompanyEmployee extends Employee { + private int vacation; + + public int getVacation() { + return vacation; + } + + public void setVacation(int vacation) { + this.vacation = vacation; + } + + @PrePersist + @PreUpdate + public void verifyVacation() { + System.out.println("CompanyEmployee.verifyVacation called on employee: " + getId()); + //... + } +} diff --git a/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/ContractEmployee.java b/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/ContractEmployee.java new file mode 100644 index 0000000..5027b22 --- /dev/null +++ b/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/ContractEmployee.java @@ -0,0 +1,46 @@ +package examples.model; + +import javax.persistence.Column; +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; +import javax.persistence.EntityListeners; +import javax.persistence.ExcludeSuperclassListeners; +import javax.persistence.PrePersist; +import javax.persistence.Table; + +@Entity +@Table(name="CONTRACT_EMP") +@DiscriminatorValue("1") +@ExcludeSuperclassListeners +@EntityListeners(LongNameValidator.class) +public class ContractEmployee extends Employee { + @Column(name="D_RATE") + private int dailyRate; + private int term; + + @PrePersist + public void verifyTerm() { + System.out.println("ContractEmployee.verifyTerm called on employee: " + getId()); + //... + } + + public int getDailyRate() { + return dailyRate; + } + + public void setDailyRate(int dailyRate) { + this.dailyRate = dailyRate; + } + + public int getTerm() { + return term; + } + + public void setTerm(int term) { + this.term = term; + } + + public String toString() { + return "ContractEmployee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/Employee.java b/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/Employee.java new file mode 100644 index 0000000..650108f --- /dev/null +++ b/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/Employee.java @@ -0,0 +1,69 @@ +package examples.model; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.DiscriminatorColumn; +import javax.persistence.DiscriminatorType; +import javax.persistence.Entity; +import javax.persistence.EntityListeners; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; +import javax.persistence.PostLoad; +import javax.persistence.PostPersist; +import javax.persistence.PostUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; +import javax.persistence.Transient; + +@Entity +@Table(name="EMP") +@Inheritance(strategy=InheritanceType.JOINED) +@DiscriminatorColumn(name="EMP_TYPE", discriminatorType=DiscriminatorType.INTEGER) +@EntityListeners(NameValidator.class) +public abstract class Employee implements NamedEntity { + @Id private int id; + private String name; + @Temporal(TemporalType.DATE) + @Column(name="S_DATE") + private Date startDate; + @Transient private long syncTime; + + @PostPersist + @PostUpdate + @PostLoad + private void resetSyncTime() { + System.out.println("Employee.resetSyncTime called on employee: " + getId()); + syncTime = System.currentTimeMillis(); + } + + 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 getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/EmployeeAudit.java b/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/EmployeeAudit.java new file mode 100644 index 0000000..8bb7b29 --- /dev/null +++ b/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/EmployeeAudit.java @@ -0,0 +1,12 @@ +package examples.model; + +import javax.persistence.PostPersist; + +public class EmployeeAudit { + @PostPersist + public void auditNewHire(CompanyEmployee emp) { + System.out.println("EmployeeAudit.auditNewHire called on employee: " + emp.getId()); + //... + } +} + diff --git a/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/EmployeeDebugListener.java b/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/EmployeeDebugListener.java new file mode 100644 index 0000000..84e1f82 --- /dev/null +++ b/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/EmployeeDebugListener.java @@ -0,0 +1,30 @@ +package examples.model; + +import javax.persistence.PostLoad; +import javax.persistence.PrePersist; +import javax.persistence.PreRemove; +import javax.persistence.PreUpdate; + +public class EmployeeDebugListener { + @PrePersist + public void prePersist(Employee emp) { + System.out.println("EmployeeDebugListener.Persist called on employee id: " + emp.getId()); + } + + @PreUpdate + public void preUpdate(Employee emp) { + System.out.println("EmployeeDebugListener.Update called on employee id: " + emp.getId()); +} + + @PreRemove + public void preRemove(Employee emp) { + System.out.println("EmployeeDebugListener.Remove called on employee id: " + emp.getId()); +} + + @PostLoad + public void postLoad(Employee emp) { + System.out.println("EmployeeDebugListener.Load called on employee id: " + emp.getId()); + Thread.dumpStack(); + } +} + diff --git a/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/EmployeeType.java b/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/EmployeeType.java new file mode 100644 index 0000000..6fab5b2 --- /dev/null +++ b/examples/Chapter9/08-lifecycleCallbackInheritance/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/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/FullTimeEmployee.java b/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/FullTimeEmployee.java new file mode 100644 index 0000000..761ed00 --- /dev/null +++ b/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/FullTimeEmployee.java @@ -0,0 +1,33 @@ +package examples.model; + +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; +import javax.persistence.Table; + +@Entity +@Table(name="FT_EMP") +@DiscriminatorValue("2") +public class FullTimeEmployee extends CompanyEmployee { + private long salary; + private long pension; + + public long getPension() { + return pension; + } + + public void setPension(long pension) { + this.pension = pension; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public String toString() { + return "FullTimeEmployee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/LongNameValidator.java b/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/LongNameValidator.java new file mode 100644 index 0000000..d53ee7f --- /dev/null +++ b/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/LongNameValidator.java @@ -0,0 +1,10 @@ +package examples.model; + +import javax.persistence.PrePersist; + +public class LongNameValidator { + @PrePersist public void validateLongName(NamedEntity obj) { + System.out.println("LongNameValidator.validate called on employee: " + obj.getName()); + //... + } +} diff --git a/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/NameValidator.java b/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/NameValidator.java new file mode 100644 index 0000000..ab0873f --- /dev/null +++ b/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/NameValidator.java @@ -0,0 +1,12 @@ +package examples.model; + +import javax.persistence.PrePersist; + +public class NameValidator { + @PrePersist + public void validate(NamedEntity obj) { + System.out.println("NameValidator.validate called on employee: " + obj.getName()); + //... + } +} + diff --git a/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/NamedEntity.java b/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/NamedEntity.java new file mode 100644 index 0000000..4473d59 --- /dev/null +++ b/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/NamedEntity.java @@ -0,0 +1,6 @@ +package examples.model; + +public interface NamedEntity { + public String getName(); +} + diff --git a/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/PartTimeEmployee.java b/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/PartTimeEmployee.java new file mode 100644 index 0000000..af16128 --- /dev/null +++ b/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/model/PartTimeEmployee.java @@ -0,0 +1,37 @@ +package examples.model; + +import javax.persistence.Column; +import javax.persistence.DiscriminatorValue; +import javax.persistence.Entity; +import javax.persistence.EntityListeners; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; + +@Entity +@EntityListeners({}) +@Table(name="PT_EMP") +@DiscriminatorValue("3") +public class PartTimeEmployee extends CompanyEmployee { + @Column(name="H_RATE") + private float hourlyRate; + + public float getHourlyRate() { + return hourlyRate; + } + + public void setHourlyRate(float hourlyRate) { + this.hourlyRate = hourlyRate; + } + + @PrePersist + @PreUpdate + public void verifyVacation() { + System.out.println("PartTimeEmployee.verifyVacation called on employee: " + getId()); + //... + } + + public String toString() { + return "PartTimeEmployee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/stateless/EmployeeService.java b/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..1f50e17 --- /dev/null +++ b/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,13 @@ +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, EmployeeType type); + public void removeEmployee(int id); + public Employee changeEmployeeName(int id, String newName); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..714db70 --- /dev/null +++ b/examples/Chapter9/08-lifecycleCallbackInheritance/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,63 @@ +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.ContractEmployee; +import examples.model.Employee; +import examples.model.EmployeeType; +import examples.model.FullTimeEmployee; +import examples.model.PartTimeEmployee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + protected EntityManager em; + + public EntityManager getEntityManager() { + return em; + } + + public Employee createEmployee(int id, String name, EmployeeType type) { + Employee emp = null; + if (type == EmployeeType.PART_TIME_EMPLOYEE) { + emp = new PartTimeEmployee(); + } else if (type == EmployeeType.FULL_TIME_EMPLOYEE) { + emp = new FullTimeEmployee(); + } else { + emp = new ContractEmployee(); + } + emp.setId(id); + emp.setName(name); + getEntityManager().persist(emp); + return emp; + } + + public void removeEmployee(int id) { + Employee emp = findEmployee(id); + if (emp != null) { + getEntityManager().remove(emp); + } + } + + public Employee changeEmployeeName(int id, String newName) { + Employee emp = findEmployee(id); + if (emp != null) { + emp.setName(newName); + } + 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/Chapter9/08-lifecycleCallbackInheritance/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter9/08-lifecycleCallbackInheritance/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..a4d992e --- /dev/null +++ b/examples/Chapter9/08-lifecycleCallbackInheritance/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.model.EmployeeType; +import examples.stateless.EmployeeService; + +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 9: Using Lifecycle Callback Inheritance Example"; + + private final String DESCRIPTION = + "This example demonstates the basics of using entity lifecycle " + + "callbacks in a hierarchy."; + + @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.createEmployee( + parseInt(request.getParameter("empId")), + request.getParameter("name"), + getEmployeeType(request.getParameter("type"))); + } else if (action.equals("Update")) { + service.changeEmployeeName( + parseInt(request.getParameter("empId")), + request.getParameter("name")); + } else if (action.equals("Remove")) { + service.removeEmployee( + parseInt(request.getParameter("empId"))); + } + + 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 int parseInt(String intString) { + try { + return Integer.parseInt(intString); + } catch (NumberFormatException e) { + return 0; + } + } + + 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; + } + } + + 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 + out.println("

Create/Update/Remove Employees

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(" "); + out.println(" "); + out.println(""); + out.println("
Employee Id:(int)
Employee Name:(String)
Empoyee Type:"); + out.println(" Full Time
"); + out.println(" Part Time
"); + out.println(" Contract"); + out.println("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter9/08-lifecycleCallbackInheritance/undeploy.bat b/examples/Chapter9/08-lifecycleCallbackInheritance/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter9/08-lifecycleCallbackInheritance/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter9/09-entityRefresh/build.xml b/examples/Chapter9/09-entityRefresh/build.xml new file mode 100644 index 0000000..b238d75 --- /dev/null +++ b/examples/Chapter9/09-entityRefresh/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter9/09-entityRefresh/deploy.bat b/examples/Chapter9/09-entityRefresh/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter9/09-entityRefresh/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter9/09-entityRefresh/etc/persistence/META-INF/persistence.xml b/examples/Chapter9/09-entityRefresh/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..4d7421a --- /dev/null +++ b/examples/Chapter9/09-entityRefresh/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/entityRefresh + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/09-entityRefresh/etc/sql/db.sql b/examples/Chapter9/09-entityRefresh/etc/sql/db.sql new file mode 100644 index 0000000..d3f0b4d --- /dev/null +++ b/examples/Chapter9/09-entityRefresh/etc/sql/db.sql @@ -0,0 +1,6 @@ +DROP TABLE EMPLOYEE; + +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, VACATIONDAYS INTEGER, MANAGER_ID INTEGER, + CONSTRAINT MANAGER_FK FOREIGN KEY (MANAGER_ID) REFERENCES EMPLOYEE (ID), PRIMARY KEY (ID)); + +INSERT INTO EMPLOYEE (ID, NAME, SALARY, VACATIONDAYS) VALUES (4, 'Patrick', 55000, 15); \ No newline at end of file diff --git a/examples/Chapter9/09-entityRefresh/etc/web/WEB-INF/web.xml b/examples/Chapter9/09-entityRefresh/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter9/09-entityRefresh/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/Chapter9/09-entityRefresh/src/model/examples/model/Employee.java b/examples/Chapter9/09-entityRefresh/src/model/examples/model/Employee.java new file mode 100644 index 0000000..ecd396d --- /dev/null +++ b/examples/Chapter9/09-entityRefresh/src/model/examples/model/Employee.java @@ -0,0 +1,83 @@ +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.ManyToOne; +import javax.persistence.OneToMany; + +@Entity +public class Employee { + @Id private int id; + private String name; + private long salary; + private int vacationDays; + + @ManyToOne(cascade={CascadeType.REFRESH}) + private Employee manager; + + @OneToMany(mappedBy="manager") + private Collection directs = 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 int getVacationDays() { + return vacationDays; + } + + public void setVacationDays(int vacation) { + this.vacationDays = vacation; + } + + 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 String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " vacation: " + getVacationDays() + " salary: " + getSalary(); + } +} diff --git a/examples/Chapter9/09-entityRefresh/src/model/examples/stateless/EmployeeService.java b/examples/Chapter9/09-entityRefresh/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..30db297 --- /dev/null +++ b/examples/Chapter9/09-entityRefresh/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,14 @@ +package examples.stateless; + +import java.util.Collection; + +import examples.model.Employee; + +public interface EmployeeService { + public void loadEmployee(int id); + public Employee getEmployee(); + public void deductEmployeeVacation(int days); + public void adjustEmployeeSalary(long salary); + public void finished(); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter9/09-entityRefresh/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter9/09-entityRefresh/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..83ceb5e --- /dev/null +++ b/examples/Chapter9/09-entityRefresh/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,64 @@ +package examples.stateless; + +import java.util.Collection; + +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 javax.persistence.Query; + +import examples.model.Employee; + +@Stateful +@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) +public class EmployeeServiceBean implements EmployeeService { + public static final long REFRESH_THRESHOLD = 3000; // changed threshold to force refresh + + @PersistenceContext(unitName="EmployeeService", + type=PersistenceContextType.EXTENDED) + private EntityManager em; + private Employee emp; + private long loadTime; + + public void loadEmployee (int id) { + emp = em.find(Employee.class, id); + if (emp == null) + throw new IllegalArgumentException("Unknown employee id: " + id); + loadTime = System.currentTimeMillis(); + } + + public Employee getEmployee() { + return emp; + } + + public void deductEmployeeVacation(int days) { + refreshEmployeeIfNeeded(); + emp.setVacationDays(emp.getVacationDays() - days); + } + + public void adjustEmployeeSalary(long salary) { + refreshEmployeeIfNeeded(); + emp.setSalary(salary); + } + + @Remove + @TransactionAttribute(TransactionAttributeType.REQUIRED) + public void finished() {} + + private void refreshEmployeeIfNeeded() { + if ((System.currentTimeMillis() - loadTime) > REFRESH_THRESHOLD) { + em.refresh(emp); + loadTime = System.currentTimeMillis(); + } + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} + diff --git a/examples/Chapter9/09-entityRefresh/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter9/09-entityRefresh/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..3cf8d5c --- /dev/null +++ b/examples/Chapter9/09-entityRefresh/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.EmployeeService; + +@EJB(name="ejb/EmployeeService", + beanInterface=EmployeeService.class, + beanName="EmployeeServiceBean") +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 9: Entity Refresh Example"; + + private final String DESCRIPTION = + "This example shows an incorrect usage of the refresh api."; + + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + printHtmlHeader(out); + + EmployeeService service = (EmployeeService) request.getSession().getAttribute("EmployeeService"); + if (service == null) { + try { + service = (EmployeeService) + new InitialContext().lookup("java:comp/env/ejb/EmployeeService"); + request.getSession().setAttribute("EmployeeService", service); + } catch (Exception e) { + throw new ServletException(e); + } + } + + // process request + String action = request.getParameter("action"); + if (action == null) { + printInitAction(out, service); + } else if (action.equals("ManageEmp")) { + service.loadEmployee(parseInt(request.getParameter("empId"))); + printManagementActions(out, service); + } else if (action.equals("DeductVacation")) { + service.deductEmployeeVacation(parseInt(request.getParameter("vacation"))); + printManagementActions(out, service); + } else if (action.equals("AdjustSalary")) { + service.adjustEmployeeSalary(parseLong(request.getParameter("salary"))); + printManagementActions(out, service); + } else if (action.equals("Finished")) { + service.finished(); + request.getSession().removeAttribute("EmployeeService"); + printInitAction(out, service); + } + + 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("
"); + } + + private void printInitAction(PrintWriter out, EmployeeService service) { + out.println(""); + out.println("

Manage Employee

"); + out.println(""); + out.println("" + + ""); + out.println("
Employee Id:(int)
"); + out.println(""); + out.println("
"); + out.println("Employees:
"); + printCollection(service.findAllEmployees(), out); + } + + private void printManagementActions(PrintWriter out, EmployeeService service) { + out.print("Managing " + service.getEmployee() + "
"); + + out.println("
"); + out.println("

Deduct Employee Vacation

"); + out.println(""); + out.println(""); + out.println(""); + out.println("
Vacation:(int)
"); + out.println("
"); + out.println("

Adjust Employee Salary

"); + out.println(""); + out.println("" + + ""); + out.println("
Salary:(long)
"); + 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/09-entityRefresh/undeploy.bat b/examples/Chapter9/09-entityRefresh/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter9/09-entityRefresh/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter9/10-entityRevert/build.xml b/examples/Chapter9/10-entityRevert/build.xml new file mode 100644 index 0000000..947f57a --- /dev/null +++ b/examples/Chapter9/10-entityRevert/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter9/10-entityRevert/deploy.bat b/examples/Chapter9/10-entityRevert/deploy.bat new file mode 100644 index 0000000..28ac656 --- /dev/null +++ b/examples/Chapter9/10-entityRevert/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant deploy + +pause \ No newline at end of file diff --git a/examples/Chapter9/10-entityRevert/etc/persistence/META-INF/persistence.xml b/examples/Chapter9/10-entityRevert/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..388e30d --- /dev/null +++ b/examples/Chapter9/10-entityRevert/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/entityRevert + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/10-entityRevert/etc/sql/db.sql b/examples/Chapter9/10-entityRevert/etc/sql/db.sql new file mode 100644 index 0000000..b62efcd --- /dev/null +++ b/examples/Chapter9/10-entityRevert/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/Chapter9/10-entityRevert/etc/web/WEB-INF/web.xml b/examples/Chapter9/10-entityRevert/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..c25518c --- /dev/null +++ b/examples/Chapter9/10-entityRevert/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/Chapter9/10-entityRevert/etc/web/editEmployee.jsp b/examples/Chapter9/10-entityRevert/etc/web/editEmployee.jsp new file mode 100644 index 0000000..365be10 --- /dev/null +++ b/examples/Chapter9/10-entityRevert/etc/web/editEmployee.jsp @@ -0,0 +1,23 @@ + +<%@ 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/Chapter9/10-entityRevert/etc/web/listEmployees.jsp b/examples/Chapter9/10-entityRevert/etc/web/listEmployees.jsp new file mode 100644 index 0000000..e6b6a64 --- /dev/null +++ b/examples/Chapter9/10-entityRevert/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/Chapter9/10-entityRevert/src/model/examples/model/Employee.java b/examples/Chapter9/10-entityRevert/src/model/examples/model/Employee.java new file mode 100644 index 0000000..0601a4c --- /dev/null +++ b/examples/Chapter9/10-entityRevert/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/Chapter9/10-entityRevert/src/model/examples/stateful/EmployeeEdit.java b/examples/Chapter9/10-entityRevert/src/model/examples/stateful/EmployeeEdit.java new file mode 100644 index 0000000..4961f2e --- /dev/null +++ b/examples/Chapter9/10-entityRevert/src/model/examples/stateful/EmployeeEdit.java @@ -0,0 +1,11 @@ +package examples.stateful; + +import examples.model.Employee; + +public interface EmployeeEdit { + public void begin(int id); + public Employee getEmployee(); + public Employee revertEmployee(); + public void save(); + public void cancel(); +} diff --git a/examples/Chapter9/10-entityRevert/src/model/examples/stateful/EmployeeEditBean.java b/examples/Chapter9/10-entityRevert/src/model/examples/stateful/EmployeeEditBean.java new file mode 100644 index 0000000..5913026 --- /dev/null +++ b/examples/Chapter9/10-entityRevert/src/model/examples/stateful/EmployeeEditBean.java @@ -0,0 +1,43 @@ +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; + } + + public Employee revertEmployee() { + em.refresh(emp); + return emp; + } + + @Remove + @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) + public void save() {} + + @Remove + public void cancel() {} +} \ No newline at end of file diff --git a/examples/Chapter9/10-entityRevert/src/model/examples/stateless/EmployeeService.java b/examples/Chapter9/10-entityRevert/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..3c54249 --- /dev/null +++ b/examples/Chapter9/10-entityRevert/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/Chapter9/10-entityRevert/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter9/10-entityRevert/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..3c0c0a6 --- /dev/null +++ b/examples/Chapter9/10-entityRevert/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/Chapter9/10-entityRevert/src/servlet/examples/servlet/EmployeeEditServlet.java b/examples/Chapter9/10-entityRevert/src/servlet/examples/servlet/EmployeeEditServlet.java new file mode 100644 index 0000000..307368c --- /dev/null +++ b/examples/Chapter9/10-entityRevert/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/Chapter9/10-entityRevert/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter9/10-entityRevert/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..34a7c43 --- /dev/null +++ b/examples/Chapter9/10-entityRevert/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/Chapter9/10-entityRevert/src/servlet/examples/servlet/EmployeeUpdateServlet.java b/examples/Chapter9/10-entityRevert/src/servlet/examples/servlet/EmployeeUpdateServlet.java new file mode 100644 index 0000000..f782df9 --- /dev/null +++ b/examples/Chapter9/10-entityRevert/src/servlet/examples/servlet/EmployeeUpdateServlet.java @@ -0,0 +1,67 @@ +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") || action.equals("Update")) { + String name = request.getParameter("name"); + long salary = parseLong(request.getParameter("salary")); + Employee emp = bean.getEmployee(); + emp.setName(name); + emp.setSalary(salary); + if (action.equals("Save")) { + bean.save(); + } else { + request.setAttribute("employee", bean.getEmployee()); + getServletContext().getRequestDispatcher("/editEmployee.jsp") + .forward(request, response); + return; + } + } else if (action.equals("Cancel")) { + bean.cancel(); + } else if (action.equals("Revert")) { + bean.revertEmployee(); + request.setAttribute("employee", bean.getEmployee()); + getServletContext().getRequestDispatcher("/editEmployee.jsp") + .forward(request, response); + return; + } + + 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/Chapter9/10-entityRevert/undeploy.bat b/examples/Chapter9/10-entityRevert/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter9/10-entityRevert/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter9/11-readLocking/build.xml b/examples/Chapter9/11-readLocking/build.xml new file mode 100644 index 0000000..3592ebb --- /dev/null +++ b/examples/Chapter9/11-readLocking/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter9/11-readLocking/deploy.bat b/examples/Chapter9/11-readLocking/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter9/11-readLocking/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter9/11-readLocking/etc/persistence/META-INF/persistence.xml b/examples/Chapter9/11-readLocking/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..9543912 --- /dev/null +++ b/examples/Chapter9/11-readLocking/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/readLocking + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/11-readLocking/etc/sql/db.sql b/examples/Chapter9/11-readLocking/etc/sql/db.sql new file mode 100644 index 0000000..83d3652 --- /dev/null +++ b/examples/Chapter9/11-readLocking/etc/sql/db.sql @@ -0,0 +1,17 @@ +DROP TABLE EMP; +DROP TABLE DEPARTMENT; + +CREATE TABLE DEPARTMENT (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID)); +CREATE TABLE EMP (ID INTEGER NOT NULL, NAME VARCHAR(255), SALARY BIGINT, VERSION INTEGER, + 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, 'QA'); +INSERT INTO DEPARTMENT (ID, NAME) VALUES (3, 'Accounting'); + +INSERT INTO EMP (ID, VERSION, NAME, SALARY, DEPARTMENT_ID) VALUES (2, 1, 'Joan', 59000, 1); +INSERT INTO EMP (ID, VERSION, NAME, SALARY, DEPARTMENT_ID) VALUES (1, 1, 'Sarah', 52000, 2); +INSERT INTO EMP (ID, VERSION, NAME, SALARY, DEPARTMENT_ID) VALUES (3, 1, 'John', 55000, 2); +INSERT INTO EMP (ID, VERSION, NAME, SALARY, DEPARTMENT_ID) VALUES (4, 1, 'Rob', 53000, 2); diff --git a/examples/Chapter9/11-readLocking/etc/web/WEB-INF/web.xml b/examples/Chapter9/11-readLocking/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter9/11-readLocking/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/Chapter9/11-readLocking/src/model/examples/model/Department.java b/examples/Chapter9/11-readLocking/src/model/examples/model/Department.java new file mode 100644 index 0000000..76cc9b2 --- /dev/null +++ b/examples/Chapter9/11-readLocking/src/model/examples/model/Department.java @@ -0,0 +1,62 @@ +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 void removeEmployee(Employee employee) { + getEmployees().remove(employee); + } + + public Collection getEmployees() { + return employees; + } + + public String toString() { + return "Department id: " + getId() + + ", name: " + getName(); + } +} diff --git a/examples/Chapter9/11-readLocking/src/model/examples/model/Employee.java b/examples/Chapter9/11-readLocking/src/model/examples/model/Employee.java new file mode 100644 index 0000000..eac7b18 --- /dev/null +++ b/examples/Chapter9/11-readLocking/src/model/examples/model/Employee.java @@ -0,0 +1,65 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import javax.persistence.Table; +import javax.persistence.Version; + +@Entity +@Table(name="EMP") +public class Employee { + @Id + private int id; + @Version private int version; + private String name; + private long salary; + + @ManyToOne + private Department department; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getVersion() { + return version; + } + + public void setVersion(int version) { + this.version = version; + } + + 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/Chapter9/11-readLocking/src/model/examples/model/SalaryReport.java b/examples/Chapter9/11-readLocking/src/model/examples/model/SalaryReport.java new file mode 100644 index 0000000..eeb9a19 --- /dev/null +++ b/examples/Chapter9/11-readLocking/src/model/examples/model/SalaryReport.java @@ -0,0 +1,12 @@ +package examples.model; + +public class SalaryReport { + + public void addDeptSalaryLine(int deptId, long deptTotal) { + + } + + public void addSummarySalaryLine(long total) { + + } +} diff --git a/examples/Chapter9/11-readLocking/src/model/examples/stateless/EmployeeService.java b/examples/Chapter9/11-readLocking/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..617a6a8 --- /dev/null +++ b/examples/Chapter9/11-readLocking/src/model/examples/stateless/EmployeeService.java @@ -0,0 +1,13 @@ +package examples.stateless; + +import java.util.Collection; +import java.util.List; + +import examples.model.Employee; +import examples.model.SalaryReport; + +public interface EmployeeService { + public SalaryReport generateDepartmentsSalaryReport(List deptIds); + public void changeEmployeeDepartment(int deptId, int empId); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter9/11-readLocking/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter9/11-readLocking/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..8b24ac1 --- /dev/null +++ b/examples/Chapter9/11-readLocking/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,56 @@ +package examples.stateless; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.LockModeType; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.Department; +import examples.model.Employee; +import examples.model.SalaryReport; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + private EntityManager em; + + public SalaryReport generateDepartmentsSalaryReport(List deptIds) { + SalaryReport report = new SalaryReport(); + long total = 0; + for (Integer deptId : deptIds) { + long deptTotal = totalSalaryInDepartment(deptId); + report.addDeptSalaryLine(deptId, deptTotal); + total += deptTotal; + } + report.addSummarySalaryLine(total); + return report; + } + + protected long totalSalaryInDepartment(int deptId) { + long total = 0; + Department dept = em.find(Department.class, deptId); + for (Employee emp : dept.getEmployees()) { + em.lock(emp, LockModeType.READ); + total += emp.getSalary(); + } + return total; + } + + public void changeEmployeeDepartment(int deptId, int empId) { + Employee emp = em.find(Employee.class, empId); + emp.getDepartment().removeEmployee(emp); + Department dept = em.find(Department.class, deptId); + dept.addEmployee(emp); + emp.setDepartment(dept); + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} diff --git a/examples/Chapter9/11-readLocking/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter9/11-readLocking/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..c6c6951 --- /dev/null +++ b/examples/Chapter9/11-readLocking/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,74 @@ +package examples.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.ArrayList; +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 { + + private final String TITLE = + "Chapter 9: Read Locking Example"; + + private final String DESCRIPTION = + "This example demonstates the basics of read locking. Look at the " + + "SQL issued in the console to see the locks acquired"; + + + @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("GenerateReport")) { + List deptIds = new ArrayList(); + deptIds.add(1); + deptIds.add(2); + empService.generateDepartmentsSalaryReport(deptIds); + } + + 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 to create and Employee and Department + out.println("

Generate Department Report

"); + 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/Chapter9/11-readLocking/undeploy.bat b/examples/Chapter9/11-readLocking/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter9/11-readLocking/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter9/12-writeLocking/build.xml b/examples/Chapter9/12-writeLocking/build.xml new file mode 100644 index 0000000..e55d1d3 --- /dev/null +++ b/examples/Chapter9/12-writeLocking/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter9/12-writeLocking/deploy.bat b/examples/Chapter9/12-writeLocking/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter9/12-writeLocking/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter9/12-writeLocking/etc/persistence/META-INF/persistence.xml b/examples/Chapter9/12-writeLocking/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..7b3db53 --- /dev/null +++ b/examples/Chapter9/12-writeLocking/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/writeLocking + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/12-writeLocking/etc/sql/db.sql b/examples/Chapter9/12-writeLocking/etc/sql/db.sql new file mode 100644 index 0000000..476109d --- /dev/null +++ b/examples/Chapter9/12-writeLocking/etc/sql/db.sql @@ -0,0 +1,16 @@ +DROP TABLE UNIFORM; +DROP TABLE EMPLOYEE; + +CREATE TABLE EMPLOYEE(ID INTEGER NOT NULL, NAME VARCHAR(255), COST FLOAT, VERSION INTEGER, PRIMARY KEY (ID)); +CREATE TABLE UNIFORM (ID INTEGER NOT NULL, COLOR VARCHAR(255), EMPLOYEE_ID INTEGER, PRIMARY KEY (ID), + CONSTRAINT EMP_FK FOREIGN KEY (EMPLOYEE_ID) REFERENCES EMPLOYEE (ID)); + + +INSERT INTO EMPLOYEE (ID, NAME, COST, VERSION) VALUES (2, 'Joan', 0, 0); +INSERT INTO EMPLOYEE (ID, NAME, COST, VERSION) VALUES (1, 'Sarah', 0, 0); + +INSERT INTO UNIFORM (ID, COLOR, EMPLOYEE_ID) VALUES (1, 'Blue', 1); +INSERT INTO UNIFORM (ID, COLOR) VALUES (2, 'White'); +INSERT INTO UNIFORM (ID, COLOR) VALUES (3, 'Black'); +INSERT INTO UNIFORM (ID, COLOR) VALUES (4, 'Red'); + diff --git a/examples/Chapter9/12-writeLocking/etc/web/WEB-INF/web.xml b/examples/Chapter9/12-writeLocking/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..5257287 --- /dev/null +++ b/examples/Chapter9/12-writeLocking/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/Chapter9/12-writeLocking/src/model/examples/model/Employee.java b/examples/Chapter9/12-writeLocking/src/model/examples/model/Employee.java new file mode 100644 index 0000000..dd0c084 --- /dev/null +++ b/examples/Chapter9/12-writeLocking/src/model/examples/model/Employee.java @@ -0,0 +1,59 @@ +package examples.model; + +import java.util.Collection; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Version; +import javax.persistence.OneToMany; + +@Entity +public class Employee { + @Id + private int id; + @Version private int version; + private String name; + private float cost; + @OneToMany(mappedBy="employee") + private Collection uniforms; + + 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 float getCost() { + return cost; + } + + public void setCost(float salary) { + this.cost = salary; + } + + public Collection getUniforms() { + return uniforms; + } + + public void addUniform(Uniform uniform) { + getUniforms().add(uniform); + } + + public void setUniforms(Collection uniforms) { + this.uniforms = uniforms; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName(); + } +} diff --git a/examples/Chapter9/12-writeLocking/src/model/examples/model/Uniform.java b/examples/Chapter9/12-writeLocking/src/model/examples/model/Uniform.java new file mode 100644 index 0000000..38a46f8 --- /dev/null +++ b/examples/Chapter9/12-writeLocking/src/model/examples/model/Uniform.java @@ -0,0 +1,38 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@Entity +public class Uniform { + @Id + private int id; + private String color; + @ManyToOne + private Employee employee; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + + public Employee getEmployee() { + return employee; + } + + public void setEmployee(Employee employee) { + this.employee = employee; + } +} diff --git a/examples/Chapter9/12-writeLocking/src/model/examples/stateless/EmployeeManagement.java b/examples/Chapter9/12-writeLocking/src/model/examples/stateless/EmployeeManagement.java new file mode 100644 index 0000000..f24fa32 --- /dev/null +++ b/examples/Chapter9/12-writeLocking/src/model/examples/stateless/EmployeeManagement.java @@ -0,0 +1,8 @@ +package examples.stateless; + +import examples.model.Uniform; + +public interface EmployeeManagement { + public Uniform getUniform(int id); + public void addUniform(int id, Uniform uniform); +} diff --git a/examples/Chapter9/12-writeLocking/src/model/examples/stateless/EmployeeManagementBean.java b/examples/Chapter9/12-writeLocking/src/model/examples/stateless/EmployeeManagementBean.java new file mode 100644 index 0000000..10e5da0 --- /dev/null +++ b/examples/Chapter9/12-writeLocking/src/model/examples/stateless/EmployeeManagementBean.java @@ -0,0 +1,28 @@ +package examples.stateless; + +import javax.ejb.Stateful; +import javax.persistence.EntityManager; +import javax.persistence.LockModeType; +import javax.persistence.PersistenceContext; +import javax.persistence.PersistenceContextType; + +import examples.model.Employee; +import examples.model.Uniform; + +@Stateful +public class EmployeeManagementBean implements EmployeeManagement { + @PersistenceContext(unitName="EmployeeService", + type=PersistenceContextType.EXTENDED) + private EntityManager em; + + public Uniform getUniform(int id) { + return em.find(Uniform.class, id); + } + + public void addUniform(int id, Uniform uniform) { + Employee emp = em.find(Employee.class, id); + em.lock(emp, LockModeType.WRITE); // comment out to show overwriting of data + emp.addUniform(uniform); + uniform.setEmployee(emp); + } +} diff --git a/examples/Chapter9/12-writeLocking/src/model/examples/stateless/FeeManagement.java b/examples/Chapter9/12-writeLocking/src/model/examples/stateless/FeeManagement.java new file mode 100644 index 0000000..b56f5b0 --- /dev/null +++ b/examples/Chapter9/12-writeLocking/src/model/examples/stateless/FeeManagement.java @@ -0,0 +1,5 @@ +package examples.stateless; + +public interface FeeManagement { + public void calculateCleaningCost(int id); +} diff --git a/examples/Chapter9/12-writeLocking/src/model/examples/stateless/FeeManagementBean.java b/examples/Chapter9/12-writeLocking/src/model/examples/stateless/FeeManagementBean.java new file mode 100644 index 0000000..bab8121 --- /dev/null +++ b/examples/Chapter9/12-writeLocking/src/model/examples/stateless/FeeManagementBean.java @@ -0,0 +1,25 @@ +package examples.stateless; + +import javax.ejb.Stateful; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.PersistenceContextType; + +import examples.model.Employee; + +@Stateful +public class FeeManagementBean implements FeeManagement { + static final Float UNIFORM_COST = 4.7f; + + @PersistenceContext(unitName="EmployeeService", + type=PersistenceContextType.EXTENDED) + protected EntityManager em; + + public void calculateCleaningCost(int id) { + Employee emp = em.find(Employee.class, id); + Float cost = emp.getUniforms().size() * UNIFORM_COST; + emp.setCost(emp.getCost() + cost); // NOTE: this isn't entirely accurate but it + // it forces an update to demonstrate the lock + } +} + diff --git a/examples/Chapter9/12-writeLocking/src/servlet/examples/servlet/EmployeeServlet.java b/examples/Chapter9/12-writeLocking/src/servlet/examples/servlet/EmployeeServlet.java new file mode 100644 index 0000000..e069f2f --- /dev/null +++ b/examples/Chapter9/12-writeLocking/src/servlet/examples/servlet/EmployeeServlet.java @@ -0,0 +1,75 @@ +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.Uniform; +import examples.stateless.FeeManagement; +import examples.stateless.EmployeeManagement; + +public class EmployeeServlet extends HttpServlet { + + private final String TITLE = + "Chapter 9: Write Locking Example"; + + private final String DESCRIPTION = + "This example demonstates the basics of using a write lock. Turn off " + + "locking and redeploy to see the data being computed incorrectly."; + + + @EJB EmployeeManagement empManagement; + @EJB FeeManagement feeManagement; + + 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("ShowWriteLocks")) { + feeManagement.calculateCleaningCost(1); + empManagement.addUniform(1, empManagement.getUniform(2)); + empManagement.addUniform(1, empManagement.getUniform(3)); + empManagement.addUniform(1, empManagement.getUniform(4)); + feeManagement.calculateCleaningCost(1); + } + + 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("
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter9/12-writeLocking/undeploy.bat b/examples/Chapter9/12-writeLocking/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter9/12-writeLocking/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter9/13-optimisticLocking/build.xml b/examples/Chapter9/13-optimisticLocking/build.xml new file mode 100644 index 0000000..5f1817b --- /dev/null +++ b/examples/Chapter9/13-optimisticLocking/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter9/13-optimisticLocking/deploy.bat b/examples/Chapter9/13-optimisticLocking/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter9/13-optimisticLocking/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter9/13-optimisticLocking/etc/persistence/META-INF/persistence.xml b/examples/Chapter9/13-optimisticLocking/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..f5e3dad --- /dev/null +++ b/examples/Chapter9/13-optimisticLocking/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,10 @@ + + + jdbc/optimisticLocking + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/13-optimisticLocking/etc/sql/db.sql b/examples/Chapter9/13-optimisticLocking/etc/sql/db.sql new file mode 100644 index 0000000..f7242bd --- /dev/null +++ b/examples/Chapter9/13-optimisticLocking/etc/sql/db.sql @@ -0,0 +1,4 @@ +DROP TABLE EMPLOYEE; + +CREATE TABLE EMPLOYEE (ID INTEGER NOT NULL, VERSION INTEGER, NAME VARCHAR(255), SALARY BIGINT, + VACATIONDAYS INTEGER, PRIMARY KEY (ID)); \ No newline at end of file diff --git a/examples/Chapter9/13-optimisticLocking/etc/web/WEB-INF/web.xml b/examples/Chapter9/13-optimisticLocking/etc/web/WEB-INF/web.xml new file mode 100644 index 0000000..fb570ff --- /dev/null +++ b/examples/Chapter9/13-optimisticLocking/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/Chapter9/13-optimisticLocking/src/model/examples/model/ChangeCollisionException.java b/examples/Chapter9/13-optimisticLocking/src/model/examples/model/ChangeCollisionException.java new file mode 100644 index 0000000..a63721b --- /dev/null +++ b/examples/Chapter9/13-optimisticLocking/src/model/examples/model/ChangeCollisionException.java @@ -0,0 +1,9 @@ +package examples.model; + +import javax.ejb.ApplicationException; + +@ApplicationException +public class ChangeCollisionException extends RuntimeException { + public ChangeCollisionException() { super(); } +} + diff --git a/examples/Chapter9/13-optimisticLocking/src/model/examples/model/Employee.java b/examples/Chapter9/13-optimisticLocking/src/model/examples/model/Employee.java new file mode 100644 index 0000000..da0b79a --- /dev/null +++ b/examples/Chapter9/13-optimisticLocking/src/model/examples/model/Employee.java @@ -0,0 +1,59 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Version; + +@Entity +public class Employee { + @Id private int id; + @Version private int version; + private String name; + private long salary; + private int vacationDays; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getVersion() { + return version; + } + + public void setVersion(int version) { + this.version = version; + } + + 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 int getVacationDays() { + return vacationDays; + } + + public void setVacationDays(int vacation) { + this.vacationDays = vacation; + } + + public String toString() { + return "Employee id: " + getId() + " name: " + getName() + + " vacation: " + getVacationDays(); + } +} diff --git a/examples/Chapter9/13-optimisticLocking/src/model/examples/stateless/EmpServiceClient.java b/examples/Chapter9/13-optimisticLocking/src/model/examples/stateless/EmpServiceClient.java new file mode 100644 index 0000000..f6dbae8 --- /dev/null +++ b/examples/Chapter9/13-optimisticLocking/src/model/examples/stateless/EmpServiceClient.java @@ -0,0 +1,6 @@ +package examples.stateless; + +public interface EmpServiceClient { + public void adjustVacation(int id, int days); + public void adjustVacationOptLock(int id, int days); +} diff --git a/examples/Chapter9/13-optimisticLocking/src/model/examples/stateless/EmpServiceClientBean.java b/examples/Chapter9/13-optimisticLocking/src/model/examples/stateless/EmpServiceClientBean.java new file mode 100644 index 0000000..701a46e --- /dev/null +++ b/examples/Chapter9/13-optimisticLocking/src/model/examples/stateless/EmpServiceClientBean.java @@ -0,0 +1,33 @@ +package examples.stateless; + +import javax.ejb.EJB; +import javax.ejb.Stateless; +import javax.ejb.TransactionManagement; +import javax.ejb.TransactionManagementType; + +import examples.model.ChangeCollisionException; + +@Stateless +@TransactionManagement(TransactionManagementType.BEAN) +public class EmpServiceClientBean implements EmpServiceClient { + @EJB protected EmployeeService empSvc; + + public void adjustVacation(int id, int days) { + try { + empSvc.deductEmployeeVacation(id, days); + } catch (ChangeCollisionException ccEx) { + System.out.println("Collision with other change - Retrying..."); + empSvc.deductEmployeeVacation(id, days); + } + } + + public void adjustVacationOptLock(int id, int days) { + try { + empSvc.deductEmployeeVacationOptLock(id, days); + } catch (ChangeCollisionException ccEx) { + System.out.println("Collision with other change - Retrying..."); + empSvc.deductEmployeeVacation(id, days); + } + } + +} \ No newline at end of file diff --git a/examples/Chapter9/13-optimisticLocking/src/model/examples/stateless/EmployeeService.java b/examples/Chapter9/13-optimisticLocking/src/model/examples/stateless/EmployeeService.java new file mode 100644 index 0000000..eda4d44 --- /dev/null +++ b/examples/Chapter9/13-optimisticLocking/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, int vacation); + public void deductEmployeeVacation(int id, int days); + public void deductEmployeeVacationOptLock(int id, int days); + public void adjustEmployeeSalary(int id, long salary); + public Collection findAllEmployees(); +} diff --git a/examples/Chapter9/13-optimisticLocking/src/model/examples/stateless/EmployeeServiceBean.java b/examples/Chapter9/13-optimisticLocking/src/model/examples/stateless/EmployeeServiceBean.java new file mode 100644 index 0000000..63bb8e4 --- /dev/null +++ b/examples/Chapter9/13-optimisticLocking/src/model/examples/stateless/EmployeeServiceBean.java @@ -0,0 +1,63 @@ +package examples.stateless; + +import java.util.Collection; + +import javax.ejb.Stateless; +import javax.persistence.EntityManager; +import javax.persistence.OptimisticLockException; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import examples.model.ChangeCollisionException; +import examples.model.Employee; + +@Stateless +public class EmployeeServiceBean implements EmployeeService { + @PersistenceContext(unitName="EmployeeService") + private EntityManager em; + + public Employee createEmployee(int id, String name, int vacation) { + Employee emp = new Employee(); + emp.setId(id); + emp.setName(name); + emp.setVacationDays(vacation); + em.persist(emp); + return emp; + } + + public void deductEmployeeVacation(int id, int days) { + Employee emp = em.find(Employee.class, id); + emp.setVacationDays(emp.getVacationDays() - days); + // ... + flushChanges(); + } + + public void deductEmployeeVacationOptLock(int id, int days) { + Employee emp = em.find(Employee.class, id); + emp.setVersion(emp.getVersion()-1); // force opt lock + emp.setVacationDays(emp.getVacationDays() - days); + // ... + flushChanges(); + } + + public void adjustEmployeeSalary(int id, long salary) { + Employee emp = em.find(Employee.class, id); + emp.setSalary(salary); + // ... + flushChanges(); + } + + protected void flushChanges() { + try { + em.flush(); + } catch (OptimisticLockException optLockEx) { + throw new ChangeCollisionException(); + } + } + + public Collection findAllEmployees() { + Query query = em.createQuery("SELECT e FROM Employee e"); + return (Collection) query.getResultList(); + } +} + diff --git a/examples/Chapter9/13-optimisticLocking/src/servlet/examples/servlet/EmployeeServiceServlet.java b/examples/Chapter9/13-optimisticLocking/src/servlet/examples/servlet/EmployeeServiceServlet.java new file mode 100644 index 0000000..e90a262 --- /dev/null +++ b/examples/Chapter9/13-optimisticLocking/src/servlet/examples/servlet/EmployeeServiceServlet.java @@ -0,0 +1,98 @@ +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.EmpServiceClient; +import examples.stateless.EmployeeService; + +public class EmployeeServiceServlet extends HttpServlet { + + private final String TITLE = + "Chapter 9: Optimistic Locking Example"; + + private final String DESCRIPTION = + "This example demonstates the basics of optimistic locking."; + + @EJB EmpServiceClient serviceClient; + @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.createEmployee( + parseInt(request.getParameter("empId")), + request.getParameter("name"), + parseInt(request.getParameter("vacation"))); + } else if (action.equals("AdjustVacation")) { + serviceClient.adjustVacation( + parseInt(request.getParameter("empId")), + parseInt(request.getParameter("vacation"))); + } else if (action.equals("AdjustVacationOptLock")) { + serviceClient.adjustVacationOptLock( + parseInt(request.getParameter("empId")), + parseInt(request.getParameter("vacation"))); + } + + 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 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 + out.println("

Create/Update Employees

"); + out.println(""); + out.println(""); + out.println(""); + out.println(""); + out.println(" "); + out.println(""); + out.println(""); + out.println("
Employee Id:(int)
Employee Name:(String)
Employee Vacation:(int)
(see exception in log)
"); + out.println("
"); + } + + + private void printHtmlFooter(PrintWriter out) throws IOException { + out.println(""); + out.println(""); + out.close(); + } +} diff --git a/examples/Chapter9/13-optimisticLocking/undeploy.bat b/examples/Chapter9/13-optimisticLocking/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter9/13-optimisticLocking/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter9/14-schemaUniqueConstraints/build.xml b/examples/Chapter9/14-schemaUniqueConstraints/build.xml new file mode 100644 index 0000000..e9c463b --- /dev/null +++ b/examples/Chapter9/14-schemaUniqueConstraints/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter9/14-schemaUniqueConstraints/deploy.bat b/examples/Chapter9/14-schemaUniqueConstraints/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter9/14-schemaUniqueConstraints/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter9/14-schemaUniqueConstraints/etc/persistence/META-INF/persistence.xml b/examples/Chapter9/14-schemaUniqueConstraints/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..771efe8 --- /dev/null +++ b/examples/Chapter9/14-schemaUniqueConstraints/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,11 @@ + + + jdbc/schemaUniqueConstraints + + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/14-schemaUniqueConstraints/src/model/examples/model/Employee.java b/examples/Chapter9/14-schemaUniqueConstraints/src/model/examples/model/Employee.java new file mode 100644 index 0000000..84fa02e --- /dev/null +++ b/examples/Chapter9/14-schemaUniqueConstraints/src/model/examples/model/Employee.java @@ -0,0 +1,42 @@ +package examples.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Employee { + @Id private int id; + // NOTE: also marked nullable because of a Derby requirement + @Column(unique=true, nullable=false) + 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(); + } +} diff --git a/examples/Chapter9/14-schemaUniqueConstraints/undeploy.bat b/examples/Chapter9/14-schemaUniqueConstraints/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter9/14-schemaUniqueConstraints/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter9/15-schemaUniqueConstraints2/build.xml b/examples/Chapter9/15-schemaUniqueConstraints2/build.xml new file mode 100644 index 0000000..461dffa --- /dev/null +++ b/examples/Chapter9/15-schemaUniqueConstraints2/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter9/15-schemaUniqueConstraints2/deploy.bat b/examples/Chapter9/15-schemaUniqueConstraints2/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter9/15-schemaUniqueConstraints2/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter9/15-schemaUniqueConstraints2/etc/persistence/META-INF/persistence.xml b/examples/Chapter9/15-schemaUniqueConstraints2/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..f747330 --- /dev/null +++ b/examples/Chapter9/15-schemaUniqueConstraints2/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,11 @@ + + + jdbc/schemaUniqueConstraints2 + + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/15-schemaUniqueConstraints2/src/model/examples/model/Employee.java b/examples/Chapter9/15-schemaUniqueConstraints2/src/model/examples/model/Employee.java new file mode 100644 index 0000000..1c39e9a --- /dev/null +++ b/examples/Chapter9/15-schemaUniqueConstraints2/src/model/examples/model/Employee.java @@ -0,0 +1,43 @@ +package examples.model; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.UniqueConstraint; + +@Entity +@Table(name="EMP", + uniqueConstraints=@UniqueConstraint(columnNames="NAME")) +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(); + } +} diff --git a/examples/Chapter9/15-schemaUniqueConstraints2/undeploy.bat b/examples/Chapter9/15-schemaUniqueConstraints2/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter9/15-schemaUniqueConstraints2/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter9/16-schemaNullConstraints/build.xml b/examples/Chapter9/16-schemaNullConstraints/build.xml new file mode 100644 index 0000000..91edabf --- /dev/null +++ b/examples/Chapter9/16-schemaNullConstraints/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter9/16-schemaNullConstraints/deploy.bat b/examples/Chapter9/16-schemaNullConstraints/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter9/16-schemaNullConstraints/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter9/16-schemaNullConstraints/etc/persistence/META-INF/persistence.xml b/examples/Chapter9/16-schemaNullConstraints/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..fb6c3fa --- /dev/null +++ b/examples/Chapter9/16-schemaNullConstraints/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,11 @@ + + + jdbc/schemaNullConstraints + + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/16-schemaNullConstraints/src/model/examples/model/Address.java b/examples/Chapter9/16-schemaNullConstraints/src/model/examples/model/Address.java new file mode 100644 index 0000000..e18406b --- /dev/null +++ b/examples/Chapter9/16-schemaNullConstraints/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/Chapter9/16-schemaNullConstraints/src/model/examples/model/Employee.java b/examples/Chapter9/16-schemaNullConstraints/src/model/examples/model/Employee.java new file mode 100644 index 0000000..5426209 --- /dev/null +++ b/examples/Chapter9/16-schemaNullConstraints/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; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; + +@Entity +public class Employee { + @Id private int id; + @Column(nullable=false) + private String name; + private long salary; + @ManyToOne + @JoinColumn(nullable=false) + 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(); + } +} diff --git a/examples/Chapter9/16-schemaNullConstraints/undeploy.bat b/examples/Chapter9/16-schemaNullConstraints/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter9/16-schemaNullConstraints/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter9/17-schemaStringBasedColumns/build.xml b/examples/Chapter9/17-schemaStringBasedColumns/build.xml new file mode 100644 index 0000000..5dccbc1 --- /dev/null +++ b/examples/Chapter9/17-schemaStringBasedColumns/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter9/17-schemaStringBasedColumns/deploy.bat b/examples/Chapter9/17-schemaStringBasedColumns/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter9/17-schemaStringBasedColumns/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter9/17-schemaStringBasedColumns/etc/persistence/META-INF/persistence.xml b/examples/Chapter9/17-schemaStringBasedColumns/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..1d20149 --- /dev/null +++ b/examples/Chapter9/17-schemaStringBasedColumns/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,11 @@ + + + jdbc/schemaStringBasedColumns + + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/17-schemaStringBasedColumns/src/model/examples/model/Employee.java b/examples/Chapter9/17-schemaStringBasedColumns/src/model/examples/model/Employee.java new file mode 100644 index 0000000..2a3ce50 --- /dev/null +++ b/examples/Chapter9/17-schemaStringBasedColumns/src/model/examples/model/Employee.java @@ -0,0 +1,33 @@ +package examples.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; + +@Entity +public class Employee { + @Id + @Column(length=40) + private String name; + @ManyToOne + @JoinColumn(name="MGR") + private Employee manager; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Employee getManager() { + return manager; + } + + public void setManager(Employee manager) { + this.manager = manager; + } +} diff --git a/examples/Chapter9/17-schemaStringBasedColumns/undeploy.bat b/examples/Chapter9/17-schemaStringBasedColumns/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter9/17-schemaStringBasedColumns/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter9/18-schemaFloatingPointColumn/build.xml b/examples/Chapter9/18-schemaFloatingPointColumn/build.xml new file mode 100644 index 0000000..7fb3d5f --- /dev/null +++ b/examples/Chapter9/18-schemaFloatingPointColumn/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter9/18-schemaFloatingPointColumn/deploy.bat b/examples/Chapter9/18-schemaFloatingPointColumn/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter9/18-schemaFloatingPointColumn/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter9/18-schemaFloatingPointColumn/etc/persistence/META-INF/persistence.xml b/examples/Chapter9/18-schemaFloatingPointColumn/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..85614ec --- /dev/null +++ b/examples/Chapter9/18-schemaFloatingPointColumn/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,11 @@ + + + jdbc/schemaFloatingPointColumn + + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/18-schemaFloatingPointColumn/src/model/examples/model/PartTimeEmployee.java b/examples/Chapter9/18-schemaFloatingPointColumn/src/model/examples/model/PartTimeEmployee.java new file mode 100644 index 0000000..2ec50e3 --- /dev/null +++ b/examples/Chapter9/18-schemaFloatingPointColumn/src/model/examples/model/PartTimeEmployee.java @@ -0,0 +1,37 @@ +package examples.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class PartTimeEmployee { + @Id private int id; + private String name; + @Column(precision=8, scale=2) + private float hourlyRate; + + 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 float getHourlyRate() { + return hourlyRate; + } + + public void setHourlyRate(float salary) { + this.hourlyRate = salary; + } +} diff --git a/examples/Chapter9/18-schemaFloatingPointColumn/undeploy.bat b/examples/Chapter9/18-schemaFloatingPointColumn/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter9/18-schemaFloatingPointColumn/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/Chapter9/19-schemaColumnDefinition/build.xml b/examples/Chapter9/19-schemaColumnDefinition/build.xml new file mode 100644 index 0000000..fd0d446 --- /dev/null +++ b/examples/Chapter9/19-schemaColumnDefinition/build.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/Chapter9/19-schemaColumnDefinition/deploy.bat b/examples/Chapter9/19-schemaColumnDefinition/deploy.bat new file mode 100644 index 0000000..b9b6293 --- /dev/null +++ b/examples/Chapter9/19-schemaColumnDefinition/deploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant + +pause \ No newline at end of file diff --git a/examples/Chapter9/19-schemaColumnDefinition/etc/persistence/META-INF/persistence.xml b/examples/Chapter9/19-schemaColumnDefinition/etc/persistence/META-INF/persistence.xml new file mode 100644 index 0000000..94fb7be --- /dev/null +++ b/examples/Chapter9/19-schemaColumnDefinition/etc/persistence/META-INF/persistence.xml @@ -0,0 +1,11 @@ + + + jdbc/schemaColumnDefinition + + + + + + + \ No newline at end of file diff --git a/examples/Chapter9/19-schemaColumnDefinition/src/model/examples/model/Employee.java b/examples/Chapter9/19-schemaColumnDefinition/src/model/examples/model/Employee.java new file mode 100644 index 0000000..23353d0 --- /dev/null +++ b/examples/Chapter9/19-schemaColumnDefinition/src/model/examples/model/Employee.java @@ -0,0 +1,36 @@ +package examples.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; + +@Entity +public class Employee { + @Id + @Column(columnDefinition="VARCHAR(40)") + private String name; + @Column(name="START_DATE", columnDefinition="DATE DEFAULT CURRENT_DATE") + private java.sql.Date startDate; + @ManyToOne + @JoinColumn(name="MGR", columnDefinition="VARCHAR(40)") + private Employee manager; + + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Employee getManager() { + return manager; + } + + public void setManager(Employee manager) { + this.manager = manager; + } +} diff --git a/examples/Chapter9/19-schemaColumnDefinition/undeploy.bat b/examples/Chapter9/19-schemaColumnDefinition/undeploy.bat new file mode 100644 index 0000000..00674ea --- /dev/null +++ b/examples/Chapter9/19-schemaColumnDefinition/undeploy.bat @@ -0,0 +1,5 @@ +call ../../../config/setenv.bat + +call ../../../glassfish/lib/ant/bin/ant undeploy + +pause \ No newline at end of file diff --git a/examples/examples.html b/examples/examples.html new file mode 100644 index 0000000..b974900 --- /dev/null +++ b/examples/examples.html @@ -0,0 +1,213 @@ + + Pro EJB 3: Java Persistence API Examples + +

Pro EJB 3: Java Persistence API Examples

+

Java SE Examples

+The SE examples (Chapter 2) do not require a running server. Simply go to the chapter's +example folder and run the batch file for the example. +
+

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 (startserver.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/commons-logging.jar b/lib/commons-logging.jar new file mode 100644 index 0000000..b73a80f Binary files /dev/null and b/lib/commons-logging.jar differ diff --git a/lib/junit-4.0.jar b/lib/junit-4.0.jar new file mode 100644 index 0000000..b204069 Binary files /dev/null and b/lib/junit-4.0.jar differ diff --git a/lib/readme.txt b/lib/readme.txt new file mode 100644 index 0000000..e2e63e1 --- /dev/null +++ b/lib/readme.txt @@ -0,0 +1 @@ +These libraries are needed by the examples for Chapter 13: Testing. They are automatically copied to the necessary location by the install script or referenced in the classpath in config/common.properties. \ No newline at end of file diff --git a/lib/spring.jar b/lib/spring.jar new file mode 100644 index 0000000..635c360 Binary files /dev/null and b/lib/spring.jar differ