集合Map多对多映射(使用xml文件)
我们可以使用set
,bag
,map
等来映射多对多关系。在这里,我们将使用map
来进行多对多映射。 在这种情况下,将创建三个表。
多对多映射示例
我们需要创建以下文件来映射map
元素。首先创建一个项目:ternaryobject
,它们分别如下 -
- Question.java
- User.java
- question.hbm.xml
- user.hbm.xml
- hibernate.cfg.xml
- MainTest.java
- 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("张小哥",
"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");
}
}
文件: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: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
集合Map多对多映射(使用xml文件)的更多相关文章
- SQL 映射的 XML 文件
MyBatis 真正的力量是在映射语句中.这里是奇迹发生的地方. 对于所有的力量, SQL映射的 XML 文件是相当的简单.当然如果你将它们和对等功能的 JDBC 代码来比较,你会发现映射文件节省了大 ...
- 五、SQL映射的XML文件
MyBatis真正的力量是在映射语句中.这里是奇迹发生的地方.对于所有的力量,SQL映射的XML文件是相当的简单.当然如果你将它们和对等功能的JDBC代码来比较,你会发现映射文件节省了大约95%的代码 ...
- IDEA Mybatis 找不到映射器xml文件
用IDEA新建了一个测试MyBatis工程,工程目录如下 其中config是MyBatis的配置文件,内容如下 <?xml version="1.0" encoding=&q ...
- mybatis 找不到映射器xml文件 (idea)
原因是: idea不会编译src的java目录的xml文件 所以解决思路就是:将IDEA maven项目中src源代码下的xml等资源文件编译进classes文件夹 具体操作方法就是:配置maven的 ...
- MyBatis学习(四)XML配置文件之SQL映射的XML文件
SQL映射文件常用的元素: 1.select 查询语句是MyBatis最常用的语句之一. 执行简单查询的select元素是非常简单的: <select id="selectUser&q ...
- Could not find resource——mybatis 找不到映射器xml文件
今天用IDEA写Mybatis的时候,测试报了如图所示的错,恶心死我了,后来解决了,总结一下,防止下回跳坑,当然,也是做一个分享,如果有朋友遇到这个错,希望有所帮助 Error parsing SQL ...
- MyBatis的mapper.xml文件的参数问题:org.apache.ibatis.builder.IncompleteElementException: Could not find parameter map
配置参数类型有两种选择,即:parameterType和parameterMap 不管参数是否是基本数据类型还是map类型,都是使用parameterType. 版权声明:本文为博主原创文章,未经博主 ...
- 【转】Mybatis 3.1中 Mapper XML 文件 的学习详解
MyBatis 真正的力量是在映射语句中.这里是奇迹发生的地方.对于所有的力量,SQL 映射的 XML 文件是相当的简单.当然如果你将它们和对等功能的 JDBC 代码来比较,你会发现映射文件节省了大约 ...
- 9.XML文件解析
一.XML简介 XML(EXtensible Markup Language),可扩展标记语言 特点:XML与操作系统.编程语言的开发平台无关 实现不同系统之间的数据交换 作用:数据交互 配置应用程序 ...
随机推荐
- Linux内核regulator架构和编写
电源种类介绍 (百度百科)LDO是low dropout regulator,意为低压差线性稳压器,是相对于传统的线性稳压器来说的.传统的线性稳压器,如78xx系列的芯片都要求输入电压要比输出电压高出 ...
- iOS:iOS 的 APP 如何适应 iPhone 5s/6/6Plus 三种屏幕的尺寸?
原文:http://www.niaogebiji.com/article-4379-1.html?utm_source=tuicool 初代iPhone 2007年,初代iPhone发布,屏幕的宽高是 ...
- docker_usb开发软件部署
1.docker镜像包 (备注:61提供,带桌面版本) rayosx2.0.2.tar 2.paho-mqtt dnf install git -y git clone https://github ...
- 10道典型的JavaScript面试题
问题1: 作用域(Scope) 考虑以下代码: (function() { ; })(); console.log(b); 上述代码会打印出5.这个问题的陷阱就是,在立即执行函数表达式(IIFE)中, ...
- virtualbox虚拟机ubuntu操作系统,设置网络互通、访问,能访问虚拟机swoole的http服务
网络互通 1.设置virtualbox网络连接模式为桥接网卡模式 2.重启虚拟机查看虚拟机IP ifconfig 3.开启window的telnet程序 控制面板->程序->启用或关闭wi ...
- 从C转到JAVA学习路之基本知识对比(转)
转自:http://blog.csdn.net/andywxf01/article/details/53502615 我一直在用C开发,想转到Java时最容易想到的事就是把C里写的代码和功能用JAVA ...
- 字符串去重(hashSet)
public static String deleteRepeat(String strn){ String s=strn; String[] array = s.sp ...
- Yasm 1.3.0 Release Notes
Yasm 1.3.0 Release Notes http://yasm.tortall.net/releases/Release1.3.0.html Target Audience Welcome ...
- ES标准中的相等比较算法 SameValue SameValueZero
1.相等比较算法 The Abstract Equality Comparison Algorithm (==) The Strict Equality Comparison Algorithm (= ...
- 关于部分Android手机安装apk,无法获取正常的logo
最近出现过类似的问题,主要出现是在,MediaPad X1 7.0和MediaPad M1 8.0. 发布应用的时候明明配置好了图标的,但是始终找不到原因,郁闷了好几个小时,也浪费了好几个小时. 如果 ...