Hibernate元件對映


在元件對映中,我們將依賴物件對映作為元件。 元件是儲存為值而不是實體參照的物件。 如果從屬物件沒有主鍵,則要使用此方法。 它用於組合(HAS-A關係)的情況下,這就是為什麼把它稱為元件。 下面來看看看有HAS-A關係的類。

Hibernate元件對映範例

建立一個Java專案:componentmapping,專案的目錄結構如下圖所示 -

下面我們來看看每個檔案中的程式碼。

檔案:Address.java

package com.yiibai;

public class Address {
    private String city, country;
    private int pincode;

    public Address() {
        super();
        // TODO Auto-generated constructor stub
    }

    public Address(String city, String country, int pincode) {
        super();
        this.city = city;
        this.country = country;
        this.pincode = pincode;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public int getPincode() {
        return pincode;
    }

    public void setPincode(int pincode) {
        this.pincode = pincode;
    }

}

檔案:Employee.java

package com.yiibai;

public class Employee {
    private int id;
    private String name;
    private Address address;

    public Employee(String name, Address address) {
        super();
        this.name = name;
        this.address = address;
    }

    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 Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

}

檔案:MainTest.java

package com.yiibai;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class MainTest {
    public static void main(String[] args) {
        // 相對於3.x.x版本hibernate,我們在4.x.x採用如下方式獲取我們的對談工廠:
        // 1. 解析我們在hibernate.cfg.xml中的組態
        // Configuration configuration = new Configuration().configure();
        // 2. 建立服務註冊類,進一步註冊初始化我們組態檔案中的屬性
        // ServiceRegistry serviceRegistry = new
        // ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
        // 3. 建立我們的資料庫存取對談工廠
        // SessionFactory sessionFactory =
        // configuration.buildSessionFactory(serviceRegistry);

        // 但在5.1.0版本匯總,hibernate則採用如下新方式獲取:
        // 1. 組態型別安全的準服務註冊類,這是當前應用的單例物件,不作修改,所以宣告為final
        // 在configure("cfg/hibernate.cfg.xml")方法中,如果不指定資源路徑,預設在類路徑下尋找名為hibernate.cfg.xml的檔案
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure("hibernate.cfg.xml").build();
        // 2. 根據服務註冊類建立一個後設資料資源集,同時構建後設資料並生成應用一般唯一的的session工廠
        SessionFactory sessionFactory = new MetadataSources(registry)
                .buildMetadata().buildSessionFactory();

        /**** 上面是組態準備,下面開始我們的資料庫操作 ******/
        Session s = sessionFactory.openSession();// 從對談工廠獲取一個session

        // creating transaction object
        Transaction t = s.beginTransaction();

        Employee e1 = new Employee("Mina Sun", new Address("Haikou", "China", 221233));
        Employee e2 = new Employee("Max Su", new Address("Haikou", "China",
                224123));

        s.save(e1);
        s.save(e2);

        t.commit();
        s.close();

        System.out.println("success...");
    }
}

檔案: employee.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

    <class name="com.yiibai.Employee" table="emp_cpmap">
        <id name="id">
            <generator class="increment"></generator>
        </id>
        <property name="name"></property>

        <component name="address" class="com.yiibai.Address">
            <property name="city"></property>
            <property name="country"></property>
            <property name="pincode"></property>
        </component>

    </class>

</hibernate-mapping>

執行範例

下面我們來執行 MainTest.java ,檢視輸出結果 -

log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Mon Mar 27 22:09:16 CST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Hibernate: select max(id) from emp_cpmap
Hibernate: insert into emp_cpmap (name, city, country, pincode, id) values (?, ?, ?, ?, ?)
Hibernate: insert into emp_cpmap (name, city, country, pincode, id) values (?, ?, ?, ?, ?)
success...

開啟資料庫表:emp_cpmap,應該能到到插入的資料了。