Hibernate学习之映射组件属性1

引言

           组件属性的意思是,持久化类的属性并不是基本数据类型,也不是字符串、日期等标量类型的变量,而是一个复合类型的对象,在持久化过程中,它仅仅被当作值类型,而并非引用另一个持久化实体。

引例

<?xml version="1.0" encoding="GBK"?>
<!-- 指定Hibernate配置文件的DTD信息 -->
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- hibernate-configuration是配置文件的根元素 -->
<hibernate-configuration>
    <session-factory>
        <!-- 指定连接数据库所用的驱动 -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <!-- 指定连接数据库的url,其中hibernate是本应用连接的数据库名 -->
        <property name="connection.url">jdbc:mysql://localhost/hibernate?serverTimezone=GMT%2b8</property>
        <!-- 指定连接数据库的用户名 -->
        <property name="connection.username">root</property>
        <!-- 指定连接数据库的密码 -->
        <property name="connection.password">123</property>
        <!-- 指定连接池里最大连接数 -->
        <property name="hibernate.c3p0.max_size">20</property>
        <!-- 指定连接池里最小连接数 -->
        <property name="hibernate.c3p0.min_size">1</property>
        <!-- 指定连接池里连接的超时时长 -->
        <property name="hibernate.c3p0.timeout">5000</property>
        <!-- 指定连接池里最大缓存多少个Statement对象 -->
        <property name="hibernate.c3p0.max_statements">100</property>
        <property name="hibernate.c3p0.idle_test_period">3000</property>
        <property name="hibernate.c3p0.acquire_increment">2</property>
        <property name="hibernate.c3p0.validate">true</property>
        <!-- 指定数据库方言 -->
        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
        <!-- 根据需要自动创建数据库 -->
        <property name="hbm2ddl.auto">update</property>
        <!-- 显示Hibernate持久化操作所生成的SQL -->
        <property name="show_sql">true</property>
        <!-- 将SQL脚本进行格式化后再输出 -->
        <property name="hibernate.format_sql">true</property>
        <!-- 罗列所有持久化类的类名 -->
        <mapping class="Person"/>
    </session-factory>
</hibernate-configuration>


import javax.persistence.*;
import org.hibernate.annotations.Parent;
/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
 * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author  Yeeku.H.Lee [email protected]
 * @version  1.0
 */
@Embeddable
public class Name
{
    
    
    // 定义first成员变量
    @Column(name="person_firstname")
    private String first;
    // 定义last成员变量
    @Column(name="person_lastname")
    private String last;
    // 引用拥有该Name的Person对象
    @Parent      // ①
    private Person owner;

    // 无参数的构造器
    public Name()
    {
    
    
    }
    // 初始化全部成员变量的构造器
    public Name(String first , String last)
    {
    
    
        this.first = first;
        this.last = last;
    }

    // first的setter和getter方法
    public void setFirst(String first)
    {
    
    
        this.first = first;
    }
    public String getFirst()
    {
    
    
        return this.first;
    }

    // last的setter和getter方法
    public void setLast(String last)
    {
    
    
        this.last = last;
    }
    public String getLast()
    {
    
    
        return this.last;
    }

    // owner的setter和getter方法
    public void setOwner(Person owner)
    {
    
    
        this.owner = owner;
    }
    public Person getOwner()
    {
    
    
        return this.owner;
    }

}

import javax.persistence.*;
/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
 * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author  Yeeku.H.Lee [email protected]
 * @version  1.0
 */
@Entity
@Table(name="person_inf")
public class Person
{
    
    
    @Id @Column(name="person_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;
    private int age;
    // 组件属性name
    private Name name;

    // id的setter和getter方法
    public void setId(Integer id)
    {
    
    
        this.id = id;
    }
    public Integer getId()
    {
    
    
        return this.id;
    }

    // age的setter和getter方法
    public void setAge(int age)
    {
    
    
        this.age = age;
    }
    public int getAge()
    {
    
    
        return this.age;
    }

    // name的setter和getter方法
    public void setName(Name name)
    {
    
    
        this.name = name;
    }
    public Name getName()
    {
    
    
        return this.name;
    }
}
import org.hibernate.*;
import org.hibernate.query.Query;
import org.hibernate.cfg.Configuration;

import javax.persistence.metamodel.EntityType;

import java.util.Map;

public class Main {
    
    
    private static final SessionFactory ourSessionFactory;

    static {
    
    
        try {
    
    
            Configuration configuration = new Configuration();
            configuration.configure();

            ourSessionFactory = configuration.buildSessionFactory();
        } catch (Throwable ex) {
    
    
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getSession() throws HibernateException {
    
    
        return ourSessionFactory.openSession();
    }

    public static void main(final String[] args) throws Exception {
    
    
        final Session session = getSession();
        try {
    
    
            Transaction tx = session.beginTransaction();
            // 创建Person对象
            Person person = new Person();
            // 为Person对象设置属性
            person.setAge(29);
            // 设置组件属性
            person.setName(new Name("crazyit.org" , "疯狂Java联盟"));
            session.save(person);
            tx.commit();
        } finally {
    
    
            session.close();
        }
    }
}

运行结果
在这里插入图片描述

组件属性为集合

           如果组件类又包括了List 、Set 、Map 等集合属性,则可直接在组件类中使用ElementCo ll ection 修饰集合属性,并使用@CollectionTable 指定保存集合属性的数据表一一与普通实体类中映射集合属性的方式基本相同。

<?xml version="1.0" encoding="GBK"?>
<!-- 指定Hibernate配置文件的DTD信息 -->
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- hibernate-configuration是配置文件的根元素 -->
<hibernate-configuration>
    <session-factory>
        <!-- 指定连接数据库所用的驱动 -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <!-- 指定连接数据库的url,其中hibernate是本应用连接的数据库名 -->
        <property name="connection.url">jdbc:mysql://localhost/hibernate?serverTimezone=GMT%2b8</property>
        <!-- 指定连接数据库的用户名 -->
        <property name="connection.username">root</property>
        <!-- 指定连接数据库的密码 -->
        <property name="connection.password">123</property>
        <!-- 指定连接池里最大连接数 -->
        <property name="hibernate.c3p0.max_size">20</property>
        <!-- 指定连接池里最小连接数 -->
        <property name="hibernate.c3p0.min_size">1</property>
        <!-- 指定连接池里连接的超时时长 -->
        <property name="hibernate.c3p0.timeout">5000</property>
        <!-- 指定连接池里最大缓存多少个Statement对象 -->
        <property name="hibernate.c3p0.max_statements">100</property>
        <property name="hibernate.c3p0.idle_test_period">3000</property>
        <property name="hibernate.c3p0.acquire_increment">2</property>
        <property name="hibernate.c3p0.validate">true</property>
        <!-- 指定数据库方言 -->
        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
        <!-- 根据需要自动创建数据库 -->
        <property name="hbm2ddl.auto">update</property>
        <!-- 显示Hibernate持久化操作所生成的SQL -->
        <property name="show_sql">true</property>
        <!-- 将SQL脚本进行格式化后再输出 -->
        <property name="hibernate.format_sql">true</property>
        <!-- 罗列所有持久化类的类名 -->
        <mapping class="Person"/>
    </session-factory>
</hibernate-configuration>

import org.hibernate.*;
import org.hibernate.query.Query;
import org.hibernate.cfg.Configuration;

import javax.persistence.metamodel.EntityType;

import java.util.Map;

public class Main {
    
    
    private static final SessionFactory ourSessionFactory;

    static {
    
    
        try {
    
    
            Configuration configuration = new Configuration();
            configuration.configure();

            ourSessionFactory = configuration.buildSessionFactory();
        } catch (Throwable ex) {
    
    
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getSession() throws HibernateException {
    
    
        return ourSessionFactory.openSession();
    }

    public static void main(final String[] args) throws Exception {
    
    
        final Session session = getSession();
        try {
    
    

            Transaction tx = session.beginTransaction();
            // 创建Person对象
            Person person = new Person();
            person.setAge(29);
            Name n = new Name("crazyit.org" , "疯狂Java联盟");
            n.getPower().put("运气" , 96);
            n.getPower().put("智慧" , 98);
            person.setName(n);
            session.save(person);
            tx.commit();

        } finally {
    
    
            session.close();
        }
    }
}
import java.util.*;
import javax.persistence.*;
import org.hibernate.annotations.Parent;
/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
 * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author  Yeeku.H.Lee [email protected]
 * @version  1.0
 */
@Embeddable
public class Name
{
    
    
    // 定义first成员变量
    @Column(name="person_firstname")
    private String first;
    // 定义last成员变量
    @Column(name="person_lastname")
    private String last;
    // 引用拥有该Name的Person对象
    @Parent
    private Person owner;
    // 集合属性,保留该对象关联的考试成绩
    @ElementCollection(targetClass=Integer.class)
    @CollectionTable(name="power_inf",
            joinColumns=@JoinColumn(name="person_name_id" , nullable=false))
    @MapKeyColumn(name="name_aspect")
    @Column(name="name_power" , nullable=false)
    @MapKeyClass(String.class)
    private Map<String , Integer> power
            = new HashMap<>();

    // 无参数的构造器
    public Name()
    {
    
    
    }
    // 初始化全部成员变量的构造器
    public Name(String first , String last)
    {
    
    
        this.first = first;
        this.last = last;
    }

    // first的setter和getter方法
    public void setFirst(String first)
    {
    
    
        this.first = first;
    }
    public String getFirst()
    {
    
    
        return this.first;
    }

    // last的setter和getter方法
    public void setLast(String last)
    {
    
    
        this.last = last;
    }
    public String getLast()
    {
    
    
        return this.last;
    }

    // owner的setter和getter方法
    public void setOwner(Person owner)
    {
    
    
        this.owner = owner;
    }
    public Person getOwner()
    {
    
    
        return this.owner;
    }

    // power的setter和getter方法
    public void setPower(Map<String ,Integer> power)
    {
    
    
        this.power = power;
    }
    public Map<String ,Integer> getPower()
    {
    
    
        return this.power;
    }
}


import javax.persistence.*;
/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
 * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author  Yeeku.H.Lee [email protected]
 * @version  1.0
 */
@Entity
@Table(name="person_inf")
public class Person
{
    
    
    @Id @Column(name="person_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;
    private int age;
    private Name name;

    // id的setter和getter方法
    public void setId(Integer id)
    {
    
    
        this.id = id;
    }
    public Integer getId()
    {
    
    
        return this.id;
    }

    // age的setter和getter方法
    public void setAge(int age)
    {
    
    
        this.age = age;
    }
    public int getAge()
    {
    
    
        return this.age;
    }

    // name的setter和getter方法
    public void setName(Name name)
    {
    
    
        this.name = name;
    }
    public Name getName()
    {
    
    
        return this.name;
    }

}

运行结果
在这里插入图片描述

集合属性的元素为组件

import javax.persistence.*;
import org.hibernate.annotations.Parent;
/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
 * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author  Yeeku.H.Lee [email protected]
 * @version  1.0
 */
@Embeddable
public class Score
{
    
    
    // 定义first成员变量
    @Column(name="score_level")
    private String level;
    // 定义last成员变量
    @Column(name="score_mark")
    private Integer mark;
    // 引用拥有该Name的Person对象
    @Parent
    private Person owner;

    // 无参数的构造器
    public Score()
    {
    
    
    }
    // 初始化全部成员变量的构造器
    public Score(String level , Integer mark)
    {
    
    
        this.level = level;
        this.mark = mark;
    }

    // level的setter和getter方法
    public void setLevel(String level)
    {
    
    
        this.level = level;
    }
    public String getLevel()
    {
    
    
        return this.level;
    }

    // mark的setter和getter方法
    public void setMark(Integer mark)
    {
    
    
        this.mark = mark;
    }
    public Integer getMark()
    {
    
    
        return this.mark;
    }

    // owner的setter和getter方法
    public void setOwner(Person owner)
    {
    
    
        this.owner = owner;
    }
    public Person getOwner()
    {
    
    
        return this.owner;
    }

}
import java.util.*;

import javax.persistence.*;
/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
 * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author  Yeeku.H.Lee [email protected]
 * @version  1.0
 */
@Entity
@Table(name="person_inf")
public class Person
{
    
    
    @Id @Column(name="person_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;
    private int age;
    // Map集合元素是组件
    @ElementCollection(targetClass=Score.class)
    @CollectionTable(name="score_inf",
            joinColumns=@JoinColumn(name="person_id" , nullable=false))
    @MapKeyColumn(name="subject_name")
    @MapKeyClass(String.class)
    private Map<String , Score> scores
            = new HashMap<>();
    // List集合元素是组件
    @ElementCollection(targetClass=Name.class)
    @CollectionTable(name="nick_inf",
            joinColumns=@JoinColumn(name="person_id" , nullable=false))
    @OrderColumn(name="list_order")
    private List<Name> nicks
            = new ArrayList<>();

    // id的setter和getter方法
    public void setId(Integer id)
    {
    
    
        this.id = id;
    }
    public Integer getId()
    {
    
    
        return this.id;
    }

    // age的setter和getter方法
    public void setAge(int age)
    {
    
    
        this.age = age;
    }
    public int getAge()
    {
    
    
        return this.age;
    }

    // nicks的setter和getter方法
    public void setNicks(List<Name> nicks)
    {
    
    
        this.nicks = nicks;
    }
    public List<Name> getNicks()
    {
    
    
        return this.nicks;
    }

    // scores的setter和getter方法
    public void setScores(Map<String , Score> scores)
    {
    
    
        this.scores = scores;
    }
    public Map<String , Score> getScores()
    {
    
    
        return this.scores;
    }
}
import javax.persistence.*;
import org.hibernate.annotations.Parent;
/**
 * Description:
 * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
 * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee
 * <br/>This program is protected by copyright laws.
 * <br/>Program Name:
 * <br/>Date:
 * @author  Yeeku.H.Lee [email protected]
 * @version  1.0
 */
@Embeddable
public class Name
{
    
    
    // 定义first成员变量
    @Column(name="person_firstname")
    private String first;
    // 定义last成员变量
    @Column(name="person_lastname")
    private String last;
    // 引用拥有该Name的Person对象
    @Parent
    private Person owner;

    // 无参数的构造器
    public Name()
    {
    
    
    }
    // 初始化全部成员变量的构造器
    public Name(String first , String last)
    {
    
    
        this.first = first;
        this.last = last;
    }

    // first的setter和getter方法
    public void setFirst(String first)
    {
    
    
        this.first = first;
    }
    public String getFirst()
    {
    
    
        return this.first;
    }

    // last的setter和getter方法
    public void setLast(String last)
    {
    
    
        this.last = last;
    }
    public String getLast()
    {
    
    
        return this.last;
    }

    // owner的setter和getter方法
    public void setOwner(Person owner)
    {
    
    
        this.owner = owner;
    }
    public Person getOwner()
    {
    
    
        return this.owner;
    }

}
import org.hibernate.*;
import org.hibernate.query.Query;
import org.hibernate.cfg.Configuration;

import javax.persistence.metamodel.EntityType;

import java.util.HashMap;
import java.util.Map;

public class Main {
    
    
    private static final SessionFactory ourSessionFactory;

    static {
    
    
        try {
    
    
            Configuration configuration = new Configuration();
            configuration.configure();

            ourSessionFactory = configuration.buildSessionFactory();
        } catch (Throwable ex) {
    
    
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getSession() throws HibernateException {
    
    
        return ourSessionFactory.openSession();
    }

    public static void main(final String[] args) throws Exception {
    
    
        final Session session = getSession();
        try {
    
    
            Transaction tx = session.beginTransaction();
            // 创建Person对象
            Person person = new Person();
            //为Person对象设置属性
            person.setAge(29);
            //创建一个Map集合
            Map<String , Name> nicks =
                    new HashMap<String , Name>();
            // 向List集合里放入Name对象
            person.getNicks().add(new Name("Wawa" , "Wawa"));
            person.getNicks().add(new Name("Yeeku" , "Lee"));
            // 向List集合里放入Score对象
            person.getScores().put("语文" , new Score("良好" , 85));
            person.getScores().put("数学" , new Score("优秀" , 92));
            session.save(person);
            tx.commit();
        } finally {
    
    
            session.close();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41827511/article/details/105103553
今日推荐