RSS

Hibernate的集合映射

01 Apr

Hibernate的集合映射  (Set Mapping, List Mapping, Bag Mapping, IdBag Mapping, Map Mapping)

————————————————————————–

Set接口

1. Set类型的对象,被加入的对象不能重复,同时被加入的对象也没有固定顺序,使用Iterator遍历。事实上,Set映射所获取的类型是org.hibernate.collection.PersistentBag类型。

2. HashSet (效率高,不记录顺序)

3. LinkedHashSet (按照加入顺序,进行输出)

4. TreeSet (会排序按照排序进行输出)

 

定义一个代表用户的User类,User类中,使用Set对象保存用户的多个email地址。但是不能重复,不注重顺序。开发的时候常用到Set映射,而List映射很少用到。

 

User2.java

package hibernate.example.vo;

import java.util.HashSet;

import java.util.Set;

public class Users2 {

    private Integer id;

    private String username;

    private String password;

    private Set<String> emails = new HashSet<String>();

   

    public Users2() {

        super();

    }

    public Integer getId() {

        return id;

    }

    public void setId(Integer id) {

        this.id = id;

    }

    public String getUsername() {

        return username;

    }

    public void setUsername(String username) {

        this.username = username;

    }

    public String getPassword() {

        return password;

    }

    public void setPassword(String password) {

        this.password = password;

    }

    public Set<String> getEmails() {

        return emails;

    }

    public void setEmails(Set<String> emails) {

        this.emails = emails;

    }

}

 

User2.hbm.xml

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

    <class name="hibernate.example.vo.Users2" table="USERS2">

        <id name="id" type="java.lang.Integer" column="id">

            <generator class="increment" />

        </id>

        <property name="username" type="java.lang.String" column="USERNAME"/>

        <property name="password" type="java.lang.String" column="PASSWORD"/>

        <set name="emails" table="EMAIL">

            <!– Foreign Key –>

            <key column="userid" foreign-key="id"/>

            <element type="java.lang.String" column="EMAIL"/>

        </set>

    </class>

</hibernate-mapping>

SetMappingTest.java

package hibernate.example.test;

import java.util.Set;

import org.hibernate.Session;

import hibernate.example.util.HibernateSessionFactoryUtil;

import hibernate.example.vo.Users2;

 

public class SetMappingTest {

 

    public static void main(String[] args) {

        new SetMappingTest().load();

    }

   

    public void add(){

        Session session = HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();

        session.beginTransaction();

        Users2 u = new Users2();

        u.setUsername("Nate");

        u.setPassword("nate");

        u.getEmails().add("finchan_ding@hotmail.com");

        u.getEmails().add("finchanding@gmail.com");

        session.save(u);

        session.getTransaction().commit();

    }

   

    public void load(){

        Session session = HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();

        session.beginTransaction();

        Users2 u = (Users2)session.load(Users2.class, new Integer(2));

        String username = u.getUsername();

        String password = u.getPassword();

        System.out.println(username + ‘\t’ + password);

        Set<String> emails = u.getEmails();

        System.out.println(emails.getClass().getName());

        for(String email: emails){

            System.out.print(email + ‘\t’);

        }

        session.getTransaction().commit();     

    }

}

————————————————————————–

List接口

List对象包含的对象,可以重复加入,同时还会记录加入对象的先后顺序。

1. ArrayList

2. LinkedList

List映射 – 事实上,所获取的类型是org.hibernate.collection.PersistentBag类型。需要在表中提供idx(Number)列

 

User3.java

package hibernate.example.vo;

import java.util.ArrayList;

import java.util.List;

public class Users3 {

    private Integer id;

    private String username;

    private String password;

    private List<String> emails = new ArrayList<String>();

   

    public Users3() {

        super();

    }

    public Integer getId() {

        return id;

    }

    public void setId(Integer id) {

        this.id = id;

    }

    public String getUsername() {

        return username;

    }

    public void setUsername(String username) {

        this.username = username;

    }

    public String getPassword() {

        return password;

    }

    public void setPassword(String password) {

        this.password = password;

    }

    public List<String> getEmails() {

        return emails;

    }

    public void setEmails(List<String> emails) {

        this.emails = emails;

    }

       

}

 

User3.hbm.xml

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

    <class name="hibernate.example.vo.Users3" table="USERS2">

        <id name="id" type="java.lang.Integer" column="id">

            <generator class="increment" />

        </id>

        <property name="username" type="java.lang.String" column="USERNAME"/>

        <property name="password" type="java.lang.String" column="PASSWORD"/>

        <list name="emails" table="EMAIL2">

            <!– Foreign Key –>

            <key column="userid" foreign-key="id"/>

            <index column="idx" type="java.lang.Integer"/>

            <element column="EMAIL" type="java.lang.String"/>

        </list>

    </class>

</hibernate-mapping>

 

ListMappingTest.java

package hibernate.example.test;

import hibernate.example.util.HibernateSessionFactoryUtil;

import hibernate.example.vo.Users3;

import java.util.List;

import org.hibernate.Session;

 

public class ListMappingTest {

 

    public static void main(String[] args) {

        new ListMappingTest().load();

    }

   

    public void add(){

        Session session = HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();

        session.beginTransaction();

        Users3 u = new Users3();

        u.setUsername("Nate");

        u.setPassword("nate");

        u.getEmails().add("finchan_ding@hotmail.com");

        u.getEmails().add("finchanding@gmail.com");

        session.save(u);

        session.getTransaction().commit();

    }

   

    public void load(){

        Session session = HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();

        session.beginTransaction();

        Users3 u = (Users3)session.load(Users3.class, new Integer(4));

        String username = u.getUsername();

        String password = u.getPassword();

        System.out.println(username + ‘\t’ + password);

        List<String> emails = u.getEmails();

        System.out.println(emails.getClass().getName());

        for(String email: emails){

            System.out.print(email + ‘\t’);

        }

        session.getTransaction().commit();     

    }

}

 

————————————————————————–

Bag映射 – 事实上,所获取的类型是org.hibernate.collection.PersistentBag类型。

1. Bag对象允许重复的元素,但是不记录添加对象的先后顺序。(List+Map)

2. JDK没有提供Bag集合类型,Hibernate中的Bag映射使用的是自己的Bag类型。

3. 删除的时候(remove()),只能删掉一个,而不是全部删除。

POJO使用Collection collection =  new ArrayList(),映射文件使用Bag,里面的内容和Set相同。

 

User3.java

package hibernate.example.vo;

import java.util.ArrayList;

import java.util.Collection;

 

public class Users4 {

    private Integer id;

    private String username;

    private String password;

    private Collection<String> emails = new ArrayList<String>();

   

    public Users4() {

        super();

    }

    public Integer getId() {

        return id;

    }

    public void setId(Integer id) {

        this.id = id;

    }

    public String getUsername() {

        return username;

    }

    public void setUsername(String username) {

        this.username = username;

    }

    public String getPassword() {

        return password;

    }

    public void setPassword(String password) {

        this.password = password;

    }

    public Collection<String> getEmails() {

        return emails;

    }

    public void setEmails(Collection<String> emails) {

        this.emails = emails;

    }

       

}

 

User3.hbm.xml

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

    <class name="hibernate.example.vo.Users4" table="USERS2">

        <id name="id" type="java.lang.Integer" column="id">

            <generator class="increment" />

        </id>

        <property name="username" type="java.lang.String" column="USERNAME"/>

        <property name="password" type="java.lang.String" column="PASSWORD"/>

        <bag name="emails" table="EMAIL">

            <!– Foreign Key –>

            <key column="userid" foreign-key="id"/>

            <element column="EMAIL" type="java.lang.String"/>

        </bag>

    </class>

</hibernate-mapping>

BagMappingTest.java

package hibernate.example.test;

import hibernate.example.util.HibernateSessionFactoryUtil;

import hibernate.example.vo.Users4;

import java.util.Collection;

import org.hibernate.Session;

 

public class BagMappingTest {

 

    public static void main(String[] args) {

        new BagMappingTest().removeDuplicate();

    }

   

    public void add(){

        Session session = HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();

        session.beginTransaction();

        Users4 u = new Users4();

        u.setUsername("Uta");

        u.setPassword("uta");

        u.getEmails().add("uta@hotmail.com");

        u.getEmails().add("uta@gmail.com");

        u.getEmails().add("uta@gmail.com");

        session.save(u);

        session.getTransaction().commit();

    }

   

    public void load(){

        Session session = HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();

        session.beginTransaction();

        Users4 u = (Users4)session.load(Users4.class, new Integer(6));

        String username = u.getUsername();

        String password = u.getPassword();

        System.out.println(username + ‘\t’ + password);

        Collection<String> emails = u.getEmails();

        System.out.println(emails.getClass().getName());

        for(String email: emails){

            System.out.print(email + ‘\t’);

        }

        session.getTransaction().commit();     

    }

   

    public void removeDuplicate(){

        Session session = HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();

        session.beginTransaction();

        Users4 u = (Users4)session.load(Users4.class, new Integer(6));

        u.setPassword("123");

        u.setUsername("Puma");

        u.getEmails().remove("uta@gmail.com");

        session.save(u);

        session.getTransaction().commit();             

    }

}

 

————————————————————————–

IdIdBag映射

Bag集合映射的一种扩展,Hibernate还提供IdBag映射,可以在定义Bag映射时,为每个加入的对象指定"id"(数据库要有这样的列),其它名字也可以。这个和List很接近。

User5.java

package hibernate.example.vo;

import java.util.ArrayList;

import java.util.Collection;

 

public class Users5 {

    private Integer id;

    private String username;

    private String password;

    private Collection<String> emails = new ArrayList<String>();

   

    public Users5() {

        super();

    }

    public Integer getId() {

        return id;

    }

    public void setId(Integer id) {

        this.id = id;

    }

    public String getUsername() {

        return username;

    }

    public void setUsername(String username) {

        this.username = username;

    }

    public String getPassword() {

        return password;

    }

    public void setPassword(String password) {

        this.password = password;

    }

    public Collection<String> getEmails() {

        return emails;

    }

    public void setEmails(Collection<String> emails) {

        this.emails = emails;

    }

       

}

 

User5.hbm.xml

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

    <class name="hibernate.example.vo.Users5" table="USERS2">

        <id name="id" type="java.lang.Integer" column="id">

            <generator class="increment" />

        </id>

        <property name="username" type="java.lang.String" column="USERNAME"/>

        <property name="password" type="java.lang.String" column="PASSWORD"/>

        <idbag name="emails" table="EMAIL3">

            <collection-id type="java.lang.Integer" column="id">

                <generator class="increment"/>

            </collection-id>

            <!– Foreign Key –>

            <key column="userid" foreign-key="id"/>

            <element column="EMAIL" type="java.lang.String"/>

        </idbag>

    </class>

</hibernate-mapping>
 

IdBagMappingTest.java

package hibernate.example.test;

import hibernate.example.util.HibernateSessionFactoryUtil;

import hibernate.example.vo.Users5;

import java.util.Collection;

import org.hibernate.Session;

 

public class IdBagMappingTest {

 

    public static void main(String[] args) {

        new IdBagMappingTest().removeDuplicate();

    }

   

    public void add(){

        Session session = HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();

        session.beginTransaction();

        Users5 u = new Users5();

        u.setUsername("Uta");

        u.setPassword("uta");

        u.getEmails().add("uta@hotmail.com");

        u.getEmails().add("uta@gmail.com");

        u.getEmails().add("uta@gmail.com");

        session.save(u);

        session.getTransaction().commit();

    }

   

    public void load(){

        Session session = HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();

        session.beginTransaction();

        Users5 u = (Users5)session.load(Users5.class, new Integer(7));

        String username = u.getUsername();

        String password = u.getPassword();

        System.out.println(username + ‘\t’ + password);

        Collection<String> emails = u.getEmails();

        System.out.println(emails.getClass().getName());

        for(String email: emails){

            System.out.print(email + ‘\t’);

        }

        session.getTransaction().commit();     

    }

   

    public void removeDuplicate(){

        Session session = HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();

        session.beginTransaction();

        Users5 u = (Users5)session.load(Users5.class, new Integer(7));

        u.setPassword("123");

        u.setUsername("Puma");

        u.getEmails().remove("uta@gmail.com");

        session.save(u);

        session.getTransaction().commit();             

    }

}

 

————————————————————————–

Map接口

1. Map对象中保存的是key/value形式的一对对象,key与value都是Object类型的变量,key与value是一一对应的关系,key值不能重复。

2. HashMap (不能重复)

3. LinkedHashMap (不能重复,按照加入顺序输出)

4. TreeMap (不能重复,但是会排序输出)

 

Map映射

Map对象所包含的每一个对象(value)都有一个key与之对应,所以将Map集合对象的数据存储到数据库表中的时候,必须同时存储value对应的key值。

比如用户有Home Tel, Office Tel和Mobile

Map phones = new HashMap();

phones.put("office", 110);

phones.put("home", 112);

phones.put("mobile", 119);

 

User6.java

package hibernate.example.vo;

import java.util.HashMap;

import java.util.Map;

 

public class Users6 {

    private Integer id;

    private String username;

    private String password;

    private Map<String, String> phones = new HashMap<String, String>();

   

    public Users6() {

        super();

    }

    public Integer getId() {

        return id;

    }

    public void setId(Integer id) {

        this.id = id;

    }

    public String getUsername() {

        return username;

    }

    public void setUsername(String username) {

        this.username = username;

    }

    public String getPassword() {

        return password;

    }

    public void setPassword(String password) {

        this.password = password;

    }

    public Map<String, String> getPhones() {

        return phones;

    }

    public void setPhones(Map<String, String> phones) {

        this.phones = phones;

    }

       

}

 

User6.hbm.xml

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

    <class name="hibernate.example.vo.Users6" table="USERS2">

        <id name="id" type="java.lang.Integer" column="id">

            <generator class="increment" />

        </id>

        <property name="username" type="java.lang.String" column="USERNAME"/>

        <property name="password" type="java.lang.String" column="PASSWORD"/>

        <!– <map name="phones" table="phone" sort="natural"> –>

        <!–order-by根据数据库所对应的列进行排序 –>

        <map name="phones" table="phone" order-by="PHONE_NUMBER DESC">

            <key column="userid" foreign-key="id"/>

            <map-key type="java.lang.String" column="USAGE"/>           

            <element type="java.lang.String" column="PHONE_NUMBER"/>

        </map>

    </class>

</hibernate-mapping>

MapMappingTest.java

package hibernate.example.test;

import hibernate.example.util.HibernateSessionFactoryUtil;

import hibernate.example.vo.Users6;

import java.util.Map;

import java.util.Set;

import org.hibernate.Session;

 

public class MapMappingTest {

 

    public static void main(String[] args) {

        new MapMappingTest().load();

    }

   

    public void add(){

        Session session = HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();

        session.beginTransaction();

        Users6 u = new Users6();

        u.setUsername("Longman");

        u.setPassword("123");

        Map<String, String> map = u.getPhones();

        map.put("home", "110");

        map.put("office", "112");

        map.put("mobile", "114");

        session.save(u);

        session.getTransaction().commit();

    }

   

    public void load(){

        Session session = HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();

        session.beginTransaction();

        Users6 u = (Users6)session.get(Users6.class, new Integer(8));

        System.out.println(u.getUsername());

        System.out.println(u.getPassword());

        Map<String, String> phones = u.getPhones();

        Set<String> keys = u.getPhones().keySet();

        for(Object o:keys){

            System.out.println(o + " – " + phones.get(o));

        }

        session.getTransaction().commit();     

    }

}

————————————————————————–

集合映射的排序

1. 利用<set>或<map>标签的sort属性对集合中的数据进行排序,这是在内存中排序,如果数据很多不要用这种方式,用下面的方式排序

2. 利用SQL的orderby子句排序

Advertisements
 
Leave a comment

Posted by on 04/01/2011 in HIBERNATE

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

 
%d bloggers like this: