• Hibernate一对多映射列表实例(使用xml文件)


    如果持久化类具有包含实体引用的列表(List)对象,则需要使用一对多关联来映射列表元素。

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

    在这种情况下,一个问题可以有多个答案,每个答案可能有自己的信息,这就是为什么在持久化类中使用列表(包含Answer类的引用)来表示一系列答案。

    下面来看看看持久化类有列表对象(包含Answer类对象)。

    package com.yiibai;  
    
    import java.util.List;  
    
    public class Question {  
        private int id;  
        private String qname;  
        private List<Answer> answers;  
        //getters and setters  
    
    }
    

    Question类有自己的信息,如idanswernamepostedBy

    package com.yiibai;  
    
    public class Answer {  
        private int id;  
        private String answername;  
        private String postedBy;  
        //getters and setters  
    
        }  
    }
    
    Java

    Question类具有包含实体引用的列表对象(即Answer类对象)。在这个示例中,需要使用一对多列表来映射此对象。 下面来看看如何映射它。

    <list name="answers" cascade="all">  
        <key column="qid"></key>  
        <index column="type"></index>  
        <one-to-many class="com.yiibai.Answer"/>
    </list>
    
    XML

    List中的一对多个映射的完整示例

    在这个例子中,我们将看到包含实体引用的映射列表的完整示例。创建一个项目:listonetomany,其完整的项目结构如下图所示 -

    1)创建持久类

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

    Question.java

    package com.yiibai;
    
    import java.util.List;
    
    public class Question {
        private int id;
        private String qname;
        private List<Answer> 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<Answer> getAnswers() {
            return answers;
        }
    
        public void setAnswers(List<Answer> answers) {
            this.answers = answers;
        }
    
    }
    
    Java

    Answer.java

    package com.yiibai;
    
    public class Answer {
        private int id;
        private String answername;
        private String postedBy;
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getAnswername() {
            return answername;
        }
    
        public void setAnswername(String answername) {
            this.answername = answername;
        }
    
        public String getPostedBy() {
            return postedBy;
        }
    
        public void setPostedBy(String postedBy) {
            this.postedBy = postedBy;
        }
    
        public String toString() {
            return answername + " by: " + postedBy;
        }
    }
    
    Java

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

    在这里,我们创建了用于定义列表(List)的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="q501">
            <id name="id">
                <generator class="increment"></generator>
            </id>
            <property name="qname"></property>
    
            <list name="answers" cascade="all">
                <key column="qid"></key>
                <index column="type"></index>
                <one-to-many class="com.yiibai.Answer" />
            </list>
    
        </class>
    
        <class name="com.yiibai.Answer" table="ans501">
            <id name="id">
                <generator class="increment"></generator>
            </id>
            <property name="answername"></property>
            <property name="postedBy"></property>
        </class>
    
    </hibernate-mapping>
    
    XML

    3)创建配置文件

    文件:hibernate.hnm.cfg.xml包含有关数据库和映射文件的信息。

    4)创建存储数据的类

    在这个类中,我们存储Question类的数据。MainTest.java文件的代码如下 -

    package com.yiibai;
    
    import java.util.ArrayList;
    
    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();
    
            Answer ans1 = new Answer();
            ans1.setAnswername("java is a programming language");
            ans1.setPostedBy("Ravi Su");
    
            Answer ans2 = new Answer();
            ans2.setAnswername("java is a platform");
            ans2.setPostedBy("Sudhir Wong");
    
            Answer ans3 = new Answer();
            ans3.setAnswername("Servlet is an Interface");
            ans3.setPostedBy("Jai Li");
    
            Answer ans4 = new Answer();
            ans4.setAnswername("Servlet is an API");
            ans4.setPostedBy("Arun");
    
            ArrayList<Answer> list1 = new ArrayList<Answer>();
            list1.add(ans1);
            list1.add(ans2);
    
            ArrayList<Answer> list2 = new ArrayList<Answer>();
            list2.add(ans3);
            list2.add(ans4);
    
            Question question1 = new Question();
            question1.setQname("What is Java?");
            question1.setAnswers(list1);
    
            Question question2 = new Question();
            question2.setQname("What is Servlet?");
            question2.setAnswers(list2);
    
            session.persist(question1);
            session.persist(question2);
    
            t.commit();
            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 08:54:12 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 ans501 (id integer not null, answername varchar(255), postedBy varchar(255), qid integer, type integer, primary key (id)) engine=InnoDB
    Hibernate: create table q501 (id integer not null, qname varchar(255), primary key (id)) engine=InnoDB
    Hibernate: alter table ans501 add constraint FKlha0fu9fjhckh66ivbt9wxn2p foreign key (qid) references q501 (id)
    Hibernate: select max(id) from q501
    Hibernate: select max(id) from ans501
    Hibernate: insert into q501 (qname, id) values (?, ?)
    Hibernate: insert into ans501 (answername, postedBy, id) values (?, ?, ?)
    Hibernate: insert into ans501 (answername, postedBy, id) values (?, ?, ?)
    Hibernate: insert into q501 (qname, id) values (?, ?)
    Hibernate: insert into ans501 (answername, postedBy, id) values (?, ?, ?)
    Hibernate: insert into ans501 (answername, postedBy, id) values (?, ?, ?)
    Hibernate: update ans501 set qid=?, type=? where id=?
    Hibernate: update ans501 set qid=?, type=? where id=?
    Hibernate: update ans501 set qid=?, type=? where id=?
    Hibernate: update ans501 set qid=?, type=? where id=?
    success
    
    Shell

    如何获取列表的数据

    在这里,我们使用HQL来获取Question类的所有记录,以及每个问题下面的回答。 在这种情况下,它从功能相关的两个表中读取数据。我们直接打印Question类的对象,需要在Answer类中覆盖了toString()方法返回答案标题和发布标题。 所以它打印答案名称和发布标题,而不是参考的ID。

    FetchData.java 代码如下所示 -

    package com.yiibai;  
    import java.util.*;  
    import org.hibernate.*;  
    import org.hibernate.cfg.*;  
    
    public class FetchData {  
    public static void main(String[] args) {  
    
        Session session=new Configuration().configure("hibernate.cfg.xml")  
                              .buildSessionFactory().openSession();  
    
        Query 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<Answer> list2=q.getAnswers();  
            Iterator<Answer> itr2=list2.iterator();  
            while(itr2.hasNext()){  
                System.out.println(itr2.next());  
            }  
    
        }  
        session.close();  
        System.out.println("success");  
    }  
    }
    
    Java

    运行 FetchData.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 08:56:45 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_.qname as qname2_1_ from q501 question0_
    Question Name: What is Java?
    Hibernate: select answers0_.qid as qid4_0_0_, answers0_.id as id1_0_0_, answers0_.type as type5_0_, answers0_.id as id1_0_1_, answers0_.answername as answerna2_0_1_, answers0_.postedBy as postedBy3_0_1_ from ans501 answers0_ where answers0_.qid=?
    java is a programming language by: Ravi Su
    java is a platform by: Sudhir Wong
    Question Name: What is Servlet?
    Hibernate: select answers0_.qid as qid4_0_0_, answers0_.id as id1_0_0_, answers0_.type as type5_0_, answers0_.id as id1_0_1_, answers0_.answername as answerna2_0_1_, answers0_.postedBy as postedBy3_0_1_ from ans501 answers0_ where answers0_.qid=?
    Servlet is an Interface by: Jai Li
    Servlet is an API by: Arun
    success
  • 相关阅读:
    OC 单例实现
    iOS 代码调试
    iOS
    iOS 11 scroll滚动偏移,tableview偏移44,获取view的宽和高
    swift 约束
    OC
    OC 线程操作
    OC 线程操作
    【第35题】2019年OCP认证12C题库062考试最新考试原题-35
    【第34题】2019年OCP认证12C题库062考试最新考试原题-34
  • 原文地址:https://www.cnblogs.com/borter/p/9522315.html
Copyright © 2020-2023  润新知