Hibernate允许您将Map元素与RDBMS映射。如我们所知,list和map是基于索引的集合。在map的情况下,索引列作为key,元素列作为value。

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

您需要创建以下页面来映射map元素:

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

Question.java

package cn.javatiku;

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 5.3//EN" 
    "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
    
<hibernate-mapping>
    <class name="cn.javatiku.Question" table="question736">
        <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 5.3//EN" 
    "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hbm2ddl.auto">update</property>
        <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
        <property name="connection.username">system</property>
        <property name="connection.password">jtp</property>
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <mapping resource="question.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

StoreTest.java

package cn.javatiku;

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

public class StoreTest {
    public static void main(String[] args) {
        StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
        Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();
        SessionFactory factory = meta.getSessionFactoryBuilder().build();
        Session session = factory.openSession();
        Transaction t = session.beginTransaction();

        HashMap<String, String> map1 = new HashMap<String, String>();
        map1.put("Java is a programming language", "John Milton");
        map1.put("Java is a platform", "Ashok Kumar");

        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 Kumar");
        map2.put("Servlet is a package", "Rahul Kumar");

        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");
    }
}

Output

5-1.png
5-2.png

FetchTest.java

package cn.javatiku;

import java.util.*;
import javax.persistence.TypedQuery;
import org.hibernate.*;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class FetchTest {
    public static void main(String[] args) {
        StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
        Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();
        SessionFactory factory = meta.getSessionFactoryBuilder().build();
        Session session = factory.openSession();

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

        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 = iteratoranswer.next();
                System.out.println("answer name:" + entry.getKey());
                System.out.println("answer posted by:" + entry.getValue());
            }
        }
        session.close();
    }
}

Output

5-3.png

标签: Hibernate, Hibernate教程, Hibernate框架, Hibernate框架设计, Hibernate初级教程, Hibernate框架用法, Hibernate指南, Hibernate入门, Hibernate中级教程, Hibernate进阶教程, Hibernate高级教程, Hibernate下载