集合Map多對多對映(使用xml檔案)


我們可以使用setbagmap等來對映多對多關係。在這裡,我們將使用map來進行多對多對映。 在這種情況下,將建立三個表。

多對多對映範例

我們需要建立以下檔案來對映map元素。首先建立一個專案: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

專案:ternaryobject的目錄結構如下圖所示 -

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

檔案: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. 組態型別安全的準服務註冊類,這是當前應用的單例物件,不作修改,所以宣告為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 session = sessionFactory.openSession();// 從對談工廠獲取一個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("張小哥",
                "[email protected]", "usa"));
        map1.put("java is a platform", new User("王達叔",
                "[email protected]", "China"));

        HashMap<String, User> map2 = new HashMap<String, User>();
        map2.put("servlet technology is a server side programming", new User(
                "John Milton", "[email protected]", "usa"));
        map2.put("Servlet is an Interface", new User("Ashok Kumar",
                "[email protected]", "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. 組態型別安全的準服務註冊類,這是當前應用的單例物件,不作修改,所以宣告為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 session = sessionFactory.openSession();// 從對談工廠獲取一個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();
    }
}

執行範例

首先,執行 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 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

接下來,執行 FetchTest.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 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:[email protected]
user country:usa
answer name:java is a platform
answer posted by.........
username:王達叔
user emailid:[email protected]
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:[email protected]
user country:usa
answer name:Servlet is an Interface
answer posted by.........
username:Ashok Kumar
user emailid:[email protected]
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:[email protected]
user country:usa
answer name:java is a platform
answer posted by.........
username:王達叔
user emailid:[email protected]
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:[email protected]
user country:usa
answer name:Servlet is an Interface
answer posted by.........
username:Ashok Kumar
user emailid:[email protected]
user country:China