Hibernate学习之一对一关联

今天练习了一下hibernate的一对一关联(主键关联),其实就是抄了一遍书上的例子。
用的例子是《深入浅出hibernate》的一对一关联例子,中国公民与护照形成的一对一主键关联。
代码如下:

数据库使用的MSSQLServer2000,我已经导出SQL语句如下:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_TPassport_TUser]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
ALTER TABLE [dbo].[TPassport] DROP CONSTRAINT FK_TPassport_TUser
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[TPassport]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[TPassport]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[TUser]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[TUser]
GO

CREATE TABLE [dbo].[TPassport] (
 [id] [int] NOT NULL ,
 [serial] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
 [expiry] [int] NOT NULL
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[TUser] (
 [id] [int] IDENTITY (1, 1) NOT NULL ,
 [name] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
 [age] [int] NOT NULL ,
 [gender] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[TPassport] WITH NOCHECK ADD
 CONSTRAINT [PK_TPassport] PRIMARY KEY  CLUSTERED
 (
  [id]
 )  ON [PRIMARY]
GO

ALTER TABLE [dbo].[TUser] WITH NOCHECK ADD
 CONSTRAINT [PK_TUser] PRIMARY KEY  CLUSTERED
 (
  [id]
 )  ON [PRIMARY]
GO

 CREATE  INDEX [F_TUser] ON [dbo].[TUser]([id]) ON [PRIMARY]
GO

 CREATE  INDEX [FK_TUser] ON [dbo].[TUser]([id]) ON [PRIMARY]
GO

ALTER TABLE [dbo].[TPassport] ADD
 CONSTRAINT [FK_TPassport_TUser] FOREIGN KEY
 (
  [id]
 ) REFERENCES [dbo].[TUser] (
  [id]
 )
GO

复制以上代码到查询分析器,即可生成相应数据库。呵呵

然后就是POJO了,有两个,分别是:
eg.one2one.bean.TPassport;
package eg.one2one.bean;

import java.io.Serializable;

public class TPassport implements Serializable {
 private static final long serialVersionUID = 1L;

 private Integer id;

 private String serial;

 private Integer expiry;

 private TUser user;

/*
 *  省略的getter()和setter()
**/
}

eg.one2one.bean.TUser;

package eg.one2one.bean;

import java.io.Serializable;

public class TUser implements Serializable {

 private static final long serialVersionUID = 1L;

 private Integer id;

 private String name;

 private String gender;

 private Integer age;

 private TPassport passport;

/*
 *  省略的getter()和setter()
**/

}

接下来就应该书写mapping文件了。
TPassport.hbm.xml
<hibernate-mapping>
  <class name="eg.one2one.bean.TPassport" table="TPassport">
    <id name="id" type="java.lang.Integer" column="id">
      <generator class="foreign">
        <param name="property">user</param>
      </generator>
    </id>
    <one-to-one name="user"
                class="eg.one2one.bean.TUser"
                constrained="true"></one-to-one>
    <property name="serial" type="java.lang.String" column="serial"></property>
    <property name="expiry" type="java.lang.Integer" column="expiry"></property>
  </class>
</hibernate-mapping>

TUser.hbm.xml
<hibernate-mapping>
  <class name="eg.one2one.bean.TUser" table="TUser">
    <id name="id" type="java.lang.Integer" column="id">
      <generator class="native">
         <param name="property">passport</param>
      </generator>
    </id>
    <property name="name" type="java.lang.String" column="name"></property>
    <property name="gender" type="java.lang.String" column="gender"></property>
    <property name="age" type="java.lang.Integer" column="age"></property>
    <one-to-one name="passport"
              class="eg.one2one.bean.TPassport"
              cascade="all"
              outer-join="true"></one-to-one>
  </class>
</hibernate-mapping>

哇,已经贴了这么多了,还没完呢。配置文件内容如下:
<session-factory>
 <property name="connection.username">yourusername</property>
 <property name="connection.url">
  jdbc:microsoft:sqlserver://127.0.0.1:1433;dataBaseName=Test
 </property>
 <property name="dialect">
  org.hibernate.dialect.SQLServerDialect
 </property>
 <property name="myeclipse.connection.profile">One2OneTest</property>
 <property name="connection.password">yourpassword</property>
 <property name="connection.driver_class">
  com.microsoft.jdbc.sqlserver.SQLServerDriver
 </property>
 <property name="show_sql">true</property>
 <mapping resource="eg/one2one/bean/TUser.hbm.xml" />
 <mapping resource="eg/one2one/bean/TPassport.hbm.xml" />

</session-factory>

Ok,好了。写了这么多代码,能不能执行,测试一下吧。
package eg.one2one.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
 private static SessionFactory sessionFactory;

 private HibernateUtil() {
 }

 public static SessionFactory getSessionFactory() {
  if (sessionFactory == null) {
   Configuration config = new Configuration();
   config.configure();
   sessionFactory = config.buildSessionFactory();
  }
  return sessionFactory;
 }
}


测试类:
package eg.test;

import java.util.Iterator;
import java.util.List;

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

import eg.one2one.bean.TPassport;
import eg.one2one.bean.TUser;
import eg.one2one.util.HibernateUtil;

public class One2OneTest {
 public static void main(String[] args) {
  SessionFactory sessionFactory =
   HibernateUtil.getSessionFactory();
        Session session = sessionFactory.openSession();
       
       
/*        TUser user = (TUser) session.load(TUser.class, new Integer(1));
       
        Transaction trans = null;
        try{
         trans = session.beginTransaction();
         session.delete(user);
         trans.commit();
        }catch(HibernateException e){
         e.printStackTrace();
         if(trans != null)
          trans.rollback();
        }*/

/*        TUser user = (TUser) session.load(TUser.class, new Integer(2));
       
        user.setName("beauty");
        user.setAge(new Integer(20));
        user.setGender("femal");
       
        user.getPassport().setExpiry(new Integer(100));
        user.getPassport().setSerial("Australian");
       
        Transaction trans = null;
        try{
         trans = session.beginTransaction();
         session.save(user);
         trans.commit();
        }catch(HibernateException e){
         e.printStackTrace();
         if(trans != null)
          trans.rollback();
        }*/
       
       
/*        Query query = session.createQuery("from TUser");       
        List list = query.list();
        Iterator it = list.iterator();
        while(it.hasNext()){
         TUser user = (TUser)it.next();
         System.out.print(user.getId() + "\t");
         System.out.print(user.getName() + "\t");
         System.out.print(user.getGender() + "\t");
         System.out.print(user.getAge() + "\t");
         System.out.print(user.getPassport().getSerial() + "\t");
         System.out.println(user.getPassport().getExpiry());
        }*/
       
       
/*        Query query = session.createQuery("from TPassport");
        List list = query.list();
        Iterator it = list.iterator();
        while(it.hasNext()){
         TPassport passport = (TPassport)it.next();
         System.out.print(passport.getId() + "\t");
         System.out.print(passport.getSerial() + "\t");
         System.out.print(passport.getExpiry() + "\t");
         System.out.print(passport.getUser().getName() + "\t");
         System.out.print(passport.getUser().getGender() + "\t");
         System.out.println(passport.getUser().getAge() + "\t");
           
        }*/
       
/*        TUser user = new TUser();
        user.setName("wangwu");
        user.setAge(new Integer(40));
        user.setGender("male");
       
        TPassport passport = new TPassport();
        passport.setSerial("American");
        passport.setExpiry(new Integer(10));
       
        user.setPassport(passport);
        passport.setUser(user);
       
        Transaction tran = null;
        try{
         tran = session.beginTransaction();         
         session.save(user);         
         tran.commit();
        }catch(HibernateException e){
            e.printStackTrace();
            if(tran != null)
             tran.rollback();
        }*/
 }
}

完成了。

你可能感兴趣的:(Hibernate学习之一对一关联)