Hibernate学习-6-集合映射保存和集合数据获取案例

建立User类
package com.cxspace.collection;

import java.util.*;

/**
 * Created by cxspace on 16-7-24.
 */
public class User {

    private int userId;

    private String userName;

    //存储的对象无序
    private Set<String> address;

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

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

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Set<String> getAddress() {
        return address;
    }

    public void setAddress(Set<String> address) {
        this.address = address;
    }

    public List<String> getAddressList() {
        return addressList;
    }

    public void setAddressList(List<String> addressList) {
        this.addressList = addressList;
    }

    public Map<String, String> getAddressMap() {
        return addressMap;
    }

    public void setAddressMap(Map<String, String> addressMap) {
        this.addressMap = addressMap;
    }
}

编写总配置java

<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <!-- 一般,一个session-factory节点表明一个数据库 -->
    <session-factory>
    
        <!-- 1. 数据库链接配置 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql:///learnstruts</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">33269456.cx</property>
        <!-- 
            数据库方法配置, hibernate在运行的时候,会根据不一样的方言生成符合当前数据库语法的sql
         -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        
        
        <!-- 2. 其余相关配置 -->
        <!-- 2.1 显示hibernate在运行时候执行的sql语句 -->
        <property name="hibernate.show_sql">true</property>
        <!-- 2.2 格式化sql
        <property name="hibernate.format_sql">true</property>  -->
        <!-- 2.3 自动建表  -->
        <property name="hibernate.hbm2ddl.auto">update</property>

        <!-- 3. 加载全部映射 
        <mapping resource="cn/itcast/a_hello/Employee.hbm.xml"/>
        -->

    </session-factory>
</hibernate-configuration>

编写user映射配置mysql

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.cxspace.collection">

    <class name="User" table="t_user">
        <id name="userId" column="id">
            <generator class="native"></generator>
        </id>
        <property name="userName"></property>

        <!--
           set集合属性映射
              name 指定要映射的set集合的属性
              table 集合属性要映射到的表
              key 指定集合表的外键字段
              element 指定集合表的其余字段

                   type 元素类型,必定要指定
        -->

        <set name="address" table="t_address">
            <key column="uid"></key>
            <element column="address" type="java.lang.String"></element>
        </set>

        <!--
           list集合映射
               list-index 指定的时排序列的名称(要保证list集合有序)
        -->

        <list name="addressList" table="t_addressList">
            <key column="uid"></key>
            <list-index column="idx"></list-index>
            <element column="address" type="java.lang.String"></element>
        </list>

        <!--
            map集合映射
                 key 指定的外键字段uid
                 map-key 指定map的key
                 element 指定map的value

        -->

        <map name="addressMap" table="t_addressMap">
            <key column="uid"></key>
            <map-key column="shortName" type="java.lang.String"></map-key>
            <element column="address" type="java.lang.String"></element>
        </map>

    </class>
    


</hibernate-mapping>

测试类sql

package com.cxspace.collection;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by cxspace on 16-7-24.
 */
public class Test {

    private static SessionFactory sf;

    static {

        sf  = new Configuration()
                .configure()
                .addClass(User.class)
                .buildSessionFactory();
    }





    public void testSaveSet() throws Exception{

        Session session = sf.openSession();
        session.beginTransaction();

        Set<String> addressSet = new HashSet<String>();
        addressSet.add("北京");
        addressSet.add("深圳");

        User user = new User();

        user.setUserName("cx");
        user.setAddress(addressSet);

        session.save(user);

        session.getTransaction().commit();
        session.close();

    }



    public void testSaveList() throws Exception{

        Session session = sf.openSession();
        session.beginTransaction();

        User user = new User();

        user.setUserName("sike");

        user.getAddressList().add("上海");
        user.getAddressList().add("杭州");

        session.save(user);

        session.getTransaction().commit();
        session.close();

    }


    @org.junit.Test
    public void testSaveMap() throws Exception{

        Session session = sf.openSession();
        session.beginTransaction();

        User user = new User();
        user.setUserName("kill");

        user.getAddressMap().put("a0001","广州");
        user.getAddressMap().put("a0002","南昌");

        session.save(user);


        session.save(user);

        session.getTransaction().commit();
        session.close();
    }
}

 集合数据的获取数据库

    public void testGet() throws Exception{

        Session session = sf.openSession();
        
session.beginTransaction(); User user
= (User) session.get(User.class , 3); //及时加载 System.out.println(user.getUserId()); System.out.println(user.getUserName()); /* 当查询用户,同时能够获取用户关联的list集合的数据(由于有正确的映射) 当使用到集合数据的使用,才向数据库发送执行的sql语句(懒加载) */ System.out.println(user.getAddressList()); session.getTransaction().commit(); session.close(); }