`
RyanPoy
  • 浏览: 50467 次
  • 性别: Icon_minigender_1
  • 来自: 长沙
社区版块
存档分类
最新评论

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

阅读更多
说明篇


写这个 入门使用 系列的文章, 学习笔记。

目的1是让没有用过hibernate的工作者们,快速的使用起来。不会介绍太多的深层次的东西。仅仅是一个入门使用而已。


目的2是总结一下hibernate的基本使用,顺便自己再熟悉熟悉。


目的3是交流心得。一个人掌握的东西只有一点点。且掌握的程度有深有浅,如不交流、固步自封,只有被淘汰。欢迎任何人拍砖的。群众的力量是无穷的。在此系列中,难免会有些不恰当或者不对的地方。尽请指出、批评。

对于认为已经熟练掌握hibernate的高手们,可能没有什么用处。但是,无限欢迎交流。

废话不多说,下面开始进入主题。


试用篇

一. 何谓hibernate?
     答:you can find the answer @google ...

二. 快速构建。
     在此先要说明一下。由于本人懒惰,记不住hibernate的配置选项,所以,此系列的实例都是使用myeclipse进行快速开发。各位对myeclipse不齿的,就请见谅。然后,数据库都是mysql。

下面开始利用hibernate进行数据库的访问。

需求:实现对用户的增、删、改、查。为了方便,用户就2个属性 用户ID和用户名。实体模型如下:



建立工程:HibernateQuickUse,并且建立包。如下:





根据实体,创建类User,代码如下:

package org.py.hib.quickstart;

/**
 * User entity.
 * @author MyEclipse Persistence Tools
 */

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

	public User()
	{
	}

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

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

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

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

 

根据实体,创建数据表。sql如下:

use HibernateQuickUse;
drop table if exists User;

create table user (
	id varchar(32) primary key,
	name varchar(32)
);

这里的id,我没有采用Integer auto_increment, 原因是为了数据库的数据能方便的导入到另外一种数据库里面,比方说:oracle。当然,这个是以牺牲部分效率为前提的。因为id是integer的,能更加快速查询。不过,从数据库会自动为 primary key 建立 index来看,效率也不会相差太多。

要想通过hibernate访问数据库。首先要建立描述数据库的文件:hibernate.cfg.xml。放到src下面。内容如下:

<?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="dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="connection.url">jdbc:mysql://localhost:3306/hibernatequickUse</property>
		<property name="connection.username">root</property>
		<property name="connection.password">root</property>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		
		<property name="show_sql">true</property>
		<mapping resource="org/py/hib/quickstart/User.hbm.xml" />

	
	</session-factory>

</hibernate-configuration>

 说说上面的 "dialect", 这个对应着hibernate生成哪种数据库的sql。

 然后是:"show_sql", 这个是为了调试时候输出sql语句到屏幕用的。

注意"mapping resource"部分。这个部分表示你的 实体- 数据库 映射文件的位置。(什么是实体-数据库 映射文件,看下面。)

 

实体-数据库映射文件 -- 主要是告诉hibernate,这个User类,对应着哪个table,User类里面的那个属性对应着table里面的哪个字段。

我们可以建立 实体-数据库 的xml映射文件,也可以采用Annotations映射,但是目前只说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.quickstart.User" table="user">
                <id name="id" type="java.lang.String" column="id" length="32">
			<generator class="uuid" />
		</id>

		<property name="name"  type="java.lang.String" column="name"	length="32" />
	</class>
</hibernate-mapping>

 上面的xml还是很好理解的。注意一个generator中的class,他可以有很多。我们这用的是uuid。什么是uuid。这个可以google一下。呵呵。google是最好的教科书。还能有很多其他的,比方说:native。具体的同样请教google。

 有了上面的准备,那么我们开始来测试一下。这里我们用junit。具体怎么使用junit,呵呵。答案我想大家都知道了,也不用我说了。其实我对test 和 使用它也不熟练。

我把测试用力放到了test/org.py.hib.quickstart下面。代码如下:

package org.py.hib.quickstart;

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 QuickStartTest extends TestCase
{
	SessionFactory factory;

	String m_name = "ryanpoy";

	String m_name2 = "ryanpoy2";

	@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 ===");
		User u = new User();
		u.setName(m_name); // 设置用户名 = m_name

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

			Assert.assertEquals(u.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();
			User u = (User) session.createQuery("from User").list().get(0);

			Assert.assertEquals(true, u.getId() != null);
			Assert.assertEquals(m_name, u.getName());
		} 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();

			User u = (User) session.createQuery("from User").list().get(0);
			u.setName(m_name2);  // 修改用户名 = m_name2.(原来用户名= m_name)
			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();
			User u = (User) session.createQuery("from User").list().get(0);

			Assert.assertEquals(true, u.getId() != null);
			Assert.assertEquals(m_name2, u.getName());
		} 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();

			User u = (User) session.createQuery("from User").list().get(0);
			session.delete(u);
			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 User").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 save ===
Hibernate: insert into hibernatequickuse.user (name, id) values (?, ?)

=== test find ===
Hibernate: select user0_.id as id2_, user0_.name as name2_ from hibernatequickuse.user user0_

=== test modify ===
Hibernate: select user0_.id as id4_, user0_.name as name4_ from hibernatequickuse.user user0_
Hibernate: update hibernatequickuse.user set name=? where id=?

=== test find after modify ===
Hibernate: select user0_.id as id4_, user0_.name as name4_ from hibernatequickuse.user user0_

=== test delete ===
Hibernate: select user0_.id as id6_, user0_.name as name6_ from hibernatequickuse.user user0_
Hibernate: delete from hibernatequickuse.user where id=?

=== test find after delete ===
Hibernate: select user0_.id as id6_, user0_.name as name6_ from hibernatequickuse.user user0_
 

这些,就是hibernte自动生成的。仔细看看,其实就是标准sql。呵呵。懂jdbc的都能看懂。

好了,第一部分就到这。附件中的zip包是原代码。

    语言的组织,举例的细节似乎像记流水账,看来还是没有文学细胞啊。忘了上次是哪位了,他写的标题就像是看 《圣斗士星矢》一项,激情洋溢啊。

  • 大小: 1.6 KB
  • 大小: 4.3 KB
分享到:
评论
32 楼 seman18 2009-01-15  
assertTrue("check",a==b);
assertEquals("check",a,b);
第二种是best practice,这样能看到expected value 和actual value
31 楼 llyzq 2008-12-30  
LZ写的帖子不错,不过好像还是有很多哥们在运行LZ的例子的时候碰到了不少问题

我最近在看尚学堂的hibernate视频,推荐感兴趣的朋友看看

下载地址
http://www.verycd.com/topics/93279/
30 楼 danni505 2008-12-23  
<div class='quote_title'>timer1983 写道</div><div class='quote_div'><div class='quote_title'>RyanPoy 写道</div>
<div class='quote_div'>
<pre name='code' class='xml'>&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"&gt;

&lt;hibernate-mapping&gt;
&lt;class name="org.py.hib.quickstart.User" table="user"&gt;
                &lt;id name="id" type="java.lang.String" column="id" length="32"&gt;
&lt;generator class="uuid" /&gt;
&lt;/id&gt;

&lt;property name="name"  type="java.lang.String" column="name" length="32" /&gt;
&lt;/class&gt;
&lt;/hibernate-mapping&gt;

</pre>
<p> </p>
</div>
<p>唉,折腾了半天,原来就这里不行</p>
<pre name='code' class='xml'>&lt;class name="org.py.hib.quickstart.User" table="user" catalog="hibernatequickuse"&gt;

把这里 catalog="test"改成我的数据库名字就好了,或者把这个属性直接去掉也行,看来还是基础太差</pre></div><br/>

买本书看看就知道了!
29 楼 yuxin_85 2008-12-22  
LZ你好!
“运行后,我们很欣慰的看到一路绿灯”
我创建的是WEB Project,按照你的写了以后怎么不能运行?
我可以怎么测试呢?

谢谢
28 楼 caiceclb 2008-12-03  
不知道lz用的是3.*版本,我用3.2版,如果hibernate.cfg.xml中缺了:


        <property name="current_session_context_class">thread</property>

这么一条配置则出错,你的不会吗?
27 楼 daweiangel 2008-11-21  
支持
我还再入门那
26 楼 niitstar 2008-11-21  
感谢lz,看了你的介绍,算是对hibernate有一些了解了
25 楼 lkjust08 2008-08-28  
不错写真很好。
24 楼 zhazha1984 2008-08-21  
先留名,以后再研究,睡觉先~~哈哈~
23 楼 woshidahuang 2008-07-20  
楼主写的不错 
22 楼 yyyywmscm 2008-06-30  
以上原因找到了
是hibernate.cfg.xml中的数据库名和我的数据库名不匹配;字段类型不对应导致的
以上只想告知刚学hibernate的同志不要犯我犯的错误!呵呵!
21 楼 yyyywmscm 2008-06-30  
一运行 测试类QuickStartTest中方法testSave()中的tran = session.beginTransaction();时就抛异常
得到的tran是null
是为什么啊?
20 楼 wf_chn 2008-06-18  
写得很好
谢谢
19 楼 timer1983 2008-06-17  
<div class='quote_title'>RyanPoy 写道</div>
<div class='quote_div'>
<pre name='code' class='xml'>&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"&gt;

&lt;hibernate-mapping&gt;
&lt;class name="org.py.hib.quickstart.User" table="user"&gt;
                &lt;id name="id" type="java.lang.String" column="id" length="32"&gt;
&lt;generator class="uuid" /&gt;
&lt;/id&gt;

&lt;property name="name"  type="java.lang.String" column="name" length="32" /&gt;
&lt;/class&gt;
&lt;/hibernate-mapping&gt;

</pre>
<p> </p>
</div>
<p>唉,折腾了半天,原来就这里不行</p>
<pre name='code' class='xml'>&lt;class name="org.py.hib.quickstart.User" table="user" catalog="hibernatequickuse"&gt;

把这里 catalog="test"改成我的数据库名字就好了,或者把这个属性直接去掉也行,看来还是基础太差</pre>
18 楼 RyanPoy 2008-06-17  
godomoneyeye 写道
我用myeclipse5.5运行你的例子
one2one的时候,老报junit找不到,可我已经吧junit4放进目录了呀
那位碰到过同样的问题的兄弟
体系一下呀


godomoneyeye 写道
你的junit case从那弄过来的,还是import org.junit.After;
import org.junit.Before;包
编码也硬的很,死活改不过来


需要加入目录。还需要把jar文件add build path。具体的操作,右键点击你的jar包。然后选在add build path
17 楼 RyanPoy 2008-06-17  
james0438 写道
小弟没用过多少junit,觉得我们要测试的是自己写的方法,但感觉楼主测的似乎是hibernate的操作

我理解的"自己的方法"。就是业务逻辑。
在这个测试里面,我的业务就是实现增删改查。所以,是没有问题的。
16 楼 james0438 2008-06-03  
小弟没用过多少junit,觉得我们要测试的是自己写的方法,但感觉楼主测的似乎是hibernate的操作
15 楼 godomoneyeye 2008-05-28  
扯淡
狗屁例子,全是错,SB
14 楼 godomoneyeye 2008-05-28  
你的junit case从那弄过来的,还是import org.junit.After;
import org.junit.Before;包
编码也硬的很,死活改不过来
13 楼 godomoneyeye 2008-05-28  
我用myeclipse5.5运行你的例子
one2one的时候,老报junit找不到,可我已经吧junit4放进目录了呀
那位碰到过同样的问题的兄弟
体系一下呀

相关推荐

Global site tag (gtag.js) - Google Analytics