Set
集合Set是一个java集合不包含任何重复的元素。更正式地说,Set不包含任何元素对e1和e2,使得e1.equals(e2),和至多一个空元素。所以被添加到一组对象必须实现equals()和hashCode()方法,使Java可以判断任何两个元素/对象是否是相同的。
集被映射到与映射表中
定义RDBMS表:
考虑一个情况下,我们需要我们的员工记录存储在EMPLOYEE表,有以下结构:
create table EMPLOYEE ( id INT NOT NULL auto_increment, first_name VARCHAr(20) default NULL, last_name VARCHAr(20) default NULL, salary INT default NULL, PRIMARY KEY (id) );
此外,假设每个员工都可以有一个或多个与他/她相关的证书。因此,我们将存储证书的相关信息在一个单独的表,该表具有以下结构:
create table CERTIFICATE ( id INT NOT NULL auto_increment, certificate_name VARCHAr(30) default NULL, employee_id INT default NULL, PRIMARY KEY (id) );
将有一个对多EMPLOYEE和证书对象之间的关系:
定义POJO类:
让我们实现我们的POJO类员工将被用于保存与EMPLOYEE表中的对象和有凭证的设置变量的集合。
import java.util.*;
public class Employee {
private int id;
private String firstName;
private String lastName;
private int salary;
private Set certificates;
public Employee() {}
public Employee(String fname, String lname, int salary) {
this.firstName = fname;
this.lastName = lname;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName( String first_name ) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary( int salary ) {
this.salary = salary;
}
public Set getCertificates() {
return certificates;
}
public void setCertificates( Set certificates ) {
this.certificates = certificates;
}
}
现在让我们定义另一个POJO类对应的表的证书,这样的证书对象可以存储和检索到的CERTIFICATE表。这个类还应该同时实现了equals()和hashCode()方法,使Java可以判断任意两个元素/对象是否相同。
public class Certificate {
private int id;
private String name;
public Certificate() {}
public Certificate(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getName() {
return name;
}
public void setName( String name ) {
this.name = name;
}
public boolean equals(Object obj) {
if (obj == null) return false;
if (!this.getClass().equals(obj.getClass())) return false;
Certificate obj2 = (Certificate)obj;
if((this.id == obj2.getId()) && (this.name.equals(obj2.getName())))
{
return true;
}
return false;
}
public int hashCode() {
int tmp = 0;
tmp = ( id + name ).hashCode();
return tmp;
}
}
定义Hibernate映射文件:
让我们开发指定Hibernate如何定义的类映射到数据库表的映射文件。
This class contains the employee detail. This class contains the certificate records.
应该保存的映射文件中的格式
映射文档是具有
在
元素是可选元素,可以用来创建类的描述。
id元素内的
创建应用程序类:
最后,我们将创建应用程序类的main()方法来运行应用程序。我们将使用这个应用程序,以节省一些员工的记录地连同凭证,然后我们将申请CRUD操作上的记录。
import java.util.*;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ManageEmployee {
private static SessionFactory factory;
public static void main(String[] args) {
try{
factory = new Configuration().configure().buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
ManageEmployee ME = new ManageEmployee();
HashSet set1 = new HashSet();
set1.add(new Certificate("MCA"));
set1.add(new Certificate("MBA"));
set1.add(new Certificate("PMP"));
Integer empID1 = ME.addEmployee("Manoj", "Kumar", 4000, set1);
HashSet set2 = new HashSet();
set2.add(new Certificate("BCA"));
set2.add(new Certificate("BA"));
Integer empID2 = ME.addEmployee("Dilip", "Kumar", 3000, set2);
ME.listEmployees();
ME.updateEmployee(empID1, 5000);
ME.deleteEmployee(empID2);
ME.listEmployees();
}
public Integer addEmployee(String fname, String lname,
int salary, Set cert){
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try{
tx = session.beginTransaction();
Employee employee = new Employee(fname, lname, salary);
employee.setCertificates(cert);
employeeID = (Integer) session.save(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return employeeID;
}
public void listEmployees( ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
List employees = session.createQuery("FROM Employee").list();
for (Iterator iterator1 =
employees.iterator(); iterator1.hasNext();){
Employee employee = (Employee) iterator1.next();
System.out.print("First Name: " + employee.getFirstName());
System.out.print(" Last Name: " + employee.getLastName());
System.out.println(" Salary: " + employee.getSalary());
Set certificates = employee.getCertificates();
for (Iterator iterator2 =
certificates.iterator(); iterator2.hasNext();){
Certificate certName = (Certificate) iterator2.next();
System.out.println("Certificate: " + certName.getName());
}
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
public void updateEmployee(Integer EmployeeID, int salary ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
employee.setSalary( salary );
session.update(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
public void deleteEmployee(Integer EmployeeID){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
session.delete(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
}
编译和执行:
下面是步骤来编译并运行上述应用程序。请确保已在进行的编译和执行之前,适当地设置PATH和CLASSPATH。
- 创建hibernate.cfg.xml配置文件中配置章节解释。
- 创建Employee.hbm.xml映射文件,如上图所示。
- 创建Employee.java源文件,如上图所示,并编译它。
- 创建Certificate.java源文件,如上图所示,并编译它。
- 创建ManageEmployee.java源文件,如上图所示,并编译它。
- 执行ManageEmployee二进制文件来运行程序。
会在屏幕上获得以下结果,并同时记录会在员工和证书表被创建。
$java ManageEmployee
.......VARIOUS LOG MESSAGES WILL DISPLAY HERE........ First Name: Manoj Last Name: Kumar Salary: 4000 Certificate: MBA Certificate: PMP Certificate: MCA First Name: Dilip Last Name: Kumar Salary: 3000 Certificate: BCA Certificate: BA First Name: Manoj Last Name: Kumar Salary: 5000 Certificate: MBA Certificate: PMP Certificate: MCA
如果检查员工和证书表,就应该记录下了:
mysql> select * from employee;
+----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 1 | Manoj | Kumar | 5000 | +----+------------+-----------+--------+ 1 row in set (0.00 sec)
mysql> select * from certificate;
+----+------------------+-------------+ | id | certificate_name | employee_id | +----+------------------+-------------+ | 1 | MBA | 1 | | 2 | PMP | 1 | | 3 | MCA | 1 | +----+------------------+-------------+ 3 rows in set (0.00 sec)
mysql>
SortedSet
SortedSet是java集合,该集合不包含任何重复的元素和元素使用提供他们的自然顺序,或由一个比较器进行排序。
一个SortedSet映射,在映射表
我们依然使用上面示例中所定义的RDBMS表,将有一个对多EMPLOYEE和证书对象之间的关系,POJO类也是如上定义。
让我们实现POJO类员工将被用于保存EMPLOYEE表中的对象和有证书的SortedSet变量的集合。
现在让我们定义另一个POJO类对应的表的证书,这样的证书对象可以存储和检索到的证书表。这个类还应该实现Comparable接口和compareTo方法将被用来设置sort="natural" 在映射文件(见下面的映射文件)的情况下,元素进行排序。
public class Certificate implements Comparable{ private int id; private String name; public Certificate() {} public Certificate(String name) { this.name = name; } public int getId() { return id; } public void setId( int id ) { this.id = id; } public String getName() { return name; } public void setName( String name ) { this.name = name; } public int compareTo(Certificate that){ final int BEFORE = -1; final int AFTER = 1; if (that == null) { return BEFORE; } Comparable thisCertificate = this.getName(); Comparable thatCertificate = that.getName(); if(thisCertificate == null) { return AFTER; } else if(thatCertificate == null) { return BEFORE; } else { return thisCertificate.compareTo(thatCertificate); } } }
定义Hibernate映射文件:
让我们开发指定Hibernate如何定义的类映射到数据库表的映射文件。该
This class contains the employee detail. This class contains the certificate records.
映射文件中的格式
映射文档是具有
元素是可选元素,可以用来创建类的描述。
id元素内的
该
如果使用sort="natural"的设置,并不需要创建一个单独的类,因为证书类已经实现了Comparable接口和hibernate会使用compareTo(在证书类定义为比较证书名称)方法。但是,我们使用的是在我们的映射文件自定义的比较器类MyClass,所以必须创建这个类的基础上实现排序算法。降序时使用这个类在这个类排序。
import java.util.Comparator; public class MyClass implements Comparator{ public int compare(Certificate o1, Certificate o2) { final int BEFORE = -1; final int AFTER = 1; if (o2 == null) { return BEFORE * -1; } Comparable thisCertificate = o1.getName(); Comparable thatCertificate = o2.getName(); if(thisCertificate == null) { return AFTER * 1; } else if(thatCertificate == null) { return BEFORE * -1; } else { return thisCertificate.compareTo(thatCertificate) * -1; } } }
创建应用程序类:
最后,我们将创建应用程序类的main()方法来运行应用程序。我们将使用这个应用程序,以节省一些员工的记录地连同证书,然后我们将申请CRUD操作上的记录。
import java.util.*;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class ManageEmployee {
private static SessionFactory factory;
public static void main(String[] args) {
try{
factory = new Configuration().configure().buildSessionFactory();
}catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
ManageEmployee ME = new ManageEmployee();
TreeSet set1 = new TreeSet();
set1.add(new Certificate("MCA"));
set1.add(new Certificate("MBA"));
set1.add(new Certificate("PMP"));
Integer empID1 = ME.addEmployee("Manoj", "Kumar", 4000, set1);
TreeSet set2 = new TreeSet();
set2.add(new Certificate("BCA"));
set2.add(new Certificate("BA"));
Integer empID2 = ME.addEmployee("Dilip", "Kumar", 3000, set2);
ME.listEmployees();
ME.updateEmployee(empID1, 5000);
ME.deleteEmployee(empID2);
ME.listEmployees();
}
public Integer addEmployee(String fname, String lname,
int salary, SortedSet cert){
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try{
tx = session.beginTransaction();
Employee employee = new Employee(fname, lname, salary);
employee.setCertificates(cert);
employeeID = (Integer) session.save(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return employeeID;
}
public void listEmployees( ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
List employees = session.createQuery("FROM Employee").list();
for (Iterator iterator1 =
employees.iterator(); iterator1.hasNext();){
Employee employee = (Employee) iterator1.next();
System.out.print("First Name: " + employee.getFirstName());
System.out.print(" Last Name: " + employee.getLastName());
System.out.println(" Salary: " + employee.getSalary());
SortedSet certificates = employee.getCertificates();
for (Iterator iterator2 =
certificates.iterator(); iterator2.hasNext();){
Certificate certName = (Certificate) iterator2.next();
System.out.println("Certificate: " + certName.getName());
}
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
public void updateEmployee(Integer EmployeeID, int salary ){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
employee.setSalary( salary );
session.update(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
public void deleteEmployee(Integer EmployeeID){
Session session = factory.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
Employee employee =
(Employee)session.get(Employee.class, EmployeeID);
session.delete(employee);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
}
}
编译和执行后,会在屏幕上获得以下结果,并同时记录会在员工和证书表被创建。可以看到证书已排序顺序相反。可以通过改变映射文件试试,只需设置sort="natural"和执行程序,并比较结果。
$java ManageEmployee
.......VARIOUS LOG MESSAGES WILL DISPLAY HERE........ First Name: Manoj Last Name: Kumar Salary: 4000 Certificate: PMP Certificate: MCA Certificate: MBA First Name: Dilip Last Name: Kumar Salary: 3000 Certificate: BCA Certificate: BA First Name: Manoj Last Name: Kumar Salary: 5000 Certificate: PMP Certificate: MCA Certificate: MBA
如果检查员工和证书表,就应该记录下了:
mysql> select * from employee;
+----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 1 | Manoj | Kumar | 5000 | +----+------------+-----------+--------+ 1 row in set (0.00 sec)
mysql> select * from certificate;
+----+------------------+-------------+ | id | certificate_name | employee_id | +----+------------------+-------------+ | 1 | MBA | 1 | | 2 | PMP | 1 | | 3 | MCA | 1 | +----+------------------+-------------+ 3 rows in set (0.00 sec)



