Hibernate組件映射

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

Hibernate組件映射示例

創建一個Java項目:componentmapping,項目的目錄結構如下圖所示 -

Hibernate組件映射

下面我們來看看每個文件中的代碼。

文件: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,應該能到到插入的數據了。