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

集合Map映射(使用xml文件)

Hibernate允許我們將Map元素與RDBMS進行映射。 我們知道,ListMap是基于索引的集合。 在map的情況下,索引列作為鍵,元素列用作值。

使用xml文件在集合映射中映射Map的示例

現(xiàn)在,我們創(chuàng)建一個Java工程:ternarystring,項目的完整目錄結(jié)構(gòu)如下圖所示 -

您需要創(chuàng)建以下頁面來映射Map元素。

  • Question.java
  • question.hbm.xml
  • hibernate.cfg.xml
  • MainTest.java
  • FetchTest.java

文件:Question.java -

package com.yiibai;

import java.util.Map;

public class Question {
    private int id;
    private String name, username;
    private Map<String, String> answers;

    public Question() {
    }

    public Question(String name, String username, Map<String, String> answers) {
        super();
        this.name = name;
        this.username = username;
        this.answers = answers;
    }

    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 String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Map<String, String> getAnswers() {
        return answers;
    }

    public void setAnswers(Map<String, String> answers) {
        this.answers = answers;
    }

}

文件: question.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.Question" table="question_736">
        <id name="id">
            <generator class="native"></generator>
        </id>
        <property name="name"></property>
        <property name="username"></property>

        <map name="answers" table="answer736" cascade="all">
            <key column="questionid"></key>
            <index column="answer" type="string"></index>
            <element column="username" type="string"></element>
        </map>
    </class>

</hibernate-mapping>

文件:hibernate.cfg.xml

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

<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>

    <session-factory>
        <property name="hbm2ddl.auto">update</property>

        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="connection.username">root</property>
        <property name="connection.password">123456</property>
        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
        <property name="show_sql">true</property>

        <mapping resource="question.hbm.xml" />
    </session-factory>

</hibernate-configuration>

文件:MainTest.java

package com.yiibai;

import java.util.HashMap;
import org.hibernate.*;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.*;

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


        /**** 上面是配置準(zhǔn)備,下面開始我們的數(shù)據(jù)庫操作 ******/
        Session session = sessionFactory.openSession();// 從會話工廠獲取一個session

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

        HashMap<String, String> map1 = new HashMap<String, String>();
        map1.put("java is a programming language", "John Lee ");
        map1.put("java is a platform", "Ashok Su");

        HashMap<String, String> map2 = new HashMap<String, String>();
        map2.put("servlet technology is a server side programming",
                "John Milton");
        map2.put("Servlet is an Interface", "Ashok Lee");
        map2.put("Servlet is a package", "Rahul Su");

        Question question1 = new Question("What is java?", "Alok", map1);
        Question question2 = new Question("What is servlet?", "Jai Dixit", map2);

        session.persist(question1);
        session.persist(question2);

        t.commit();
        session.close();
        System.out.println("successfully stored");
    }
}

文件: FetchTest.java -

package com.yiibai;

import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;

public class FetchTest {
    public static void main(String[] args) {
        Session session = new Configuration().configure().buildSessionFactory()
                .openSession();

        Query query = session.createQuery("from Question ");
        List<Question> list = query.list();

        Iterator<Question> iterator = list.iterator();
        while (iterator.hasNext()) {
            Question question = iterator.next();
            System.out.println("question id:" + question.getId());
            System.out.println("question name:" + question.getName());
            System.out.println("question posted by:" + question.getUsername());
            System.out.println("answers.....");
            Map<String, String> map = question.getAnswers();
            Set<Map.Entry<String, String>> set = map.entrySet();

            Iterator<Map.Entry<String, String>> iteratoranswer = set.iterator();
            while (iteratoranswer.hasNext()) {
                Map.Entry<String, String> entry = (Map.Entry<String, String>) iteratoranswer
                        .next();
                System.out.println("answer name:" + entry.getKey());
                System.out.println("answer posted by:" + entry.getValue());
            }
        }
        session.close();
    }
}

運行測試結(jié)果

首先,運行 MainTest.java 以插入數(shù)據(jù),然后運行 FetchTest.java查詢數(shù)據(jù) -

  1. 執(zhí)行 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 02:31:54 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: create table answer736 (questionid integer not null, answer varchar(255) not null, username varchar(255), primary key (questionid, answer)) engine=InnoDB
    Hibernate: create table question_736 (id integer not null auto_increment, name varchar(255), username varchar(255), primary key (id)) engine=InnoDB
    Hibernate: alter table answer736 add constraint FK8a0ar72dc6qqqh79ujtwm4w9o foreign key (questionid) references question_736 (id)
    Hibernate: insert into question_736 (name, username) values (?, ?)
    Hibernate: insert into question_736 (name, username) values (?, ?)
    Hibernate: insert into answer736 (questionid, answer, username) values (?, ?, ?)
    Hibernate: insert into answer736 (questionid, answer, username) values (?, ?, ?)
    Hibernate: insert into answer736 (questionid, answer, username) values (?, ?, ?)
    Hibernate: insert into answer736 (questionid, answer, username) values (?, ?, ?)
    Hibernate: insert into answer736 (questionid, answer, username) values (?, ?, ?)
    successfully stored
    
  2. 執(zhí)行 FetchTest.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 02:34:17 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 question0_.id as id1_1_, question0_.name as name2_1_, question0_.username as username3_1_ from question_736 question0_
question id:1
question name:What is java?
question posted by:Alok
answers.....
Hibernate: select answers0_.questionid as question1_0_0_, answers0_.username as username3_0_0_, answers0_.answer as answer2_0_ from answer736 answers0_ where answers0_.questionid=?
answer name:java is a programming language
answer posted by:John Lee 
answer name:java is a platform
answer posted by:Ashok Su
question id:2
question name:What is servlet?
question posted by:Jai Dixit
answers.....
Hibernate: select answers0_.questionid as question1_0_0_, answers0_.username as username3_0_0_, answers0_.answer as answer2_0_ from answer736 answers0_ where answers0_.questionid=?
answer name:Servlet is a package
answer posted by:Rahul Su
answer name:servlet technology is a server side programming
answer posted by:John Milton
answer name:Servlet is an Interface
answer posted by:Ashok Lee