Java/JPA/Many to One Mapping
Содержание
One To Many And Many To One Mapping
<source lang="java">
File: Department.java
import java.util.HashMap; import java.util.Map; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.MapKey; import javax.persistence.OneToMany; @Entity public class Department {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; private String name; @OneToMany(mappedBy="department") @MapKey(name="name") private Map<String, Professor> employees; public Department() { employees = new HashMap<String, 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().containsKey(employee.getName())) { getProfessors().put(employee.getName(), employee); if (employee.getDepartment() != null) { employee.getDepartment().getProfessors().remove(employee.getName()); } employee.setDepartment(this); } } public Map<String,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); emp.setDepartment(dept); return emp; } public Collection<Professor> findAllProfessors() { Query query = em.createQuery("SELECT e FROM Professor e"); return (Collection<Professor>) query.getResultList(); }
}
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: 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>
</source>
Persisting With Relationships Using GetReference
<source lang="java">
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 void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Collection<Professor> getProfessors() { return employees; } public String toString() { return "Department no: " + getId() + ", name: " + getName(); }
}
File: Professor.java
import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToOne; @Entity public class Professor {
@Id private int id; private String name; @ManyToOne private Department department; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Department getDepartment() { return department; } public void setDepartment(Department dept) { this.department = dept; } public String toString() { return "Professor " + getId() + ": name: " + getName() + ", dept: " + ((getDepartment() == null) ? null : getDepartment().getName()); }
}
File: ProfessorService.java import java.util.Collection; import javax.persistence.EntityManager; public class ProfessorService {
protected EntityManager em; public ProfessorService(EntityManager em) { this.em = em; } public Professor createProfessor(int empId, String empName, int deptId) { Department dept = em.getReference(Department.class, deptId); Professor emp = new Professor(); emp.setId(empId); emp.setName(empName); emp.setDepartment(dept); dept.getProfessors().add(emp); em.persist(emp); return emp; } public Collection<Professor> findAllProfessors() { return (Collection<Professor>) em.createQuery("SELECT e FROM Professor e").getResultList(); } public Collection<Department> findAllDepartments() { return (Collection<Department>) em.createQuery("SELECT d FROM Department d").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 java.util.Iterator; 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.createProfessor(1, "empName", 1); 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>
</source>
Use One Joined Column
<source lang="java">
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: Professor.java
import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Entity public class Professor {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; private String name; private long salary; @ManyToOne @JoinColumn(name="DEPT_ID") private Department department; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getSalary() { return salary; } public void setSalary(long salary) { this.salary = salary; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } public String toString() { return "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 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); emp.setDepartment(dept); return emp; } public Collection<Professor> findAllProfessors() { Query query = em.createQuery("SELECT e FROM Professor e"); return (Collection<Professor>) query.getResultList(); } 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(); }
}
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", 100); Department dept = service.createDepartment("deptName"); service.setProfessorDepartment(emp.getId(), dept.getId()); Collection<Professor> emps = service.findAllProfessors(); for (Professor emp1 : emps) { System.out.println(emp1); } Collection<Department> depts = service.findAllDepartments(); for (Department dept1 : depts) { System.out.println(dept1); } 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>
</source>
Use Two Joined Columns for Many to one Mapping
<source lang="java">
File: Professor.java
import java.util.ArrayList; import java.util.Collection; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.JoinColumn; import javax.persistence.JoinColumns; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; @Entity @IdClass(ProfessorId.class) public class Professor {
@Id private String country; @Id @Column(name="EMP_ID") private int id; private String name; private long salary; @ManyToOne @JoinColumns({ @JoinColumn(name="MGR_COUNTRY", referencedColumnName="COUNTRY"), @JoinColumn(name="MGR_ID", referencedColumnName="EMP_ID") }) private Professor manager; @OneToMany(mappedBy="manager") private Collection<Professor> directs; @ManyToMany @JoinTable( name="EMP_PROJECT", joinColumns={ @JoinColumn(name="EMP_COUNTRY", referencedColumnName="COUNTRY"), @JoinColumn(name="EMP_ID", referencedColumnName="EMP_ID")}, inverseJoinColumns=@JoinColumn(name="PROJECT_ID")) private Collection<Project> projects; public Professor() { directs = new ArrayList<Professor>(); projects = new ArrayList<Project>(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getSalary() { return salary; } public void setSalary(long salary) { this.salary = salary; } public Collection<Professor> getDirects() { return directs; } public Professor getManager() { return manager; } public void setManager(Professor manager) { this.manager = manager; } public Collection<Project> getProjects() { return projects; } public String toString() { return "Professor id: " + getId() + " name: " + getName() + " country: " + getCountry(); }
}
File: ProfessorId.java import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Embeddable; @Embeddable public class ProfessorId implements Serializable{
private String country; @Column(name = "EMP_ID") private int id; public ProfessorId() { } public ProfessorId(String country, int id) { this.country = country; this.id = id; } public String getCountry() { return country; } public int getId() { return id; } public boolean equals(Object o) { return ((o instanceof ProfessorId) && country.equals(((ProfessorId) o).getCountry()) && id == ((ProfessorId) o) .getId()); } public int hashCode() { return country.hashCode() + id; }
}
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 Professor createProfessor(String country, int id, String name, long salary) { Professor emp = new Professor(); emp.setCountry(country); emp.setId(id); emp.setName(name); emp.setSalary(salary); em.persist(emp); return emp; } public void createProject(String projName) { Project proj = new Project(); proj.setName(projName); em.persist(proj); } public void setProfessorManager(String country, int id, String mgrCountry, int mgrId) { Professor emp = findProfessor(country, id); Professor mgr = findProfessor(mgrCountry, mgrId); emp.setManager(mgr); mgr.getDirects().add(emp); } public void addProfessorProject(String country, int id, int projId) { Professor emp = findProfessor(country, id); Project proj = em.find(Project.class, projId); emp.getProjects().add(proj); proj.getProfessors().add(emp); } public Professor findProfessor(String country, int id) { return em.find(Professor.class, new ProfessorId(country, id)); } public Collection<Professor> findAllProfessors() { Query query = em.createQuery("SELECT e FROM Professor e"); return (Collection<Professor>) query.getResultList(); } public Collection<Project> findAllProjects() { Query query = em.createQuery("SELECT p FROM Project p"); return (Collection<Project>) query.getResultList(); }
}
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") 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.createProfessor("country", 1, "name", 100); service.createProfessor("mgrcountry", 2, "mgrName", 100); service.createProject("proj"); service.addProfessorProject("empCountry2", 1, 1); service.setProfessorManager("Country", 1, "mgrCountry", 1);
System.out.println("Professors:"); for (Professor emp : service.findAllProfessors()) { System.out.println(emp + " " + emp.getProjects().size()); System.out.println(emp + " " + emp.getManager()); } System.out.println("Projects:"); for (Project p : service.findAllProjects()) { System.out.print(p + " " + p.getProfessors().size()); } 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>
</source>