注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

欢迎来到三件事的空间

欢迎登陆 javacs.cn

 
 
 

日志

 
 

Hibernate的一对一关联关系  

2010-09-14 11:27:40|  分类: hibernate笔记 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

    对象的关联关系基本上有以下四种:一对一、一对多、多对一、多对多。Hibernate对这种关联关系有着非常好的支持。
   在进行开发的时候,为了提高数据的检索速度,我们会对一些表进行拆分,比如用户表。用户表在开发业务系统的时候是最多的,比如这个业务模块跟流程性相关, 那假如我们将用户的所有信息都存放在同一张表当中,而我们检索最常用的也就是id、用户名、登录号、密码,而其它属性则是很少使用,那这样子会对资源造成 很大的浪费(因为当我们使用hibernate从数据库当中load出数据的时候,hibernate会取出所有的列,并填充属性)。
    那 在进行设计的时候,我们往往会使用一种一对一的关联关系,也就是说,一张用户表拆分成两张表,我们将经常用到的列放在一张表当中,而不常用的放在用户信息 详情表当中。那么,一个用户的数据会拆分成两条,一条存放在用户表当中,一条存放在用户信息详情表当中,这两条数据的关联关系是一种一对一的关联关系。
    那在设计一对一的关联关联应该如何设计呢?
    最关键的一条就是:用户信息详情表的ID既是主键也是外键
    本次使用的数据库是Mysql 5,数据库的物理数据模型图如下:    



建表SQL Script
程序代码 程序代码
/*==============================================================*/
/* DBMS name:      MySQL 5.0                                    */
/* Created on:     2008-4-21 22:31:08                           */
/*==============================================================*/


drop table if exists T_USER;

drop table if exists T_USER_DETAIL;

/*==============================================================*/
/* Table: T_USER                                                */
/*==============================================================*/
create table T_USER
(
   ID                   INT not null auto_increment,
   USER_NAME            VARCHAR(20) not null,
   LOGINID              VARCHAR(20) not null,
   PASSWORD             VARCHAR(32) not null,
   primary key (ID)
);

/*==============================================================*/
/* Table: T_USER_DETAIL                                         */
/*==============================================================*/
create table T_USER_DETAIL
(
   ID                   INT not null,
   AGE                  INT,
   ADDRESS              VARCHAR(50),
   MARRIED              INT,
   DEGREE               VARCHAR(20),
   primary key (ID)
);

alter table T_USER_DETAIL add constraint FK_Reference_1 foreign key (ID)
      references T_USER (ID) on delete restrict on update restrict;



用户对象与用户信息详情对象的对象模型如下图所示:



接着,我们在eclipse当中创建一个新的java project,将hibernate核心包以及它依赖的包文件加到classpath当中。
创建User对象以及hibernate mapping文件

User.java
程序代码 程序代码
package zizz.model;

import java.io.Serializable;

/**
* 该对象是针对着数据库的T_USER表.
*
* <a href="http://xialiang19851204.blog.163.com/blog/http://www.suneca.com">ZIZZ</a>
*
* Create-Time:Apr 21, 2008 9:53:58 PM
*/

public class User implements Serializable {

    /**
     * serialVersionUID
     */

    private static final long serialVersionUID = 1L;

    private int id;
    
    private String userName;
    
    private String loginId;
    
    private String password;
    
    private UserDetail userDetail;

    public int getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

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

    public String getLoginId() {
        return loginId;
    }

    public void setLoginId(String loginId) {
        this.loginId = loginId;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public UserDetail getUserDetail() {
        return userDetail;
    }

    public void setUserDetail(UserDetail userDetail) {
        this.userDetail = userDetail;
    }
    
}


User hibernate mapping file
User.hbm.xml
程序代码 程序代码
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="zizz.model">
    <class name="User" table="T_USER">
        <id name="id" column="ID">
            <generator class="increment" />
        </id>

        <property name="userName" column="USER_NAME" />
        <property name="loginId" column="LOGINID" />
        <property name="password" column="PASSWORD" />
        
        <one-to-one name="userDetail" class="UserDetail" cascade="all"/>
    </class>
</hibernate-mapping>


UserDetail.java
程序代码 程序代码
package zizz.model;

import java.io.Serializable;

/**
* 该表对应着数据库表T_USERDETAIL
* <a href="http://xialiang19851204.blog.163.com/blog/http://www.suneca.com">ZIZZ</a>
*
* Create-Time:Apr 21, 2008 9:53:54 PM
*/

public class UserDetail implements Serializable {

    /**
     * serialVersionUID
     */

    private static final long serialVersionUID = 1L;
    
    private int id;
    
    private int age;
    
    private String address;
    
    private boolean married;
    
    private String degree;
    
    private User user;

    public User getUser() {
        return user;
    }

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

    public int getId() {
        return id;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

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

    public boolean isMarried() {
        return married;
    }

    public void setMarried(boolean married) {
        this.married = married;
    }

    public String getDegree() {
        return degree;
    }

    public void setDegree(String degree) {
        this.degree = degree;
    }
    
}


UserDetail.hbm.xml
程序代码 程序代码
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="zizz.model">
    <class name="UserDetail" table="T_USER_DETAIL">
        <id name="id" column="ID">
            <generator class="foreign">
             <param name="property">user</param>
            </generator>
        </id>

        <property name="age" column="AGE" />
        <property name="address" column="ADDRESS" />
        <property name="married" column="MARRIED" />
        <property name="degree" column="DEGREE" />
        
        <one-to-one name="user" class="User"/>
    </class>
</hibernate-mapping>


Hibernate.hbm.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">
<hibernate-configuration>

    <session-factory>
        <property name="connection.username">root</property>
        <property name="connection.url">jdbc:mysql://127.0.0.1:3306/suneca</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="connection.password">admin</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        
        <property name="show_sql">true</property>
        
        <mapping resource="zizz/model/User.hbm.xml"/>
        <mapping resource="zizz/model/UserDetail.hbm.xml"/>
    </session-factory>

</hibernate-configuration>


定义UserDAO接口.
程序代码 程序代码
package zizz.dao;

import java.util.List;

import zizz.model.User;

/**
* User DAO接口.
*
* <a href="http://xialiang19851204.blog.163.com/blog/http://www.suneca.com">ZIZZ</a>
*
* Create-Time:Apr 21, 2008 11:48:30 PM
*/

public interface UserDAO {
    
    void createUser(User user);
    
    void updateUser(User user);
    
    void deleteUser(User user);
    
    User findUserById(int id);
    
    List<User> listAllUsers();
}


定义UserDAO实现,实现对User持久对象的持久化.
UserDAOHibernate.java
程序代码 程序代码
package zizz.dao.hibernate;

import java.util.List;

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

import zizz.dao.UserDAO;
import zizz.model.User;
import zizz.utils.HibernateSessionFactory;

/**
*
* <a href="http://xialiang19851204.blog.163.com/blog/http://www.suneca.com">ZIZZ</a>
*
* Create-Time:Apr 21, 2008 11:54:41 PM
*/

public class UserDAOHibernate implements UserDAO{

    public void createUser(User user) {
        Session session = HibernateSessionFactory.getSession();
        Transaction transaction = session.beginTransaction();
        session.save(user);
        transaction.commit();
        session.close();
    }

    public void deleteUser(User user) {
        Session session = HibernateSessionFactory.getSession();
        Transaction transaction = session.beginTransaction();
        session.delete(user);
        transaction.commit();
        session.close();
    }

    public User findUserById(int id) {
        Session session = HibernateSessionFactory.getSession();
        User user = (User)session.load(User.class, id);
        session.close();
        return user;
    }

    public List<User> listAllUsers() {
        Session session = HibernateSessionFactory.getSession();
        List<User> users = session.createCriteria(User.class).list();
        session.close();
        return users;
    }

    public void updateUser(User user) {
        Session session = HibernateSessionFactory.getSession();
        Transaction transaction = session.beginTransaction();
        session.update(user);
        transaction.commit();
        session.close();
    }
    
}


测试类:
OneToOneTest.java



程序代码 程序代码
package zizz.test;

import zizz.dao.UserDAO;
import zizz.dao.hibernate.UserDAOHibernate;
import zizz.model.User;
import zizz.model.UserDetail;

/**
* 一对一的测试代码.
*
* <a href="http://xialiang19851204.blog.163.com/blog/http://www.suneca.com">ZIZZ</a>
*
* Create-Time:Apr 22, 2008 12:00:44 AM
*/

public class OneToOneTest {
    
    public static void main(String[] args){
        OneToOneTest test = new OneToOneTest();
        test.testOneToOneCreate();
    }
    
    public void testOneToOneCreate(){
        //创建一个DAO对象.
        UserDAO dao = new UserDAOHibernate();
        //创建User对象
        User user = new User();
        user.setUserName("达闻西");
        user.setLoginId("dawenxi");
        user.setPassword("admin");
        //创建User详情对象.
        UserDetail detail = new UserDetail();
        detail.setAddress("飞扬电影城");
        detail.setAge(28);
        detail.setDegree("圣斗士");
        detail.setMarried(true);
        //设置User跟UserDetail的关联关系.
        user.setUserDetail(detail);
        detail.setUser(user);
        //创建新用户.
        dao.createUser(user);
    }

}


从控制台我们可以看到:
程序代码 程序代码
Hibernate: insert into T_USER (USER_NAME, LOGINID, PASSWORD, ID) values (?, ?, ?, ?)
Hibernate: insert into T_USER_DETAIL (AGE, ADDRESS, MARRIED, DEGREE, ID) values (?, ?, ?, ?, ?)


我 们在hibernate当中定义了对象与对象之间的关联关系,并且,我们定义了在User对UserDetail之间的级联关系是 cascade="all",那么,当我们创建User对象的同时,系统将会自动帮我们创建用户详情对象,即自动往数据库两张表当中插入相应的数据。
  评论这张
 
阅读(116)| 评论(0)
推荐 转载

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018