Hibernate允许我们将Map元素与RDBMS进行映射。 我们知道,ListMap是基于索引的集合。 在map的情况下,索引列作为键,元素列用作值。

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

现在,我们创建一个Java工程:ternarystring,项目的完整目录结构如下图所示 -

您需要创建以下页面来映射Map元素。

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

文件:Question.java -

package com.yiibai;

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;
} }
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_736">
<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>
XML

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

文件: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, String> map1 = new HashMap<String, String>();
map1.put("java is a programming language", "John Lee ");
map1.put("java is a platform", "Ashok Su"); 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 Lee");
map2.put("Servlet is a package", "Rahul Su"); 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");
}
}
Java

文件: FetchTest.java -

package com.yiibai;

import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*; public class FetchTest {
public static void main(String[] args) {
Session session = new Configuration().configure().buildSessionFactory()
.openSession(); 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("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 = (Map.Entry<String, String>) iteratoranswer
.next();
System.out.println("answer name:" + entry.getKey());
System.out.println("answer posted by:" + entry.getValue());
}
}
session.close();
}
}
Java

运行测试结果

首先,运行 MainTest.java 以插入数据,然后运行 FetchTest.java查询数据 -

  1. 执行 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 02:31:54 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 answer736 (questionid integer not null, answer varchar(255) not null, username varchar(255), primary key (questionid, answer)) engine=InnoDB
    Hibernate: create table question_736 (id integer not null auto_increment, name varchar(255), username varchar(255), primary key (id)) engine=InnoDB
    Hibernate: alter table answer736 add constraint FK8a0ar72dc6qqqh79ujtwm4w9o foreign key (questionid) references question_736 (id)
    Hibernate: insert into question_736 (name, username) values (?, ?)
    Hibernate: insert into question_736 (name, username) values (?, ?)
    Hibernate: insert into answer736 (questionid, answer, username) values (?, ?, ?)
    Hibernate: insert into answer736 (questionid, answer, username) values (?, ?, ?)
    Hibernate: insert into answer736 (questionid, answer, username) values (?, ?, ?)
    Hibernate: insert into answer736 (questionid, answer, username) values (?, ?, ?)
    Hibernate: insert into answer736 (questionid, answer, username) values (?, ?, ?)
    successfully stored
    Shell
  2. 执行 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 02:34:17 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_, question0_.username as username3_1_ from question_736 question0_
question id:1
question name:What is java?
question posted by:Alok
answers.....
Hibernate: select answers0_.questionid as question1_0_0_, answers0_.username as username3_0_0_, answers0_.answer as answer2_0_ from answer736 answers0_ where answers0_.questionid=?
answer name:java is a programming language
answer posted by:John Lee
answer name:java is a platform
answer posted by:Ashok Su
question id:2
question name:What is servlet?
question posted by:Jai Dixit
answers.....
Hibernate: select answers0_.questionid as question1_0_0_, answers0_.username as username3_0_0_, answers0_.answer as answer2_0_ from answer736 answers0_ where answers0_.questionid=?
answer name:Servlet is a package
answer posted by:Rahul Su
answer name:servlet technology is a server side programming
answer posted by:John Milton
answer name:Servlet is an Interface
answer posted by:Ashok Lee

集合Map映射(使用xml文件)的更多相关文章

  1. SQL 映射的 XML 文件

    MyBatis 真正的力量是在映射语句中.这里是奇迹发生的地方. 对于所有的力量, SQL映射的 XML 文件是相当的简单.当然如果你将它们和对等功能的 JDBC 代码来比较,你会发现映射文件节省了大 ...

  2. 五、SQL映射的XML文件

    MyBatis真正的力量是在映射语句中.这里是奇迹发生的地方.对于所有的力量,SQL映射的XML文件是相当的简单.当然如果你将它们和对等功能的JDBC代码来比较,你会发现映射文件节省了大约95%的代码 ...

  3. Python连载43-current中的map函数、xml文件

    一.current中的map函数 1.map(fn,*iterable,timeout=None) (1)跟map函数相类似(2)函数需要异步执行(3)timeout代表超时时间 (4)map和sub ...

  4. IDEA Mybatis 找不到映射器xml文件

    用IDEA新建了一个测试MyBatis工程,工程目录如下 其中config是MyBatis的配置文件,内容如下 <?xml version="1.0" encoding=&q ...

  5. mybatis 找不到映射器xml文件 (idea)

    原因是: idea不会编译src的java目录的xml文件 所以解决思路就是:将IDEA maven项目中src源代码下的xml等资源文件编译进classes文件夹 具体操作方法就是:配置maven的 ...

  6. Spring中注入List,Set,Map,Properties的xml文件配置方法

    下面的例子展示了如何注入 List – <list/> Set – <set/> Map – <map/> Properties – <props/> ...

  7. MyBatis学习(四)XML配置文件之SQL映射的XML文件

    SQL映射文件常用的元素: 1.select 查询语句是MyBatis最常用的语句之一. 执行简单查询的select元素是非常简单的: <select id="selectUser&q ...

  8. Could not find resource——mybatis 找不到映射器xml文件

    今天用IDEA写Mybatis的时候,测试报了如图所示的错,恶心死我了,后来解决了,总结一下,防止下回跳坑,当然,也是做一个分享,如果有朋友遇到这个错,希望有所帮助 Error parsing SQL ...

  9. 集合Map多对多映射(使用xml文件)

    我们可以使用set,bag,map等来映射多对多关系.在这里,我们将使用map来进行多对多映射. 在这种情况下,将创建三个表. 多对多映射示例 我们需要创建以下文件来映射map元素.首先创建一个项目: ...

随机推荐

  1. 《新一代视频压缩码标准-H.264_AVC》读书笔记1

    摘要 第一章 绪论 正文 1.一般而言,视频信号信息量大,传输网络所需要的带宽相对较宽.例如,一路可视电话或会议电视信号,由于其活动内容较少,所需带宽较窄,但要达到良好质量,不压缩约需若干 Mbps, ...

  2. java直接跳转页面

    public static String genForwardHtml(String url, Map<String, String> parameters, String charset ...

  3. FL2440 ubifs文件系统烧录遇到的问题——内核分区的重要性

    之前用的文件系统是initramfs的,这种文件系统是编译进内核里的,而开机之后内核是写在内存中的,所以每次掉电之后写进文件系统中的东西都会丢失.所以决定换成ubifs的文件系统.这种文件系统是跟内核 ...

  4. webpack配置:增加babel支持、打包后调试

    一.babel支持 Babel其实是几个模块化的包,其核心功能位于称为babel-core的npm包中,webpack可以把其不同的包整合在一起使用,对于每一个你需要的功能或拓展,你都需要安装单独的包 ...

  5. window安装mysql5.7.11

    1.到mysql官网(http://dev.mysql.com/downloads/mysql/)下载压缩包,我的是win7 64位的,根据自己的系统进行下载 2.解压到自己的目录,我的是 E:\so ...

  6. Nginx 报错413 Request Entity Too Large 上传文件过大

    1.进入Nginx安装路径下的conf文件夹中(我的路径是:/usr/local/nginx/conf) 2.打开nginx.conf,在http大括号中第一行加语句:client_max_body_ ...

  7. jQuery 全选 正反选

    <script src="http://code.jquery.com/jquery-1.4.4.min.js" type="text/javascript&quo ...

  8. [转载]Android开发者必须深入学习的10个应用开源项目

    [转载]Android开发者必须深入学习的10个应用开源项目 原文地址:Android开发者必须深入学习的10个应用开源项目(http://blog.sina.com.cn/s/blog_7b8a63 ...

  9. Java实现图片裁剪预览功能

    在项目中.我们须要做些类似头像上传,图片裁剪的功能,ok看以下文章! 须要插件:jQuery Jcrop 后端代码: package org.csg.upload; import java.awt.R ...

  10. lodash map

    _.map(collection, [iteratee=_.identity]) 创建一个经过 iteratee 处理的集合中每一个元素的结果数组. iteratee 会传入3个参数:(value, ...