• 集合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;
        }
    
    }
    
    Java

    文件: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;
        }
    
    }
    
    Java

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

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

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

    文件: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("张小哥",
                    "user2@gmail.com", "usa"));
            map1.put("java is a platform", new User("王达叔",
                    "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");
        }
    }
    
    Java

    文件: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();
        }
    }
    
    Java

    运行示例

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

    接下来,运行 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:john@gmail.com
    user country:usa
    answer name:java is a platform
    answer posted by.........
    username:王达叔
    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:王达叔
    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
    
    Shell
     
  • 相关阅读:
    在状态栏中显示鼠标坐标
    为网页设置背景音乐
    将RGB格式的颜色值转换为十六进制格式
    随机产生指定位数的验证码
    树状导航菜单
    ionic入门教程第一课环境搭建和新建ionic项目
    (一)hbase搭建
    数据库的三个范式
    Sql 用于创建表、存储过程、触发器、标量函数的代码
    通过树形结构在控制台显示XML文档的全部内容
  • 原文地址:https://www.cnblogs.com/borter/p/9522368.html
Copyright © 2020-2023  润新知