Hibernate-map-mapping
Hibernate-マップマッピング
*Map* は、キーと値のペアで要素を保存するJavaコレクションであり、リスト内の要素の重複を許可しません。 Mapインターフェイスには3つのコレクションビューがあり、マップのコンテンツをキーのセット、値のコレクション、またはキーと値のマッピングのセットとして表示できます。
Mapはマッピングテーブルの<map>要素でマップされ、順序付けられていないマップはjava.util.HashMapで初期化できます。
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 Map 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 Map getCertificates() {
return certificates;
}
public void setCertificates( Map certificates ) {
this.certificates = certificates;
}
}
証明書オブジェクトを保存してCERTIFICATEテーブルに取得できるように、CERTIFICATEテーブルに対応する別のPOJOクラスを定義する必要があります。
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;
}
}
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">
<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 属性は、親クラスで定義された Map 変数に設定されます。この例では、_certificates_です。
- <index> 要素は、キー/値マップペアのキー部分を表すために使用されます。 キーは、ストリングのタイプを使用して、certificate_type列に格納されます。
- <key> 要素は、親オブジェクトへの外部キーを保持するCERTIFICATEテーブルの列です。 テーブルEMPLOYEE。
- <one-to-many> 要素は、1つのEmployeeオブジェクトが多くのCertificateオブジェクトに関連しているため、CertificateオブジェクトにはEmployee親が関連付けられている必要があることを示します。 要件に応じて、 <one-to-one> 、 <many-to-one> 、または <many-to-many> 要素を使用できます。
アプリケーションクラスを作成する
最後に、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 */
HashMap set = new HashMap();
set.put("ComputerScience", new Certificate("MCA"));
set.put("BusinessManagement", new Certificate("MBA"));
set.put("ProjectManagement", new Certificate("PMP"));
/*Add employee records in the database*/
Integer empID = ME.addEmployee("Manoj", "Kumar", 4000, set);
/*List down all the employees*/
ME.listEmployees();
/*Update employee's salary records*/
ME.updateEmployee(empID, 5000);
/*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, HashMap 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());
Map ec = employee.getCertificates();
System.out.println("Certificate: " +
(((Certificate)ec.get("ComputerScience")).getName()));
System.out.println("Certificate: " +
(((Certificate)ec.get("BusinessManagement")).getName()));
System.out.println("Certificate: " +
(((Certificate)ec.get("ProjectManagement")).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ソースファイルを作成し、コンパイルします。
- 上記のようにManageEmployee.javaソースファイルを作成し、コンパイルします。 *ManageEmployeeバイナリを実行してプログラムを実行します。
画面に次の結果が表示され、EMPLOYEEおよびCERTIFICATEテーブルに同じ時間レコードが作成されます。
$java ManageEmployee
.......VARIOUS LOG MESSAGES WILL DISPLAY HERE........
First Name: Manoj Last Name: Kumar Salary: 4000
Certificate: MCA
Certificate: MBA
Certificate: PMP
First Name: Manoj Last Name: Kumar Salary: 5000
Certificate: MCA
Certificate: MBA
Certificate: PMP
EMPLOYEEおよびCERTIFICATEテーブルを確認する場合、次のレコードが必要です-
mysql> select* from EMPLOYEE;
+----+------------+-----------+--------+
| id | first_name | last_name | salary |
+----+------------+-----------+--------+
| 60 | Manoj | Kumar | 5000 |
+----+------------+-----------+--------+
1 row in set (0.00 sec)
mysql>select * from CERTIFICATE;
+----+--------------------+------------------+-------------+
| id | certificate_type | certificate_name | employee_id |
+----+--------------------+------------------+-------------+
| 16 | ProjectManagement | PMP | 60 |
| 17 | BusinessManagement | MBA | 60 |
| 18 | ComputerScience | MCA | 60 |
+----+--------------------+------------------+-------------+
3 rows in set (0.00 sec)
mysql>