zoukankan      html  css  js  c++  java
  • 集合映射中的映射列表(使用xml文件)

    如果持久化类具有List对象,我们可以通过映射文件中的类的<list>元素或注释来映射List

    在这里,我们正在使用论坛的场景,其中一个问题有多个答案。

    在这里,我们使用论坛的场景,其中一个问题有多个答案。

    我们来看看如何在映射文件中实现列表(List):

    <class name="com.yiibai.Question" table="q100">  
           ...        
              <list name="answers" table="ans100">  
              <key column="qid"></key>  
              <index column="type"></index>  
              <element column="answer" type="string"></element>  
              </list>  
    
           ...  
    </class>
    
    XML

    注: List 和 Map是基于索引的集合,因此将在表中创建一个额外的列进行索引。

    集合映射中的映射列表(List)示例

    在这个例子中,我们将看到列表(List)在集合映射的完整示例。 这是List中存储字符串值而不是实体引用的示例,这就是为什么要在列表元素中使用element标签而不是one-to-many标签的元素。

    这个示例项目的完整结构如下图所示 -

    1)创建持久化类

    这个持久化类定义了类的属性,包括List

    package com.yiibai;
    
    import java.util.List;
    
    public class Question {
        private int id;
        private String qname;
        private List<String> answers;
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getQname() {
            return qname;
        }
    
        public void setQname(String qname) {
            this.qname = qname;
        }
    
        public List<String> getAnswers() {
            return answers;
        }
    
        public void setAnswers(List<String> answers) {
            this.answers = answers;
        }
    
    }
    
    Java

    2)创建持久化类的映射文件

    在这里,我们创建了用于定义列表的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_100">
            <id name="id">
                <generator class="increment"></generator>
            </id>
            <property name="qname"></property>
    
            <list name="answers" table="answer_100">
                <key column="qid"></key>
                <index column="type"></index>
                <element column="answer" type="string"></element>
            </list>
    
        </class>
    
    </hibernate-mapping>
    
    XML

    3)创建配置文件

    此文件包含有关数据库和映射文件的信息。

    文件:hibernate.hnm.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>
    
    XML

    4)创建存储数据的类

    在这个类(MainTest.java)中,用来存储Question类的数据。使用HQL来获取Answer类的所有记录,包括答案。 在这个示例中,它从功能相关的两个表中获取数据。

    package com.yiibai;
    
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    
    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();
    
            ArrayList<String> list1 = new ArrayList<String>();
            list1.add("java is a programming language");
            list1.add("java is a platform");
    
            ArrayList<String> list2 = new ArrayList<String>();
            list2.add("Servlet is an Interface");
            list2.add("Servlet is an API");
    
            Question question1 = new Question();
            question1.setQname("Java 是什么?");
            question1.setAnswers(list1);
    
            Question question2 = new Question();
            question2.setQname("Hibernate 是什么?");
            question2.setAnswers(list2);
    
            session.persist(question1);
            session.persist(question2);
    
            t.commit();
    
            // 查询数据
            Query<Question> query = session.createQuery("from Question");
            List<Question> list = query.list();
    
            Iterator<Question> itr = list.iterator();
            while (itr.hasNext()) {
                Question q = itr.next();
                System.out.println("Question Name: " + q.getQname());
    
                // printing answers
                List<String> list21 = q.getAnswers();
                Iterator<String> itr2 = list21.iterator();
                while (itr2.hasNext()) {
                    System.out.println(itr2.next());
                }
    
            }
            session.close();
            System.out.println("success");
    
        }
    }
    
    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.
    Sun Mar 26 05:18:56 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 question_100
    Hibernate: insert into question_100 (qname, id) values (?, ?)
    Hibernate: insert into question_100 (qname, id) values (?, ?)
    Hibernate: insert into answer_100 (qid, type, answer) values (?, ?, ?)
    Hibernate: insert into answer_100 (qid, type, answer) values (?, ?, ?)
    Hibernate: insert into answer_100 (qid, type, answer) values (?, ?, ?)
    Hibernate: insert into answer_100 (qid, type, answer) values (?, ?, ?)
    Hibernate: select question0_.id as id1_1_, question0_.qname as qname2_1_ from question_100 question0_
    Question Name: What is Java?
    Hibernate: select answers0_.qid as qid1_0_0_, answers0_.answer as answer3_0_0_, answers0_.type as type2_0_ from answer_100 answers0_ where answers0_.qid=?
    java is a programming language
    java is a platform
    Question Name: What is Servlet?
    Hibernate: select answers0_.qid as qid1_0_0_, answers0_.answer as answer3_0_0_, answers0_.type as type2_0_ from answer_100 answers0_ where answers0_.qid=?
    Servlet is an Interface
    Servlet is an API
    Question Name: What is Java?
    Hibernate: select answers0_.qid as qid1_0_0_, answers0_.answer as answer3_0_0_, answers0_.type as type2_0_ from answer_100 answers0_ where answers0_.qid=?
    java is a programming language
    java is a platform
    Question Name: What is Servlet?
    Hibernate: select answers0_.qid as qid1_0_0_, answers0_.answer as answer3_0_0_, answers0_.type as type2_0_ from answer_100 answers0_ where answers0_.qid=?
    Servlet is an Interface
    Servlet is an API
    Question Name: What is Java?
    Hibernate: select answers0_.qid as qid1_0_0_, answers0_.answer as answer3_0_0_, answers0_.type as type2_0_ from answer_100 answers0_ where answers0_.qid=?
    java is a programming language
    java is a platform
    Question Name: What is Servlet?
    Hibernate: select answers0_.qid as qid1_0_0_, answers0_.answer as answer3_0_0_, answers0_.type as type2_0_ from answer_100 answers0_ where answers0_.qid=?
    Servlet is an Interface
    Servlet is an API
    Question Name: Java 是什么?
    java is a programming language
    java is a platform
    Question Name: Hibernate 是什么?
    Servlet is an Interface
    Servlet is an API
    success
  • 相关阅读:
    操盘策略:判断强庄股的四个诀窍
    三类股有望继续走强
    操盘策略:股市空头陷阱五大招数
    每日一招:面对亏损我们应该如何操作(鳄鱼法则)
    (转)一个大户的自白:我是这样被两融打爆的
    3.2、迭代
    3.1、切片
    2.4、递归函数
    2.3、函数的参数
    2.2、定义函数
  • 原文地址:https://www.cnblogs.com/borter/p/9522308.html
Copyright © 2011-2022 走看看