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

集合Map多對(duì)多映射(使用xml文件)

我們可以使用set,bag,map等來(lái)映射多對(duì)多關(guān)系。在這里,我們將使用map來(lái)進(jìn)行多對(duì)多映射。 在這種情況下,將創(chuàng)建三個(gè)表。

多對(duì)多映射示例

我們需要?jiǎng)?chuàng)建以下文件來(lái)映射map元素。首先創(chuàng)建一個(gè)項(xiàng)目:ternaryobject,它們分別如下 -

  1. Question.java
  2. User.java
  3. question.hbm.xml
  4. user.hbm.xml
  5. hibernate.cfg.xml
  6. MainTest.java
  7. FetchTest.java

項(xiàng)目:ternaryobject的目錄結(jié)構(gòu)如下圖所示 -

下面我們看看每個(gè)文件的代碼。

文件:Question.java

package com.yiibai;

import java.util.Map;

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

    public Question() {
    }

    public Question(String name, Map<String, User> answers) {
        super();
        this.name = name;
        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 Map<String, User> getAnswers() {
        return answers;
    }

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

}

文件:User.java

package com.yiibai;

public class User {
    private int id;
    private String username, email, country;

    public User() {
    }

    public User(String username, String email, String country) {
        super();
        this.username = username;
        this.email = email;
        this.country = country;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getCountry() {
        return country;
    }

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

}

文件: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_m2m">
        <id name="id">
            <generator class="native"></generator>
        </id>
        <property name="name"></property>

        <map name="answers" table="answer_m2m" cascade="all">
            <key column="questionid"></key>
            <index column="answer" type="string"></index>
            <many-to-many class="com.yiibai.User" column="userid"></many-to-many>
        </map>
    </class>

</hibernate-mapping>

文件:user.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.User" table="user_m2m">
        <id name="id">
            <generator class="native"></generator>
        </id>
        <property name="username"></property>
        <property name="email"></property>
        <property name="country"></property>
    </class>

</hibernate-mapping>

文件:hibernate.cfg.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_m2m">
        <id name="id">
            <generator class="native"></generator>
        </id>
        <property name="name"></property>

        <map name="answers" table="answer_m2m" cascade="all">
            <key column="questionid"></key>
            <index column="answer" type="string"></index>
            <many-to-many class="com.yiibai.User" column="userid"></many-to-many>
        </map>
    </class>

</hibernate-mapping>

文件: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. 配置類(lèi)型安全的準(zhǔn)服務(wù)注冊(cè)類(lèi),這是當(dāng)前應(yīng)用的單例對(duì)象,不作修改,所以聲明為final
        // 在configure("cfg/hibernate.cfg.xml")方法中,如果不指定資源路徑,默認(rèn)在類(lèi)路徑下尋找名為hibernate.cfg.xml的文件
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure("hibernate.cfg.xml").build();
        // 2. 根據(jù)服務(wù)注冊(cè)類(lèi)創(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 session = sessionFactory.openSession();// 從會(huì)話(huà)工廠獲取一個(gè)session

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

        HashMap<String, User> map1 = new HashMap<String, User>();
        map1.put("java is a programming language", new User("張小哥",
                "user2@gmail.com", "usa"));
        map1.put("java is a platform", new User("王達(dá)叔",
                "user1@gmail.com", "China"));

        HashMap<String, User> map2 = new HashMap<String, User>();
        map2.put("servlet technology is a server side programming", new User(
                "John Milton", "john.su@gmail.com", "usa"));
        map2.put("Servlet is an Interface", new User("Ashok Kumar",
                "as-top@gmail.com", "China"));

        Question question1 = new Question("Java是什么?", map1);
        Question question2 = new Question("Servlet是什么?", 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.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.*;

public class FetchTest {
    public static void main(String[] args) {
        // 在5.1.0版本中,hibernate則采用如下新方式獲?。?        // 1. 配置類(lèi)型安全的準(zhǔn)服務(wù)注冊(cè)類(lèi),這是當(dāng)前應(yīng)用的單例對(duì)象,不作修改,所以聲明為final
        // 在configure("cfg/hibernate.cfg.xml")方法中,如果不指定資源路徑,默認(rèn)在類(lèi)路徑下尋找名為hibernate.cfg.xml的文件
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure("hibernate.cfg.xml").build();
        // 2. 根據(jù)服務(wù)注冊(cè)類(lèi)創(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 session = sessionFactory.openSession();// 從會(huì)話(huà)工廠獲取一個(gè)session

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

        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("answers.....");
            Map<String, User> map = question.getAnswers();
            Set<Map.Entry<String, User>> set = map.entrySet();

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

運(yùn)行示例

首先,運(yùn)行 MainTest.java,它創(chuàng)建表,并把演示數(shù)據(jù)添加到所創(chuàng)建的表串,得到結(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 21:43:24 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 answer_m2m (questionid integer not null, answer varchar(255) not null, userid integer not null, primary key (questionid, answer)) engine=InnoDB
Hibernate: create table question_m2m (id integer not null auto_increment, name varchar(255), primary key (id)) engine=InnoDB
Hibernate: create table user_m2m (id integer not null auto_increment, username varchar(255), email varchar(255), country varchar(255), primary key (id)) engine=InnoDB
Hibernate: alter table answer_m2m add constraint FKkwn39v22curkbevluik274npg foreign key (userid) references user_m2m (id)
Hibernate: alter table answer_m2m add constraint FK7cy207rewp4u6fbkjekvuyo5 foreign key (questionid) references question_m2m (id)
Hibernate: insert into question_m2m (name) values (?)
Hibernate: insert into user_m2m (username, email, country) values (?, ?, ?)
Hibernate: insert into user_m2m (username, email, country) values (?, ?, ?)
Hibernate: insert into question_m2m (name) values (?)
Hibernate: insert into user_m2m (username, email, country) values (?, ?, ?)
Hibernate: insert into user_m2m (username, email, country) values (?, ?, ?)
Hibernate: insert into answer_m2m (questionid, answer, userid) values (?, ?, ?)
Hibernate: insert into answer_m2m (questionid, answer, userid) values (?, ?, ?)
Hibernate: insert into answer_m2m (questionid, answer, userid) values (?, ?, ?)
Hibernate: insert into answer_m2m (questionid, answer, userid) values (?, ?, ?)
successfully stored

接下來(lái),運(yùn)行 FetchTest.java 來(lái)讀取上面的數(shù)據(jù) -

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 21:50: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 question0_.id as id1_1_, question0_.name as name2_1_ from question_m2m question0_
question id:1
question name:Java是什么?
answers.....
Hibernate: select answers0_.questionid as question1_0_0_, answers0_.userid as userid3_0_0_, answers0_.answer as answer2_0_, user1_.id as id1_2_1_, user1_.username as username2_2_1_, user1_.email as email3_2_1_, user1_.country as country4_2_1_ from answer_m2m answers0_ inner join user_m2m user1_ on answers0_.userid=user1_.id where answers0_.questionid=?
answer name:java is a programming language
answer posted by.........
username:張小哥
user emailid:john@gmail.com
user country:usa
answer name:java is a platform
answer posted by.........
username:王達(dá)叔
user emailid:ashok@gmail.com
user country:india
question id:2
question name:Servlet是什么?
answers.....
Hibernate: select answers0_.questionid as question1_0_0_, answers0_.userid as userid3_0_0_, answers0_.answer as answer2_0_, user1_.id as id1_2_1_, user1_.username as username2_2_1_, user1_.email as email3_2_1_, user1_.country as country4_2_1_ from answer_m2m answers0_ inner join user_m2m user1_ on answers0_.userid=user1_.id where answers0_.questionid=?
answer name:servlet technology is a server side programming
answer posted by.........
username:John Milton
user emailid:john@gmail.com
user country:usa
answer name:Servlet is an Interface
answer posted by.........
username:Ashok Kumar
user emailid:ashok@gmail.com
user country:india
question id:3
question name:Java是什么?
answers.....
Hibernate: select answers0_.questionid as question1_0_0_, answers0_.userid as userid3_0_0_, answers0_.answer as answer2_0_, user1_.id as id1_2_1_, user1_.username as username2_2_1_, user1_.email as email3_2_1_, user1_.country as country4_2_1_ from answer_m2m answers0_ inner join user_m2m user1_ on answers0_.userid=user1_.id where answers0_.questionid=?
answer name:java is a programming language
answer posted by.........
username:張小哥
user emailid:user2@gmail.com
user country:usa
answer name:java is a platform
answer posted by.........
username:王達(dá)叔
user emailid:user1@gmail.com
user country:China
question id:4
question name:Servlet是什么?
answers.....
Hibernate: select answers0_.questionid as question1_0_0_, answers0_.userid as userid3_0_0_, answers0_.answer as answer2_0_, user1_.id as id1_2_1_, user1_.username as username2_2_1_, user1_.email as email3_2_1_, user1_.country as country4_2_1_ from answer_m2m answers0_ inner join user_m2m user1_ on answers0_.userid=user1_.id where answers0_.questionid=?
answer name:servlet technology is a server side programming
answer posted by.........
username:John Milton
user emailid:john.su@gmail.com
user country:usa
answer name:Servlet is an Interface
answer posted by.........
username:Ashok Kumar
user emailid:as-top@gmail.com
user country:China