hibernate入门使用系列 2-- xml关系映射篇(上)

接上篇 hibernate入门使用系列 1-- 说明篇+试用篇

现在起主要讲 hibernate中的关系映射。对应的关系主要有 1:1, n:1, n:n。今天主要写1:1。

关系映射篇(上)—— 之1:1

1对1的关系在现实中很常见。比方说:人和身份证。1个身份证对应着一个身份证,一个身份证对应着一个人。那么,我们就以此为原型。进行代码编写。

建立实体模型如右:

 

根据模型,创建数据库:

use HibernateQuickUse;
drop table if exists Person;
drop table if exists Card;

create table Card (
	id varchar(32) primary key,
	cardDesc varchar(128) not null
);

create table Person (
	id varchar(32) primary key,
	name varchar(32) not null,
	card_id varchar(32) not null,
	foreign key(card_id) references Card(id)
);


 

java代码如下:

Person类

package org.py.hib.relation.one2one;

/**
 * Person entity.
 */

@SuppressWarnings("serial")
public class Person implements java.io.Serializable
{
	private String id;

	private String name;

	private Card card;

	public Person()
	{
	}

	public String getId()
	{
		return this.id;
	}

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

	public Card getCard()
	{
		return this.card;
	}

	public void setCard(Card card)
	{
		this.card = card;
	}

	public String getName()
	{
		return this.name;
	}

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

}

 

Card类:

package org.py.hib.relation.one2one;

/**
 * Card entity.
 */

@SuppressWarnings("serial")
public class Card implements java.io.Serializable
{
	private String id;

	private String cardDesc;

	public Card()
	{
	}

	public String getId()
	{
		return this.id;
	}

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

	public String getCardDesc()
	{
		return cardDesc;
	}

	public void setCardDesc(String cardDesc)
	{
		this.cardDesc = cardDesc;
	}
}

 

xml映射文件如下:

Person.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>
	<class name="org.py.hib.relation.one2one.Person" table="person">
		<id name="id" type="java.lang.String" column="id" length="32">
			<generator class="uuid" />
		</id>

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

		<many-to-one name="card" class="org.py.hib.relation.one2one.Card" unique="true"
			cascade="all" column="card_id" />
			
	</class>
</hibernate-mapping>

今天讲的是one-to-one配置。但是,此处用的是many-to-one,这个是什么原因呢?其实,one-to-one就是特殊的many-to-one。

Card.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">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="org.py.hib.relation.one2one.Card" table="card">
        <id name="id" type="java.lang.String" column="id" length="32">
            <generator class="uuid" />
        </id>
        
        <property name="cardDesc" type="java.lang.String" column="cardDesc" length="128" not-null="true"/>

    </class>
</hibernate-mapping>

 

测试代码如下:

One2OneTest.java

package org.py.hib.relation.one2one;

import junit.framework.Assert;
import junit.framework.TestCase;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.Before;

public class One2OneTest extends TestCase
{
	private SessionFactory factory;

	private String m_name = "ryanpoy";

	private String m_name2 = "ryanpoy2";

	private String m_cardDesc1 = "desc_1";

	private String m_cardDesc2 = "desc_2";

	@Before
	public void setUp() throws Exception
	{
		Configuration conf = new Configuration().configure();
		factory = conf.buildSessionFactory();
	}

	/**
	 * 测试添加
	 * @throws Exception
	 */
	public void testSave() throws Exception
	{
		System.out.println("\n=== test save ===");

		Card card = new Card();
		card.setCardDesc(m_cardDesc1);

		Person person = new Person();
		person.setName(m_name); // 设置用户名 = m_name
		person.setCard(card);

		Session session = null;
		Transaction tran = null;
		try
		{
			session = factory.openSession();
			tran = session.beginTransaction();
			session.save(person);
			
			tran.commit();

			Assert.assertEquals(person.getId() != null, true);
			Assert.assertEquals(card.getId() != null, true);

		} catch (Exception ex)
		{
			tran.rollback();
			throw ex;
		} finally
		{
			if (session != null)
			{
				try
				{
					session.close();
				} catch (Exception ex)
				{
					// nothing to do
				} finally
				{
					if (session != null)
						session = null;
				}
			}
		}
	}

	/**
	 * 测试查询
	 * @throws Exception
	 */
	public void testFind() throws Exception
	{
		System.out.println("\n=== test find ===");
		Session session = null;
		try
		{
			session = factory.openSession();
			Person person = (Person) session.createQuery("from Person").list().get(0);

			Assert.assertEquals(true, person.getId() != null);
			Assert.assertEquals(m_name, person.getName());

			Assert.assertEquals(true, person.getCard().getId() != null);
			Assert.assertEquals(m_cardDesc1, person.getCard().getCardDesc());

		} catch (Exception ex)
		{
			throw ex;
		} finally
		{
			if (session != null)
			{
				try
				{
					session.close();
				} catch (Exception ex)
				{
					// nothing to do
				} finally
				{
					if (session != null)
						session = null;
				}
			}
		}
	}

	/**
	 * 测试修改
	 * @throws Exception
	 */
	public void testModify() throws Exception
	{
		System.out.println("\n=== test modify ===");
		Session session = null;
		Transaction tran = null;
		try
		{
			session = factory.openSession();
			tran = session.beginTransaction();

			Person person = (Person) session.createQuery("from Person").list().get(0);
			person.setName(m_name2); // 修改用户名 = m_name2.(原来用户名= m_name)
			person.getCard().setCardDesc(m_cardDesc2); // 修改cardDesc 为 m_cardDesc2 (原来是:m_cardDesc1)
			tran.commit();

		} catch (Exception ex)
		{
			throw ex;
		} finally
		{
			if (session != null)
			{
				try
				{
					session.close();
				} catch (Exception ex)
				{
					// nothing to do
				} finally
				{
					if (session != null)
						session = null;
				}
			}
		}

		/*
		 * 修改后再查询
		 */
		System.out.println("\n=== test find after modify ===");
		try
		{
			session = factory.openSession();
			Person person = (Person) session.createQuery("from Person").list().get(0);

			Assert.assertEquals(true, person.getId() != null);
			Assert.assertEquals(m_name2, person.getName());

			Assert.assertEquals(true, person.getCard().getId() != null);
			Assert.assertEquals(m_cardDesc2, person.getCard().getCardDesc());

		} catch (Exception ex)
		{
			throw ex;
		} finally
		{
			if (session != null)
			{
				try
				{
					session.close();
				} catch (Exception ex)
				{
					// nothing to do
				} finally
				{
					if (session != null)
						session = null;
				}
			}
		}
	}

	/**
	 * 测试删除
	 * @throws Exception
	 */
	public void testDelete() throws Exception
	{
		System.out.println("\n=== test delete ===");
		Session session = null;
		Transaction tran = null;
		try
		{
			session = factory.openSession();
			tran = session.beginTransaction();

			Person person = (Person) session.createQuery("from Person").list().get(0);
			session.delete(person);
			tran.commit();

		} catch (Exception ex)
		{
			throw ex;
		} finally
		{
			if (session != null)
			{
				try
				{
					session.close();
				} catch (Exception ex)
				{
					// nothing to do
				} finally
				{
					if (session != null)
						session = null;
				}
			}
		}

		/*
		 * 删除后再查询
		 */
		System.out.println("\n=== test find after delete ===");
		try
		{
			session = factory.openSession();

			Integer num = (Integer) session.createQuery("from Person").list().size();
			Assert.assertEquals(0, num.intValue());

			num = (Integer) session.createQuery("from Card").list().size();
			Assert.assertEquals(0, num.intValue());

		} catch (Exception ex)
		{
			throw ex;
		} finally
		{
			if (session != null)
			{
				try
				{
					session.close();
				} catch (Exception ex)
				{
					// nothing to do
				} finally
				{
					if (session != null)
						session = null;
				}
			}
		}
	}

	/**
	 * 
	 */
	@After
	public void tearDown() throws Exception
	{
		factory.close();
	}

}

 

运行test,一路飚绿。呵呵。陶醉一番。不过,这也就是一个拿不出手的测试和一个拿不出手的例子。没有任何实际意义的例子。仅此一个demo而已。

在1:1中,其实还有一种方式,即:唯一主见关联。但是,我一直倾向于上面的这种形式,所以,唯一主见关联的旧部介绍了。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值