我们可以使用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