Hibernate-sortedset-mapping
Hibernate-SortedSetマッピング
*SortedSet* は、重複する要素を含まないJavaコレクションであり、要素は自然な順序付けを使用して、または提供されるコンパレータによって順序付けられます。
SortedSetは、マッピングテーブルの<set>要素でマップされ、java.util.TreeSetで初期化されます。 sort 属性は、コンパレーターまたは自然順序付けのいずれかに設定できます。 *自然*順序付けを使用する場合、その反復子は要素の昇順でセットを走査します。
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)
);
さらに、各従業員が自分に関連付けられた1つ以上の証明書を持つことができると仮定します。 だから、私たちは証明書に関連する情報を次の構造を持つ別のテーブルに保存します-
create table CERTIFICATE (
id INT NOT NULL auto_increment,
certificate_name VARCHAR(30) default NULL,
employee_id INT default NULL,
PRIMARY KEY (id)
);
EMPLOYEEとCERTIFICATEオブジェクトの間には* 1対多*の関係があります-
POJOクラスを定義する
EMPLOYEEテーブルに関連し、 SortedSet 変数に証明書のコレクションを持つオブジェクトを永続化するために使用されるPOJOクラス Employee を実装しましょう。
import java.util.*;
public class Employee {
private int id;
private String firstName;
private String lastName;
private int salary;
private SortedSet 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 SortedSet getCertificates() {
return certificates;
}
public void setCertificates( SortedSet certificates ) {
this.certificates = certificates;
}
}
次に、CERTIFICATEテーブルに対応する別のPOJOクラスを定義して、証明書オブジェクトを保存してCERTIFICATEテーブルに取得できるようにします。 このクラスは、 Comparable インターフェイスと compareTo メソッドも実装する必要があります。これは、マッピングファイルで sort = "natural" を設定した場合に要素をソートするために使用されます(マッピングファイルを参照)-
public class Certificate implements Comparable <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 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に指示するマッピングファイルを作成しましょう。 <set>要素は、使用されるSortedSetコレクションのルールを定義するために使用されます。
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name = "Employee" table = "EMPLOYEE">
<meta attribute = "class-description">
This class contains the employee detail.
</meta>
<id name = "id" type = "int" column = "id">
<generator class="native"/>
</id>
<set name = "certificates" cascade="all" sort="MyClass">
<key column = "employee_id"/>
<one-to-many class="Certificate"/>
</set>
<property name = "firstName" column = "first_name" type = "string"/>
<property name = "lastName" column = "last_name" type = "string"/>
<property name = "salary" column = "salary" type = "int"/>
</class>
<class name = "Certificate" table = "CERTIFICATE">
<meta attribute = "class-description">
This class contains the certificate records.
</meta>
<id name = "id" type = "int" column = "id">
<generator class="native"/>
</id>
<property name = "name" column = "certificate_name" type = "string"/>
</class>
</hibernate-mapping>
マッピングドキュメントは、<classname> .hbm.xml形式のファイルに保存する必要があります。 マッピング文書をファイルEmployee.hbm.xmlに保存しました。 あなたはすでにマッピングの詳細のほとんどに精通していますが、マッピングファイルのすべての要素をもう一度見てみましょう-
マッピングドキュメントは、ルート要素として <hibernate-mapping> を持つXMLドキュメントであり、各クラスに対応する2つの<class>要素が含まれます。
<class> 要素は、Javaクラスからデータベーステーブルへの特定のマッピングを定義するために使用されます。 Javaクラス名はクラス要素の name 属性を使用して指定され、データベーステーブル名は table 属性を使用して指定されます。
<meta> 要素はオプションの要素であり、クラスの説明を作成するために使用できます。
<id> 要素は、クラスの一意のID属性をデータベーステーブルの主キーにマップします。 id要素の name 属性はクラスのプロパティを参照し、 column 属性はデータベーステーブルの列を参照します。 type 属性はhibernateマッピングタイプを保持します。このマッピングタイプはJavaからSQLデータタイプに変換します。
id要素内の <generator> 要素は、主キー値を自動的に生成するために使用されます。 ジェネレーター要素の class 属性は native に設定され、休止状態が基になるデータベースの機能に応じて主キーを作成するために identity、sequence または hilo アルゴリズムを選択できるようにします。
<property> 要素は、Javaクラスプロパティをデータベーステーブルの列にマップするために使用されます。 要素の name 属性はクラスのプロパティを参照し、 column 属性はデータベーステーブルの列を参照します。 type 属性はhibernateマッピングタイプを保持します。このマッピングタイプはJavaからSQLデータタイプに変換します。
<set> 要素は、CertificateクラスとEmployeeクラス間の関係を設定するために使用されます。 <set>要素で cascade 属性を使用して、HibernateにEmployeeオブジェクトと同時にCertificateオブジェクトを永続化するように指示しました。 name 属性は、親クラスで定義された SortedSet 変数に設定されます。この例では、_certificates_です。 sort 属性を natural に設定して自然な並べ替えを行うか、 java.util.Comparator を実装するカスタムクラスに設定できます。 java.util.Comparatorを実装するクラス MyClass を使用して、 Certificate クラスで実装されたソート順を逆にしました。
<key> 要素は、親オブジェクトへの外部キーを保持するCERTIFICATEテーブルの列です。 テーブルEMPLOYEE。
<one-to-many> 要素は、1つのEmployeeオブジェクトが多くのCertificateオブジェクトに関連しているため、CertificateオブジェクトにはEmployee親が関連付けられている必要があることを示します。 要件に応じて、 <one-to-one> 、 <many-to-one> 、または <many-to-many> 要素を使用できます。
*sort = "natural"* 設定を使用する場合、Certificateクラスは既にComparableインターフェイスを実装しており、hibernateはCertificateクラスで定義されたcompareTo()メソッドを使用して証明書名を比較するため、別のクラスを作成する必要はありません ただし、マッピングファイルでカスタムコンパレータクラス *MyClass* を使用しているため、並べ替えアルゴリズムに基づいてこのクラスを作成する必要があります。 このクラスを使用して、このクラスで降順ソートを行いましょう。
import java.util.Comparator;
public class MyClass implements Comparator<Certificate>{
public int compare(Certificate o1, Certificate o2) {
final int BEFORE = -1;
final int AFTER = 1;
/*To reverse the sorting order, multiple by -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();
/*Let us have a set of certificates for the first employee */
TreeSet set1 = new TreeSet();
set1.add(new Certificate("MCA"));
set1.add(new Certificate("MBA"));
set1.add(new Certificate("PMP"));
/*Add employee records in the database*/
Integer empID1 = ME.addEmployee("Manoj", "Kumar", 4000, set1);
/*Another set of certificates for the second employee */
TreeSet set2 = new TreeSet();
set2.add(new Certificate("BCA"));
set2.add(new Certificate("BA"));
/*Add another employee record in the database*/
Integer empID2 = ME.addEmployee("Dilip", "Kumar", 3000, set2);
/*List down all the employees*/
ME.listEmployees();
/*Update employee's salary records*/
ME.updateEmployee(empID1, 5000);
/*Delete an employee from the database*/
ME.deleteEmployee(empID2);
/*List down all the employees*/
ME.listEmployees();
}
/*Method to add an employee record in the database*/
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;
}
/*Method to list all the employees detail*/
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();
}
}
/*Method to update salary for an employee*/
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();
}
}
/*Method to delete an employee from the records*/
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ソースファイルを作成し、コンパイルします。
- 上記のようにMyClass.javaソースファイルを作成し、コンパイルします。
- 上記のようにManageEmployee.javaソースファイルを作成し、コンパイルします。
- ManageEmployeeバイナリを実行してプログラムを実行します。
画面に次の結果が表示され、EMPLOYEEおよびCERTIFICATEテーブルに同じ時間レコードが作成されます。 証明書が逆順にソートされていることがわかります。 マッピングファイルを変更して、 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
あなたはあなたの従業員とCERTIFICATEテーブルをチェックする場合、それらは次のレコードを持つ必要があります-
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>