hibernate一对一映射主键关联

 

Hibernate一对一主键关联

主键关联:两个表中的数据使用相同的主键值.

一﹑确定数据的一对一关联关系

本例中的数据表为companyaddress,一个company对应一个address构成一对一关系.数据脚本如下:

==================================================

表字段

company

   ID,companyName

Address

   ID,companyID,address

==================================================

脚本

drop database if exists test;

create database test;

use test;

create table company

(

 ID int auto_increment not null primary key,

 companyName varchar(20)

);

 

create table address

(

 ID int auto_increment not null primary key,

 address varchar(20)

);

二﹑编写数据表的映射bean(本例的beanmyeclipse自动生成)

Company:

package com.guopeng.bo;

 

import java.io.Serializable;

 

/**

 * A class that represents a row in the company table.

 * You can customize the behavior of this class by editing the class, {@link Company()}.

 * WARNING: DO NOT EDIT THIS FILE. This is a generated file that is synchronized * by MyEclipse Hibernate tool integration.

 */

public abstract class AbstractCompany implements Serializable

{

 

    private int hashValue = 0;

 

  

    private java.lang.Integer id;

    private java.lang.String companyname;

    private Address address;//设置companyaddress的关系

    public AbstractCompany()

    {}

    public AbstractCompany(java.lang.Integer id)

    {

        this.setId(id);

    }

    public java.lang.Integer getId()

    {

        return id;

    }

    public void setId(java.lang.Integer id)

    {

        this.hashValue = 0;

        this.id = id;

    }

    public java.lang.String getCompanyname()

    {

        return this.companyname;

    }

    public void setCompanyname(java.lang.String companyname)

    {

        this.companyname = companyname;

    }

    public boolean equals(Object rhs)

    {

        if (rhs == null)

            return false;

        if (! (rhs instanceof Company))

            return false;

        Company that = (Company) rhs;

        if (this.getId() != null && that.getId() != null)

        {

            if (! this.getId().equals(that.getId()))

            {

                return false;

            }

//红色部分为添加部分,hibernate对两个对象进行比较时如果在默认情况下只对主键做对比,如果主键相同,则认为这两个对象相等.而事实上有些情况下并非如此,:数据更新后和原来的数据做对比时,如果是默认情况下更新后的数据如原来的数据相等,因此要加上一些对象的其它重要属性也做对比.

            if(! this.getCompanyname().equals(that.getCompanyname()))

            {

                return false;

            }

        }

        return true;

    }

    public int hashCode()

    {

        if (this.hashValue == 0)

        {

            int result = 17;

            int idValue = this.getId() == null ? 0 : this.getId().hashCode();

            result = result * 37 + idValue;

            idValue = this.getCompanyname() == null ? 0 : this.getCompanyname().hashCode();

            result = result * 37 + idValue;

            idValue = this.getAddress().getAddress() == null ? 0 : this.getAddress().getAddress().hashCode();

            result = result * 37 + idValue;

            this.hashValue = result;

        }

        return this.hashValue;

    }

    public Address getAddress() {

        return address;

    }

    public void setAddress(Address address) {

        this.address = address;

    }

}

 

Company表的映射XML文件:

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

                            "-//Hibernate/Hibernate Mapping DTD 2.0//EN"

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

 

<!-- DO NOT EDIT: This is a generated file that is synchronized -->

<!-- by MyEclipse Hibernate tool integration.                   -->

<!-- Created Mon Jun 19 14:41:35 CST 2006                         -->

<hibernate-mapping package="com.guopeng.bo">

    <class name="Company" table="company">

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

            <generator class="native"/>

        </id>

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

        <one-to-one name="address" class="Address" cascade="all"></one-to-one>

    </class>

</hibernate-mapping>

 

Address:

package com.guopeng.bo;

 

import java.io.Serializable;

 

public abstract class AbstractAddress implements Serializable

{

    private int hashValue = 0;

    private java.lang.Integer id;

    private java.lang.String address;

private Company company;//设置addresscompany的关系

 

    public AbstractAddress()

    {

    }

    public AbstractAddress(java.lang.Integer id)

    {

        this.setId(id);

    }

    public java.lang.Integer getId()

    {

        return id;

    }

    public void setId(java.lang.Integer id)

    {

        this.hashValue = 0;

        this.id = id;

    }

    public java.lang.String getAddress()

    {

        return this.address;

    }

    public void setAddress(java.lang.String address)

    {

        this.address = address;

    }

    public boolean equals(Object rhs)

    {

        if (rhs == null)

            return false;

        if (! (rhs instanceof Address))

            return false;

        Address that = (Address) rhs;

        if (this.getId() != null && that.getId() != null)

        {

            if (! this.getId().equals(that.getId()))

            {

                return false;

            }

            if(! this.getAddress().equals(that.getAddress()))

            {

                return false;

            }

            if(! this.getCompany().getId().equals(that.getCompany().getId()))

            {

                return false;

            }

           

        }

        return true;

    }

    public int hashCode()

    {

        if (this.hashValue == 0)

        {

            int result = 17;

            int idValue = this.getId() == null ? 0 : this.getId().hashCode();

            result = result * 37 + idValue;

            idValue = this.getAddress() == null ? 0 : this.getAddress().hashCode();

            result = result * 37 + idValue;

            idValue = this.getCompany().getId() == null ? 0 : this.getCompany().getId().hashCode();

            result = result * 37 + idValue;

            this.hashValue = result;

        }

        return this.hashValue;

    }

    public Company getCompany() {

        return company;

    }

    public void setCompany(Company company) {

        this.company = company;

    }

}

 

Address表的映射XML文件:

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

                            "-//Hibernate/Hibernate Mapping DTD 2.0//EN"                            "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >

<!-- DO NOT EDIT: This is a generated file that is synchronized -->

<!-- by MyEclipse Hibernate tool integration.                   -->

<!-- Created Mon Jun 19 14:41:25 CST 2006                         -->

<hibernate-mapping package="com.guopeng.bo">

    <class name="Address" table="address">

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

        unsaved-value="0">

    <!—-company表共享主键-->

        <generator class="foreign" >

             <param name="property">company</param>

        </generator>

        </id>

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

    <!—constrained设置为true表示address表必须与company表的主键值相同-->

        <one-to-one name="company" class="Company"

        constrained="true">

        </one-to-one>

    </class>

</hibernate-mapping>

三﹑hibernatesession操作

1.    保存数据

public void saveCompany()

    {

        try

        {

        session=SessionFactory.currentSession();

        tran=session.beginTransaction();//关联关系中保存数据应用启用事务,如果不启用事务,有时被关联表的数据无法保存

       address.setAddress(companyAddress);

        company.setCompanyname(companyName);

       //设置addresscompany的相互关系

        company.setAddress(address);

        address.setCompany(company);

 

        session.save(this.company);

        tran.commit();

        session.close();

        SessionFactory.closeSession();

        }catch(Exception e)

        {

            try

            {

                tran.rollback();

            } catch (HibernateException e1)

            {

                e1.printStackTrace();

            }

            System.out.println(e.toString());

        }

}

 

2.    更新数据

public void updateCompany(Company company)

    {

        try

        {

            session=SessionFactory.currentSession();

            session.update(company);

            session.flush();//同步数据库

            session.close();

            SessionFactory.closeSession();

        }

        catch(Exception e)

        {

            e.printStackTrace();

        }

    }

updateCompany(Company company)方法中的company参数的传入

 

id=request.getParameter("companyID");

            companyName=request.getParameter("companyName");

            address=request.getParameter("address");

           

            //设置属性

           Company.setId(id);

            company.setCompanyname(companyName);

            adds.setId(id);

adds.setAddress(address);

//设置相互关系

adds.setCompany(company);

            company.setAddress(adds);

           

            //更新数据库

            add.updateCompany(company);

3.    删除数据 

删除company的同时删除与company对应的address

public void deleteCompany(String companyID) throws HibernateException

    {

        session=SessionFactory.currentSession();

        company=(Company)session.load(Company.class,new Integer(companyID));

        session.delete(company);

        session.flush();

        session.close();

        SessionFactory.closeSession();

    }

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值