Hibernate 二 实体映射(一对一映射)



       持久化的原理  ;     持久化类User.java------------->ORM映射文件(User.hbm.xml)------------------------------>数据库表user




一,映射一对一关联关系


  映射一对一关联关系分为主键式和唯一外键方式,


1. 主键式

主键式是一个表的主键参照另外一张表的主键

数据库表

                                            1对1的关联     

      

user表         -------------------------------->        userinfo表

id                                                                      id

username                                                       companyname

password                                                       telephone,email


java对象


相应的持久化类之间的关联关系图

                              1                           1

User.java         < ------------------------- >              UserInfo.java


id                Integer                                         id                             Integer

userName String                                          companyname        String

password  String                                         telephone,email       String      

userInfo      UserInfo                                     user                            User


User类与UserInfo类的一对以关联


实例如下:


hibernate.cfg.xml配置文件

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>
<session-factory>
<property name="connection.username">root</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/album
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="myeclipse.connection.profile">mysql</property>
<property name="connection.password">123456</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<mapping resource="com/xiu/hibernate/bean/User.hbm.xml" />
<mapping resource="com/xiu/hibernate/bean/UserInfo.hbm.xml" />

</session-factory>

</hibernate-configuration>



Java对象


User 类


package com.xiu.hibernate.bean;

import java.io.Serializable;

public class User implements Serializable {
/**
* User与UserInfo是关联关系
*/
private static final long serialVersionUID = 1L;
private Integer id;
private String userName;
private String password;
private UserInfo userInfo;
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 UserInfo getUserInfo() {
return userInfo;
}

public void setUserInfo(UserInfo userInfo) {
this.userInfo = userInfo;
}

public User() {

}

}


UserInfo 类


package com.xiu.hibernate.bean;
import java.io.Serializable;
public class UserInfo implements Serializable{
private static final long serialVersionUID = 1L;
private Integer id;
private String companyName;
private String telephone;
private String email;
private User user;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCompanyName() {
return companyName;
}

public void setCompanyName(String companyName) {
this.companyName = companyName;
}

public String getTelephone() {
return telephone;
}

public void setTelephone(String telephone) {
this.telephone = telephone;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public User getUser() {
return user;
}

public void setUser(User user) {
this.user = user;
}
public UserInfo() {

}

}


User.hbm.xml 文件

<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.xiu.hibernate.bean">
<class name="User" table="user">
<id name="id" column="id" type="int">
<generator class="increment"></generator>
</id>
<property name="userName" type="string" column="username"></property>
<property name="password" type="string" column="password"></property>
<one-to-one name="userInfo"
class="com.xiu.hibernate.bean.UserInfo" constrained="true">
<!-- constrained表示当前主键存在一个外键约束 -->
</one-to-one>
</class>

</hibernate-mapping>


UserInfo.hbm.xml


<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.xiu.hibernate.bean">
<class name="UserInfo" table="userinfo">
<id name="id" column="id" type="int">
<generator class="increment"></generator>
</id>
<property name="companyName" type="string"
column="companyname">
</property>
<property name="telephone" type="string" column="telephone"></property>
<property name="email" type="string" column="email"></property>
<one-to-one name="user" class="com.xiu.hibernate.bean.User"
constrained="true" cascade="all">
<!-- cascade表示级联 主控类的所有操作,对关联类也执行同样操作 -->
</one-to-one>
</class>
</hibernate-mapping>


测试类

package com.xiu.hibernate.test;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;


import com.xiu.hibernate.bean.User;
import com.xiu.hibernate.bean.UserInfo;


public class Test {
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateSessionFactory
.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
tx.begin();
User user = new User();
user.setUserName("朱光和");
user.setPassword("123456");
UserInfo userInfo = new UserInfo();
userInfo.setCompanyName("google");
userInfo.setEmail("zghweb@163.com");
userInfo.setTelephone("13480742613");
user.setUserInfo(userInfo);
userInfo.setUser(user);
session.save(userInfo);
UserInfo useri = (UserInfo) session.load(UserInfo.class, 1);
System.out.println(useri.getUser().getPassword());
tx.commit();
}


}


运行结果

Hibernate: 
    select
        max(id) 
    from
        userinfo
Hibernate: 
    select
        max(id) 
    from
        user
Hibernate: 
    select
        userinfo0_.id as id1_0_,
        userinfo0_.companyname as companyn2_1_0_,
        userinfo0_.telephone as telephone1_0_,
        userinfo0_.email as email1_0_ 
    from
        userinfo userinfo0_ 
    where
        userinfo0_.id=?
Hibernate: 
    select
        user0_.id as id0_0_,
        user0_.username as username0_0_,
        user0_.password as password0_0_ 
    from
        user user0_ 
    where
        user0_.id=?
123456
Hibernate: 
    insert 
    into
        user
        (username, password, id) 
    values
        (?, ?, ?)
Hibernate: 
    insert 
    into
        userinfo
        (companyname, telephone, email, id) 
    values
        (?, ?, ?, ?)





2. 唯一外键

   所谓唯一外键方式就是一个表的外键和另外一个表的唯一主键对应形成一对一的映射关系,这种一对一的关系其实就是多对一关联关系的一种 特殊情况。


客户信息表(client)                                                           

id
name
phone
email
address   int       fk

其实这个外键(address)是用的唯一约束,  其实这2张表看上去是多对一,其实上是一对一,只不过是多对一的一种特殊情况而已                                                        


地址表(address)


id
province
city
street
zopcode

客户信息表(client)    的 address字段 对应地址表(address)的id



对象间的关系

                 1                                                1

Client      < ---------------------------------------->            Address


id                 Integer                                                id                      Integer

name          String                                                  province          String

phone        String                                                   city                   String

email         String                                                  street,zipcode  String

address     Address                                              client                 Client



                                               

Java类


Client 类


package com.xiu.hibernate.bean;

/**
 * Client与Address是关联关系(双向关联关系)
 * 
 * @author Administrator
 * 
 */
public class Client {
private Integer id;
private String name ;
private String phone;
private String email;
private Address address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}


public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}


public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

}


Address 类


package com.xiu.hibernate.bean;
import java.io.Serializable;
public class Address implements Serializable {
private Integer id;
private String province;
private String city;
private String street;
private String zipcode;
private Client client;
public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getProvince() {
return province;
}

public void setProvince(String province) {
this.province = province;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}


public String getStreet() {
return street;
}

public void setStreet(String street) {
this.street = street;
}

public String getZipcode() {
return zipcode;
}

public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}

public Client getClient() {
return client;
}

public void setClient(Client client) {
this.client = client;
}

}


        


Client.hbm.xml


<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.xiu.hibernate.bean">
<class name="Client" table="client">
<id name="id" column="id" type="int">
<generator class="increment"></generator>
</id>
<property name="name" type="string" column="name"></property>
<property name="phone" type="string" column="phone"></property>
<property name="email" type="string" column="email"></property>
<many-to-one name="address"
class="com.xiu.hibernate.bean.Address" column="address" lazy="false"
cascade="all" unique="true">
<!--column充当外键的字段名,lazy为false表示不延迟加载,即立即加载,unique唯一约束,实现一对一关联的目的  -->
</many-to-one>
</class>
</hibernate-mapping>



Address.hbm.xml


<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.xiu.hibernate.bean">
<class name="Address" table="address">
<id name="id" column="id" type="int">
<generator class="increment"></generator>
</id>
<property name="province" type="string" column="province"></property>
<property name="city" type="string" column="city"></property>
<property name="street" type="string" column="street"></property>
<property name="zipcode" type="string" column="zipcode"></property>
<one-to-one name="client" class="com.xiu.hibernate.bean.Client"
property-ref="address">
<!--property-ref 指定关联类的属性名  -->
</one-to-one>
</class>
</hibernate-mapping>


测试类


package com.xiu.hibernate.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.xiu.hibernate.bean.Address;
import com.xiu.hibernate.bean.Client;
public class TestOneToOne {
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateSessionFactory
.getSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
tx.begin();
Address address = new Address();
Client client = new Client();


address.setCity("武汉");
address.setProvince("湖北");
address.setStreet("鲁巷");
address.setZipcode("435000");
client.setEmail("zghweb@163.com");
client.setName("zgh");
client.setPhone("119");

address.setClient(client);
client.setAddress(address);

session.save(client);
tx.commit();
}


}


测试结果


Hibernate: 
    select
        max(id) 
    from
        client
Hibernate: 
    select
        max(id) 
    from
        address
Hibernate: 
    insert 
    into
        address
        (province, city, street, zipcode, id) 
    values
        (?, ?, ?, ?, ?)
Hibernate: 
    insert 
    into
        client
        (name, phone, email, address, id) 
    values
        (?, ?, ?, ?, ?)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值