鍍金池/ 教程/ Java/ Hibernate組件映射
Hibernate繼承映射
Hibernate每個(gè)子類一張表(使用XML文件)實(shí)例
Hibernate快速入門
Hibernate使用注釋
Hibernate使用xml文件的每個(gè)類層次一張表
Hibernate命名查詢
Hibernate每個(gè)層次類一張表(使用注釋)
Hibernate組件映射
Hibernate事務(wù)管理
Hibernate二級(jí)緩存
集合映射Set(使用xml文件)
Hibernate每個(gè)具體類一張表映射(使用XML)
集合映射中的映射列表(使用xml文件)
Hibernate使用Log4j日志記錄(使用properties文件)
Hibernate集合映射
集合Map映射(使用xml文件)
集合Set映射一對(duì)多(使用xml文件)
Hibernate查詢語(yǔ)言(HQL)
Hibernate入門程序
Hibernate標(biāo)準(zhǔn)查詢語(yǔ)言
Hibernate使用Log4j日志記錄(使用xml文件)
Hibernate教程
Hibernate體系結(jié)構(gòu)
Hibernate生成器類
Hibernate通過(guò)many-to-one元素的一對(duì)一映射
集合Map多對(duì)多映射(使用xml文件)
Web應(yīng)用程序使用Hibernate
Hibernate一對(duì)多映射列表實(shí)例(使用xml文件)
Hibernate通過(guò)one-to-one元素的一對(duì)一映射
Hibernate每個(gè)子類一張表(使用注釋)實(shí)例
集合映射中的映射包(使用xml文件)
通過(guò)Bag一對(duì)多映射示例(使用xml文件)
Hibernate緩存
Hibernate每個(gè)具體類一張表映射(使用注釋)

Hibernate組件映射

在組件映射中,我們將依賴對(duì)象映射作為組件。 組件是存儲(chǔ)為值而不是實(shí)體引用的對(duì)象。 如果從屬對(duì)象沒(méi)有主鍵,則要使用此方法。 它用于組合(HAS-A關(guān)系)的情況下,這就是為什么把它稱為組件。 下面來(lái)看看看有HAS-A關(guān)系的類。

Hibernate組件映射示例

創(chuàng)建一個(gè)Java項(xiàng)目:componentmapping,項(xiàng)目的目錄結(jié)構(gòu)如下圖所示 -

下面我們來(lái)看看每個(gè)文件中的代碼。

文件: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) {
        // 相對(duì)于3.x.x版本hibernate,我們?cè)?.x.x采用如下方式獲取我們的會(huì)話工廠:
        // 1. 解析我們?cè)趆ibernate.cfg.xml中的配置
        // Configuration configuration = new Configuration().configure();
        // 2. 創(chuàng)建服務(wù)注冊(cè)類,進(jìn)一步注冊(cè)初始化我們配置文件中的屬性
        // ServiceRegistry serviceRegistry = new
        // ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
        // 3. 創(chuàng)建我們的數(shù)據(jù)庫(kù)訪問(wèn)會(huì)話工廠
        // SessionFactory sessionFactory =
        // configuration.buildSessionFactory(serviceRegistry);

        // 但在5.1.0版本匯總,hibernate則采用如下新方式獲?。?        // 1. 配置類型安全的準(zhǔn)服務(wù)注冊(cè)類,這是當(dāng)前應(yīng)用的單例對(duì)象,不作修改,所以聲明為final
        // 在configure("cfg/hibernate.cfg.xml")方法中,如果不指定資源路徑,默認(rèn)在類路徑下尋找名為hibernate.cfg.xml的文件
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure("hibernate.cfg.xml").build();
        // 2. 根據(jù)服務(wù)注冊(cè)類創(chuàng)建一個(gè)元數(shù)據(jù)資源集,同時(shí)構(gòu)建元數(shù)據(jù)并生成應(yīng)用一般唯一的的session工廠
        SessionFactory sessionFactory = new MetadataSources(registry)
                .buildMetadata().buildSessionFactory();

        /**** 上面是配置準(zhǔn)備,下面開(kāi)始我們的數(shù)據(jù)庫(kù)操作 ******/
        Session s = sessionFactory.openSession();// 從會(huì)話工廠獲取一個(gè)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>

運(yùn)行示例

下面我們來(lái)運(yùn)行 MainTest.java ,查看輸出結(jié)果 -

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

打開(kāi)數(shù)據(jù)庫(kù)表:emp_cpmap,應(yīng)該能到到插入的數(shù)據(jù)了。