如果我们的持久化类中有Set对象,可以在映射文件中通过set元素来映射Set。Set元素不需要索引元素。List和Set的一个区别是,Set只存储唯一值。

让我们看看如何在映射文件中实现set:

<class name="cn.javatiky.Question" table="q1002">  
       ...        
          <set name="answers" table="ans1002">  
          <key column="qid"></key>  
          <element column="answer" type="string"></element>  
          </set>  
            
       ...  
</class>  

在集合映射中映射Set的示例

在这个示例中,我们将看到通过set进行集合映射的完整示例。这是一个set存储值而不是实体引用的示例,因此我们将使用element而不是one-to-many。

1) 创建持久化类

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

package cn.javatiku;  
  
import java.util.Set;  
  
public class Question {  
private int id;  
private String qname;  
private Set<String> answers;  
  
//getters and setters  
  
}  

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

这里,我们创建了question.hbm.xml文件来定义set。

<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-mapping PUBLIC  
          "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
          "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">  
  
<hibernate-mapping>  
 <class name="cn.javatiku.Question" table="q1002">  
   <id name="id">  
     <generator class="increment"></generator>  
   </id>  
   <property name="qname"></property>  
            
   <set name="answers" table="ans1002">  
     <key column="qid"></key>  
     <element column="answer" type="string"></element>  
   </set>  
            
 </class>  
            
</hibernate-mapping>  

3) 创建配置文件

此文件包含有关数据库和映射文件的信息。

<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-configuration PUBLIC  
          "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
          "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">  
  
<hibernate-configuration>  
  
    <session-factory>  
        <property name="hbm2ddl.auto">update</property>  
        <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>  
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>  
        <property name="connection.username">system</property>  
        <property name="connection.password">jtp</property>  
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>  
    <mapping resource="question.hbm.xml"/>  
    </session-factory>  
  
</hibernate-configuration>  

4) 创建存储数据的类

在这个类中,我们存储了Question类的数据。

package cn.javatiku;    
    
import java.util.HashSet;    
    
import org.hibernate.*;  
import org.hibernate.boot.Metadata;  
import org.hibernate.boot.MetadataSources;  
import org.hibernate.boot.registry.StandardServiceRegistry;  
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;   
    
public class StoreData {    
 public static void main(String[] args) {    
      
     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();  
        Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
          
        SessionFactory factory=meta.getSessionFactoryBuilder().build();  
        Session session=factory.openSession();  
       
 Transaction t=session.beginTransaction();    
        
    
    HashSet<String> set1=new HashSet<String>();    
    set1.add("Java is a programming language");    
    set1.add("Java is a platform");    
        
    HashSet<String> set2=new HashSet<String>();    
    set2.add("Servlet is an Interface");    
    set2.add("Servlet is an API");    
        
    Question question1=new Question();    
    question1.setQname("What is Java?");    
    question1.setAnswers(set1);    
        
    Question question2=new Question();    
    question2.setQname("What is Servlet?");    
    question2.setAnswers(set2);    
        
    session.persist(question1);    
    session.persist(question2);    
        
    t.commit();    
    session.close();    
    System.out.println("success");    
 }    
}    

输出

4-1.png
4-2.png

如何获取Set的数据

这里,我们使用HQL来获取Question类的所有记录,包括答案。在这种情况下,它从功能依赖的两个表中获取数据。

package cn.javatiku;    
    
import java.util.*;  
  
import javax.persistence.TypedQuery;  
  
import org.hibernate.*;  
import org.hibernate.boot.Metadata;  
import org.hibernate.boot.MetadataSources;  
import org.hibernate.boot.registry.StandardServiceRegistry;  
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;  
    
public class FetchData {    
public static void main(String[] args) {    
        
     StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();  
        Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();  
          
        SessionFactory factory=meta.getSessionFactoryBuilder().build();  
        Session session=factory.openSession();  
       
 Transaction t=session.beginTransaction();    
        
    TypedQuery query=session.createQuery("from Question");    
    List<Question> list=query.getResultList();    
        
    Iterator<Question> itr=list.iterator();    
    while(itr.hasNext()){    
        Question q=itr.next();    
        System.out.println("Question Name: "+q.getQname());    
            
        //printing answers    
        Set<String> set=q.getAnswers();    
        Iterator<String> itr2=set.iterator();    
        while(itr2.hasNext()){    
            System.out.println(itr2.next());    
        }    
            
    }    
    session.close();    
    System.out.println("success");    
        
}    
}    

输出

4-3.png

标签: Hibernate, Hibernate教程, Hibernate框架, Hibernate框架设计, Hibernate初级教程, Hibernate框架用法, Hibernate指南, Hibernate入门, Hibernate中级教程, Hibernate进阶教程, Hibernate高级教程, Hibernate下载