Hibernate-sortedmap-mapping

提供:Dev Guides
移動先:案内検索

Hibernate-SortedMapマッピング

*SortedMap* は、キーと値のペアで要素を保存し、キーの全体的な順序を提供する *Map* と同様のJavaコレクションです。 マップ内で要素を複製することはできません。 マップは、そのキーの自然な順序に従って、またはソートされたマップの作成時に通常提供されるコンパレータによって順序付けられます。

SortedMapは、マッピングテーブルの<map>要素でマップされ、順序付けられたマップはjava.util.TreeMapで初期化できます。

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_type VARCHAR(40) default NULL,
   certificate_name VARCHAR(30) default NULL,
   employee_id INT default NULL,
   PRIMARY KEY (id)
);

EMPLOYEEオブジェクトとCERTIFICATEオブジェクトの間には* 1対多*の関係があります。

POJOクラスを定義する

EMPLOYEEテーブルに関連するオブジェクトを永続化し、証明書のコレクションを List 変数に保持するために使用されるPOJOクラス Employee を実装しましょう。

import java.util.*;

public class Employee {
   private int id;
   private String firstName;
   private String lastName;
   private int salary;
   private SortedMap 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 SortedMap getCertificates() {
      return certificates;
   }

   public void setCertificates( SortedMap certificates ) {
      this.certificates = certificates;
   }
}

証明書オブジェクトを保存してCERTIFICATEテーブルに取得できるように、CERTIFICATEテーブルに対応する別のPOJOクラスを定義する必要があります。 このクラスは、マッピングファイルでsort = "natural"を設定した場合に、ソート済みマップのキー要素をソートするために使用されるComparableインターフェイスとcompareToメソッドも実装する必要があります(マッピングファイルを参照)。

public class Certificate implements Comparable <String>{
   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(String that){
      final int BEFORE = -1;
      final int AFTER = 1;

      if (that == null) {
         return BEFORE;
      }

      Comparable thisCertificate = this;
      Comparable thatCertificate = that;

      if(thisCertificate == null) {
         return AFTER;
      } else if(thatCertificate == null) {
         return BEFORE;
      } else {
         return thisCertificate.compareTo(thatCertificate);
      }
   }
}

Hibernateマッピングファイルの定義

定義済みのクラスをデータベーステーブルにマップする方法をHibernateに指示するマッピングファイルを開発しましょう。 <map>要素は、使用されるマップのルールを定義するために使用されます。

<?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>

      <map name = "certificates" cascade="all" sort="MyClass">
         <key column = "employee_id"/>
         <index column = "certificate_type" type = "string"/>
         <one-to-many class="Certificate"/>
      </map>

      <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に保存しました。 あなたはすでにマッピングの詳細の大部分に精通していますが、もう一度マッピングファイルのすべての要素を見てみましょう-

  • マッピングドキュメントは、各クラスに対応する2つの<class>要素を含むルート要素として <hibernate-mapping> を持つXMLドキュメントです。

  • <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データタイプに変換します。

  • <map> 要素は、CertificateクラスとEmployeeクラス間の関係を設定するために使用されます。 <map>要素で cascade 属性を使用して、HibernateにEmployeeオブジェクトと同時にCertificateオブジェクトを永続化するように指示しました。 name 属性は、親クラスで定義された SortedMap 変数に設定されます。この例では、_certificates_です。 sort 属性を natural に設定して自然な並べ替えを行うか、 java.util.Comparator を実装するカスタムクラスに設定できます。 java.util.Comparatorを実装するクラス MyClass を使用して、 Certificate クラスで実装されたソート順を逆にしました。

  • <index> 要素は、キー/値マップペアのキー部分を表すために使用されます。 キーは、ストリングのタイプを使用して、certificate_type列に格納されます。

  • <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はSortedMapキーを比較するためにCertificateクラスで定義されたcompareTo()メソッドを使用するため、別のクラスを作成する必要はありません ただし、マッピングファイルでカスタムコンパレータクラス *MyClass* を使用しているため、並べ替えアルゴリズムに基づいてこのクラスを作成する必要があります。 マップで使用可能なキーを降順で並べ替えます。
import java.util.Comparator;

public class MyClass implements Comparator <String>{
   public int compare(String o1, String 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;
      Comparable thatCertificate = o2;

      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 */
      TreeMap set1 = new TreeMap();
      set1.put("ComputerScience", new Certificate("MCA"));
      set1.put("BusinessManagement", new Certificate("MBA"));
      set1.put("ProjectManagement", 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 */
      TreeMap set2 = new TreeMap();
      set2.put("ComputerScience", new Certificate("MCA"));
      set2.put("BusinessManagement", new Certificate("MBA"));

     /*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, TreeMap 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());
            SortedMap<String, Certificate> map = employee.getCertificates();
            for(Map.Entry<String,Certificate> entry : map.entrySet()){
               System.out.print("\tCertificate Type: " +  entry.getKey());
               System.out.println(",  Name: " + (entry.getValue()).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 Type: ProjectManagement,  Name: PMP
    Certificate Type: ComputerScience,  Name: MCA
    Certificate Type: BusinessManagement,  Name: MBA
First Name: Dilip  Last Name: Kumar  Salary: 3000
    Certificate Type: ComputerScience,  Name: MCA
    Certificate Type: BusinessManagement,  Name: MBA
First Name: Manoj  Last Name: Kumar  Salary: 5000
    Certificate Type: ProjectManagement,  Name: PMP
    Certificate Type: ComputerScience,  Name: MCA
    Certificate Type: BusinessManagement,  Name: MBA

EMPLOYEEおよびCERTIFICATEテーブルを確認する場合、次のレコードが必要です-

mysql> select *from EMPLOYEE;
+----+------------+-----------+--------+
| id | first_name | last_name | salary |
+----+------------+-----------+--------+
| 74 | Manoj      | Kumar     |   5000 |
+----+------------+-----------+--------+
1 row in set (0.00 sec)

mysql> select* from CERTIFICATE;
+----+--------------------+------------------+-------------+
| id | certificate_type   | certificate_name | employee_id |
+----+--------------------+------------------+-------------+
| 52 | BusinessManagement | MBA              |          74 |
| 53 | ComputerScience    | MCA              |          74 |
| 54 | ProjectManagement  | PMP              |          74 |
+----+--------------------+------------------+-------------+
3 rows in set (0.00 sec)

mysql>