Java/JPA/EJB Query Language
Содержание
- 1 Aggregate function: AVG
- 2 Aggregate function: Count And Avg
- 3 All Operator in EJB QL
- 4 Any With Subquery
- 5 AVG With GroupBy clause
- 6 Between...And
- 7 Conditional operator: AND
- 8 Count Collection
- 9 Count Entities
- 10 Create Sub Query With Entities
- 11 Distinct function
- 12 EJB QL: Concat Function With Substring
- 13 EJB QL: Having clause
- 14 EJB QL: Where Clause With SubQuery
- 15 Empty Value
- 16 Entity Join With Condition
- 17 Escape wildcard
- 18 Get String Properties From Entities
- 19 Get Two Properties From Entity
- 20 Group By With Count
- 21 Join Fetch
- 22 Join Three Entities
- 23 Join Two Entities in Many To One Mapping
- 24 Join Two Entities in One To One Mapping
- 25 Left Join
- 26 Match Single Character And Multiple Characters
- 27 MemberOf function
- 28 Not Empty
- 29 Not Exist With Subquery
- 30 Not IN
- 31 OBJECT Funtion
- 32 Order By Descending
- 33 Order By Two Columns
- 34 Reference Two Entities In Where Clause
- 35 Retrieve Entity Fields
- 36 Retrieve Inner Entity
- 37 Retrieve in One to Many Mapping
- 38 Select Two Entities
- 39 Simple Select statement
- 40 Subquery in EJB QL
- 41 Use In With One To One Mapping
- 42 Use OrderBy Clause
- 43 Use Size Function To Check Collection
- 44 Using Exists clause
- 45 Using In function
Aggregate function: AVG
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: Address.java
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();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT AVG(e.salary) FROM Professor e");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Aggregate function: Count And Avg
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT d.name, COUNT(e), AVG(e.salary) FROM Department d JOIN d.employees e GROUP BY d.name");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
All Operator in EJB QL
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT e FROM Professor e WHERE e.salary < ALL (SELECT d.salary FROM e.directs d)");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Any With Subquery
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT e FROM Professor e WHERE e.department = ANY (SELECT DISTINCT d FROM Department d)");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
AVG With GroupBy clause
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT d.name, AVG(e.salary) FROM Department d JOIN d.employees e GROUP BY d.name");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Between...And
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT e FROM Professor e WHERE e.salary BETWEEN 40 AND 50");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Conditional operator: AND
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT e FROM Professor e WHERE e.salary >= 40 AND e.salary <= 50");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Count Collection
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT d FROM Department d WHERE (SELECT COUNT(e) FROM d.employees e) = 2");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: Address.java
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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Count Entities
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT COUNT(e), AVG(e.salary) FROM Professor e");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Create Sub Query With Entities
File: Professor.java
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="findHighestPaidByDepartment",
query="SELECT e " +
"FROM Professor e " +
"WHERE e.department = :dept AND " +
" e.salary = (SELECT MAX(e2.salary) " +
" FROM Professor e2 " +
" WHERE e2.department = :dept)")
public class Professor {
@Id
private int id;
private String name;
private long salary;
@Temporal(TemporalType.DATE)
private Date startDate;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs;
@ManyToOne
private Department department;
@ManyToMany
private Collection<Project> projects;
public Professor() {
projects = new ArrayList<Project>();
directs = new ArrayList<Professor>();
}
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<Professor> getDirects() {
return directs;
}
public Professor getManager() {
return manager;
}
public Collection<Project> getProjects() {
return projects;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", dept: " + ((getDepartment() == null) ? null : getDepartment().getName());
}
}
File: Department.java
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<Professor> employees;
public Department() {
employees = new ArrayList<Professor>();
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public Collection<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: ProfessorService.java
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public Professor findHighestPaidByDepartment(Department dept) {
try {
return (Professor) em.createNamedQuery("findHighestPaidByDepartment")
.setParameter("dept", dept)
.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
}
File: Project.java
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<Professor> employees;
public Project() {
employees = new ArrayList<Professor>();
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public Collection<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Project id: " + getId() + ", name: " + getName();
}
}
File: Main.java
import java.util.Collection;
import java.util.Date;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
util.checkData("select * from Professor");
util.checkData("select * from Department");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Distinct function
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT DISTINCT e.department FROM Professor e");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
EJB QL: Concat Function With Substring
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executeUpdate("UPDATE Phone p SET p.number = CONCAT("0",SUBSTRING(p.number,LOCATE(p.number, "-"), 4)), p.type = "Business" ");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
EJB QL: Having clause
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("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) > 50"
);
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
EJB QL: Where Clause With SubQuery
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: Address.java
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();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT m FROM Professor m WHERE (SELECT COUNT(e) FROM Professor e WHERE e.manager = m) > 0");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Empty Value
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT p FROM Project p WHERE p.employees IS NOT EMPTY");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: Address.java
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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Entity Join With Condition
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT DISTINCT e.department FROM Project p JOIN p.employees e WHERE p.name = "proj"");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Escape wildcard
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT d FROM Department d WHERE d.name LIKE "Q\\_%" ESCAPE "\\"");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Get String Properties From Entities
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT e.name FROM Professor e");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: Address.java
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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Get Two Properties From Entity
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT e.name, e.salary FROM Professor e");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Group By With Count
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT d.name, COUNT(e) FROM Department d JOIN d.employees e GROUP BY d.name");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Join Fetch
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT e FROM Professor e JOIN FETCH e.address");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Join Three Entities
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT DISTINCT p FROM Department d JOIN d.employees e JOIN e.projects p");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Join Two Entities in Many To One Mapping
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT d FROM Professor e JOIN e.department d");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Join Two Entities in One To One Mapping
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT p FROM Professor e JOIN e.phones p");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Left Join
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT e, d FROM Professor e LEFT JOIN e.department d");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Match Single Character And Multiple Characters
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT d FROM Department d WHERE d.name LIKE "__Eng%"");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
MemberOf function
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT e FROM Professor e WHERE e MEMBER OF e.directs");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: Address.java
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();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Not Empty
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT e FROM Professor e WHERE e.directs IS NOT EMPTY");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Not Exist With Subquery
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT e FROM Professor e WHERE NOT EXISTS (SELECT p FROM e.phones p)");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Not IN
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT e FROM Professor e WHERE e.address.state NOT IN ("NY", "CA")");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
OBJECT Funtion
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT OBJECT(d) FROM Department d");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: Address.java
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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Order By Descending
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT e FROM Professor e ORDER BY e.name DESC");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Order By Two Columns
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT e FROM Professor e JOIN e.department d ORDER BY d.name, e.name DESC");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Reference Two Entities In Where Clause
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT d FROM Department d, Professor e WHERE d = e.department");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Retrieve Entity Fields
File: Address.java
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();
}
}
File: Professor.java
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.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="ProfessorWithAddressColumnAlias",
entities={@EntityResult(entityClass=Professor.class,
fields=@FieldResult(name="id", column="EMP_ID")),
@EntityResult(entityClass=Address.class)}
)
})
public class Professor {
@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 Professor manager;
@OneToMany(mappedBy = "manager")
private Collection<Professor> directs = new ArrayList<Professor>();
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<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public String toString() {
return "Professor id: " + getId() + " name: " + getName() + " with MgrId: "
+ (getManager() == null ? null : getManager().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List findWithAlias() {
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", "ProfessorWithAddressColumnAlias");
return query.getResultList();
}
}
File: Department.java
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();
}
}
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.findWithAlias();
util.checkData("select * from EMP");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Retrieve Inner Entity
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT e.department FROM Professor e");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Retrieve in One to Many Mapping
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT d.employees FROM Department d");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Select Two Entities
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT d, m FROM Department d, Professor m WHERE d = m.department");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Simple Select statement
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT e FROM Professor e");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Subquery in EJB QL
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT e FROM Professor e WHERE e.salary = (SELECT MAX(e2.salary) FROM Professor e2)");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: Address.java
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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Use In With One To One Mapping
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT DISTINCT p FROM Professor e, IN(e.phones) p");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Use OrderBy Clause
File: Department.java
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<Professor> employees;
public Department() {
employees = new ArrayList<Professor>();
}
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 addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().add(employee);
if (employee.getDepartment() != null) {
employee.getDepartment().getProfessors().remove(employee);
}
employee.setDepartment(this);
}
}
public Collection<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department id: " + getId() + ", name: " + getName();
}
}
File: Professor.java
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity
public class Professor {
@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 "Professor id: " + getId() + " name: " + getName() +
" with " + getDepartment();
}
}
File: ProfessorService.java
import java.util.Collection;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public Department createDepartment(String name) {
Department dept = new Department();
dept.setName(name);
em.persist(dept);
return dept;
}
public Collection<Department> findAllDepartments() {
Query query = em.createQuery("SELECT d FROM Department d");
return (Collection<Department>) query.getResultList();
}
public Professor createProfessor(String name, long salary) {
Professor emp = new Professor();
emp.setName(name);
emp.setSalary(salary);
em.persist(emp);
return emp;
}
public Professor setProfessorDepartment(int empId, int deptId) {
Professor emp = em.find(Professor.class, empId);
Department dept = em.find(Department.class, deptId);
dept.addProfessor(emp);
return emp;
}
public Collection<Professor> findAllProfessors() {
Query query = em.createQuery("SELECT e FROM Professor e");
return (Collection<Professor>) query.getResultList();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Main.java
import java.util.Collection;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
Professor emp = service.createProfessor("empName", 100L);
Department dept = service.createDepartment("deptName");
emp = service.setProfessorDepartment(emp.getId(),dept.getId());
System.out.println(emp.getDepartment() + " with Professors:");
System.out.println(emp.getDepartment().getProfessors());
Collection<Professor> emps = service.findAllProfessors();
if (emps.isEmpty()) {
System.out.println("No Professors found ");
} else {
System.out.println("Found Professors:");
for (Professor emp1 : emps) {
System.out.println(emp1);
}
}
Collection<Department> depts = service.findAllDepartments();
if (depts.isEmpty()) {
System.out.println("No Departments found ");
} else {
System.out.println("Found Departments:");
for (Department dept1 : depts) {
System.out.println(dept1 + " with " + dept1.getProfessors().size() + " employees "
+ dept1.getProfessors());
}
}
util.checkData("select * from Professor");
util.checkData("select * from Department");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Use Size Function To Check Collection
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT d FROM Department d WHERE SIZE(d.employees) = 2");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Using Exists clause
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT e FROM Professor e WHERE EXISTS (SELECT p FROM Phone p WHERE p.employee = e)");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>
Using In function
File: Main.java
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);
em.getTransaction().begin();
service.executetQuery("SELECT e FROM Professor e WHERE e.address.state IN ("NY", "CA")");
util.checkData("select * from Professor");
em.getTransaction().rumit();
em.close();
emf.close();
}
}
File: Address.java
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();
}
}
File: Department.java
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<Professor> employees = new HashSet<Professor>();
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<Professor> getProfessors() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
File: JPAUtil.java
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class JPAUtil {
Statement st;
public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";
Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 0; i < metadata.getColumnCount(); i++) {
System.out.print("\t"+ metadata.getColumnLabel(i + 1));
}
System.out.println("\n----------------------------------");
while (rs.next()) {
for (int i = 0; i < metadata.getColumnCount(); i++) {
Object value = rs.getObject(i + 1);
if (value == null) {
System.out.print("\t ");
} else {
System.out.print("\t"+value.toString().trim());
}
}
System.out.println("");
}
}
}
File: Phone.java
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 Professor 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 Professor getProfessor() {
return employee;
}
public void setProfessor(Professor employee) {
this.employee = employee;
}
public String toString() {
return "Phone id: " + getId() +
", no: " + getNumber() +
", type: " + getType();
}
}
File: Professor.java
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 Professor {
@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<Phone> phones = new ArrayList<Phone>();
@ManyToOne
private Department department;
@ManyToOne
private Professor manager;
@OneToMany(mappedBy="manager")
private Collection<Professor> directs = new ArrayList<Professor>();
@ManyToMany(mappedBy="employees")
private Collection<Project> projects = new ArrayList<Project>();
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<Phone> getPhones() {
return phones;
}
public void addPhone(Phone phone) {
if (!getPhones().contains(phone)) {
getPhones().add(phone);
if (phone.getProfessor() != null) {
phone.getProfessor().getPhones().remove(phone);
}
phone.setProfessor(this);
}
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
if (this.department != null) {
this.department.getProfessors().remove(this);
}
this.department = department;
this.department.getProfessors().add(this);
}
public Collection<Professor> getDirects() {
return directs;
}
public void addDirect(Professor employee) {
if (!getDirects().contains(employee)) {
getDirects().add(employee);
if (employee.getManager() != null) {
employee.getManager().getDirects().remove(employee);
}
employee.setManager(this);
}
}
public Professor getManager() {
return manager;
}
public void setManager(Professor manager) {
this.manager = manager;
}
public Collection<Project> getProjects() {
return projects;
}
public void addProject(Project project) {
if (!getProjects().contains(project)) {
getProjects().add(project);
}
if (!project.getProfessors().contains(this)) {
project.getProfessors().add(this);
}
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String toString() {
return "Professor " + getId() +
": name: " + getName() +
", salary: " + getSalary() +
", phones: " + getPhones() +
", managerNo: " + ((getManager() == null) ? null : getManager().getId()) +
", deptNo: " + ((getDepartment() == null) ? null : getDepartment().getId());
}
}
File: ProfessorService.java
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class ProfessorService {
protected EntityManager em;
public ProfessorService(EntityManager em) {
this.em = em;
}
public List executetQuery(String queryString) {
Query query = em.createQuery(queryString);
return query.getResultList();
}
public void executeUpdate(String updateString) {
em.createQuery(updateString).executeUpdate();
}
}
File: Project.java
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<Professor> employees = new ArrayList<Professor>();
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<Professor> getProfessors() {
return employees;
}
public void addProfessor(Professor employee) {
if (!getProfessors().contains(employee)) {
getProfessors().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();
}
}
File: persistence.xml
<persistence xmlns="http://java.sun.ru/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
<persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
</properties>
</persistence-unit>
</persistence>