码迷,mamicode.com
首页 > Web开发 > 详细

Hibernate关联关系映射(单向篇)

时间:2016-05-12 11:53:20      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:

Hibernate关联关系可分为单向关联和双向关联两大类。单向关联可以分为一对一、一对多、多对一和多对多4种关联方式,而多向关联可以分为一对一、一对多和多对多3种关联方式。

Hibernate连接管理类HibernateUtil.java

public class HibernateUtil {
    private static SessionFactory sessionFactory;

    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();

    static{
        try{
            Configuration cfg = new Configuration().configure();
            sessionFactory = cfg.buildSessionFactory();
        }catch(Throwable ex){
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory(){
        return sessionFactory;
    }

    public static Session getSession() throws HibernateException{
        Session session = (Session)threadLocal.get();
        if(session == null || !session.isOpen()){
            session = (sessionFactory != null)?sessionFactory.openSession():null;
            threadLocal.set(session);
        }

        return session;
    }

    public static void closeSession() throws HibernateException{
        Session session = (Session)threadLocal.get();
        threadLocal.set(null);
        if(session != null){
            session.close();
        }
    }

    public static void shutdown(){
        getSessionFactory().close();
    }

}

1.单向的一对一关联

(1)通过主键关联

通过主键关联,是指两个数据表之间通过主键建立一对一的关联关系。这两张表的主键值是相同的,一张表改动时,另一张也会相关的发生改变,从而避免多余字段被创建,但基于主键关联的持久化类(其对应的数据表称为从表)不能拥有自己的主键生成策略,它的主键由关联类负责生成。另外,增加one-to-one元素来关联属性,必须为one-to-one元素增加constrained=”true”属性,表明该类主键由关联类生成。

示例:

实体类:

User.java

public class User {
    private int userid;
    private String name;
    private String password;
    private Address address;
    public int getUserid() {
        return userid;
    }
    public void setUserid(int userid) {
        this.userid = userid;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }   
}

Address.java

public class Address {
    private int addressid;
    private String addressinfo;
    public int getAddressid() {
        return addressid;
    }
    public void setAddressid(int addressid) {
        this.addressid = addressid;
    }
    public String getAddressinfo() {
        return addressinfo;
    }
    public void setAddressinfo(String addressinfo) {
        this.addressinfo = addressinfo;
    }


}

表结构:

user表:

技术分享

address表:

技术分享

配置文件:

User.hbm.xml

<hibernate-mapping>
    <class name="com.entity.User" table="user">
        <id name="id" type="java.lang.Integer" column="user_id">
            <generator class="foreign">
                <param name="property">address</param>
            </generator>
        </id>

        <property name="name" type="java.lang.String" column="name">
        </property>
        <property name="password" type="java.lang.String" column="password">
        </property>
        <one-to-one name="address" class="Address" constrained="true"></one-to-one>

    </class>
</hibernate-mapping>

Address.hbm.xml

<hibernate-mapping>
    <class name="com.entity.Address" table="address">
        <id name="addressid" type="java.lang.Integer" column="addressid">
            <generator class="identity"/>
        </id>

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


    </class>
</hibernate-mapping>

测试类Test.java

public class Test {
    public static void main(String[] args){
        Session session = HibernateUtil.getSession();
        Transaction tx = session.beginTransaction();

        User u = new User();
        u.setName("sbw");
        u.setPassword("123");

        Address a = new Address();
        a.setAddressinfo("heu");
        u.setAddress(a);

        session.save(a);
        session.save(u);
        tx.commit();

        HibernateUtil.closeSession();

    }
}

运行结果:

技术分享

(2)通过外键关联

通过外键关联时两张数据表的主键是不同的,通过在一张表中添加外键列来保持一对一的关系。配置外键关联关系时需要使用many-to-one元素。因为通过外键关联的一对一关系,本质上是多对一关系的特例。因此,只需在many-to-one元素中增加unique=“true”属性即可,这相当于在多的一端增加了唯一性的约束,表示多的一端也必须是唯一的,这样就变成为单向的一对一关系了。

示例:

实体类与通过主键关联相同。

表结构:

user表

技术分享

address表

技术分享

配置文件:

User.hbm.xml

<hibernate-mapping>
    <class name="com.entity.User" table="user">
        <id name="userid" type="java.lang.Integer" column="userid">
            <generator class="identity"/>
        </id>

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

        <many-to-one name="address" class="com.entity.Address" unique="true" column="addressid"></many-to-one>

    </class>
</hibernate-mapping>

Address.hbm.xml

<hibernate-mapping>
    <class name="com.entity.Address" table="address">
        <id name="addressid" type="java.lang.Integer" column="addressid">
            <generator class="identity"/>
        </id>

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


    </class>
</hibernate-mapping>

测试类与通过主键关联一样

运行结果:

技术分享

2.单向一对多关联

单向的一对多关联映射关系主要是通过外键来关联的。一对多的关联映射是在表示多的一方的数据表中增加一个外键,并由“一”的一方指向“多”的一方。单向的一对多关联的持久化类里需要包含一个集合属性,在“一”的一方访问“多”的一方时,“多”的一方将以集合的形式来体现。

示例:

实体类:

User.java

public class User {
    private int userid;
    private String name;
    private String password;
    private Set<Address> address = new HashSet<Address>();

    public int getUserid() {
        return userid;
    }
    public void setUserid(int userid) {
        this.userid = userid;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public Set<Address> getAddress() {
        return address;
    }
    public void setAddress(Set<Address> address) {
        this.address = address;
    }       
}

Address.java

public class Address {
    private int addressid;
    private String addressinfo;

    public int getAddressid() {
        return addressid;
    }
    public void setAddressid(int addressid) {
        this.addressid = addressid;
    }
    public String getAddressinfo() {
        return addressinfo;
    }
    public void setAddressinfo(String addressinfo) {
        this.addressinfo = addressinfo;
    }   
}

表结构:

User表

技术分享

Address表

技术分享

配置文件

User.hbm.xml

<hibernate-mapping>
    <class name="com.entity.User" table="user">
        <id name="userid" type="java.lang.Integer" column="userid">
            <generator class="identity"/>
        </id>

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

        <set name="address" table="address" inverse="false" lazy="true">
            <key>
                <column name="userid"/>
            </key>

            <one-to-many class="com.entity.User"/>
        </set>

    </class>
</hibernate-mapping>

Address.hbm.xml

<hibernate-mapping>
    <class name="com.entity.Address" table="address">
        <id name="addressid" type="java.lang.Integer" column="addressid">
            <generator class="identity"/>
        </id>

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


    </class>
</hibernate-mapping>

测试代码

Test.java

public class Test {
    public static void main(String[] args){
        Session session = HibernateUtil.getSession();
        Transaction tx = session.beginTransaction();

        User u = new User();
        u.setName("sbw");
        u.setPassword("123");

        Address a = new Address();
        a.setAddressinfo("heu");
        Address a1 = new Address();
        a1.setAddressinfo("hrb");

        u.getAddress().add(a);
        u.getAddress().add(a1);

        session.save(a);
        session.save(a1);
        session.save(u);
        tx.commit();

        HibernateUtil.closeSession();

    }
}

运行结果:

技术分享

3.单向的多对一关联

单向的多对一关联映射关系也是通过外键来关联的。多对一的映射方式类似于一对多的映射方式,不过它的映射关系是由“多”的一方指向“一”的一方。在表示“多”的一方的数据表中增加一个外键来指向表示“一”的一方的数据表,“一”的一方作为主表,”多“的一方作为从表。

示例:

实体类

User.java

public class User {
    private int userid;
    private String name;
    private String password;
    private Address address = new Address();

    public int getUserid() {
        return userid;
    }
    public void setUserid(int userid) {
        this.userid = userid;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }       
}

Address.java

public class Address {
    private int addressid;
    private String addressinfo;

    public int getAddressid() {
        return addressid;
    }
    public void setAddressid(int addressid) {
        this.addressid = addressid;
    }
    public String getAddressinfo() {
        return addressinfo;
    }
    public void setAddressinfo(String addressinfo) {
        this.addressinfo = addressinfo;
    }   
}

表结构:

user表

技术分享

address表

技术分享

配置文件:

User.hbm.xml

<hibernate-mapping>
    <class name="com.entity.User" table="user">
        <id name="userid" type="java.lang.Integer" column="userid">
            <generator class="identity"/>
        </id>

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

        <many-to-one name="address" column="addressid"/> 

    </class>
</hibernate-mapping>

Address.hbm.xml

<hibernate-mapping>
    <class name="com.entity.Address" table="address">
        <id name="addressid" type="java.lang.Integer" column="addressid">
            <generator class="identity"/>
        </id>

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


    </class>
</hibernate-mapping>

测试类Test.java

public class Test {
    public static void main(String[] args){
        Session session = HibernateUtil.getSession();
        Transaction tx = session.beginTransaction();

        User u = new User();
        u.setName("sbw");
        u.setPassword("123");

        User u1 = new User();
        u.setName("gaoya");
        u.setPassword("456");

        Address a = new Address();
        a.setAddressinfo("heu");

        u.setAddress(a);
        u1.setAddress(a);

        session.save(a);
        session.save(u);
        session.save(u1);
        tx.commit();

        HibernateUtil.closeSession();

    }
}

测试结果:

技术分享

4.单向的多对多关联

多对多关联在数据库中是比较常见的,它利用中间表将两个主表关联起来。中间表的作用是将两张表的主键作为其外键,通过外键建立这两张表的映射关系。在单向的多对多关联中,需要在主控端的类定义中增加一个Set集合属性,使得被关联一方的类的实例以集合的形式存在。

示例:

实体类:

User.java

public class User {
    private int userid;
    private String name;
    private String password;
    private Set<Address> address = new HashSet<Address>();

    public int getUserid() {
        return userid;
    }
    public void setUserid(int userid) {
        this.userid = userid;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public Set<Address> getAddress() {
        return address;
    }
    public void setAddress(Set<Address> address) {
        this.address = address;
    }       
}

Address.java

public class Address {
    private int addressid;
    private String addressinfo;

    public int getAddressid() {
        return addressid;
    }
    public void setAddressid(int addressid) {
        this.addressid = addressid;
    }
    public String getAddressinfo() {
        return addressinfo;
    }
    public void setAddressinfo(String addressinfo) {
        this.addressinfo = addressinfo;
    }   
}

表结构:

user表:

技术分享

user_address表:

技术分享

address表:

技术分享

配置文件:

User.hbm.xml

<hibernate-mapping>
    <class name="com.entity.User" table="user">
        <id name="userid" type="java.lang.Integer" column="userid">
            <generator class="identity"/>
        </id>

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

        <set name="address" table="user_address">
            <key column="userid"/>
            <many-to-many column="addressid" class="com.entity.Address"/>
        </set> 

    </class>
</hibernate-mapping>

Address.hbm.xml

<hibernate-mapping>
    <class name="com.entity.Address" table="address">
        <id name="addressid" type="java.lang.Integer" column="addressid">
            <generator class="identity"/>
        </id>

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


    </class>
</hibernate-mapping>

测试代码Test.java

public class Test {
    public static void main(String[] args){
        Session session = HibernateUtil.getSession();
        Transaction tx = session.beginTransaction();

        User u = new User();
        u.setName("sbw");
        u.setPassword("123");       
        User u1 = new User();
        u1.setName("gaoya");
        u1.setPassword("456");

        Address a = new Address();
        a.setAddressinfo("heu");
        Address a1 = new Address();
        a1.setAddressinfo("hrb");

        u.getAddress().add(a);
        u.getAddress().add(a1);
        u1.getAddress().add(a);
        u1.getAddress().add(a1);

        session.save(a);
        session.save(a1);
        session.save(u);
        session.save(u1);
        tx.commit();

        HibernateUtil.closeSession();

    }
}

测试结果:

技术分享

Hibernate关联关系映射(单向篇)

标签:

原文地址:http://blog.csdn.net/woaigaolaoshi/article/details/51378147

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!