hibernate 简单入门[转]

本文档提供了一个Hibernate快速入门指南,介绍了如何使用Hibernate进行数据库操作,包括增删改查等基本功能。通过实例演示了如何配置环境、创建实体类及映射文件,并提供了JUnit测试样例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

说明篇

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

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


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


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

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

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

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

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

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

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



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





根据实体,创建类User,代码如下:
Java代码 复制代码
  1. package org.py.hib.quickstart;   
  2.   
  3. /**  
  4.  * User entity.  
  5.  * @author MyEclipse Persistence Tools  
  6.  */  
  7.   
  8. @SuppressWarnings("serial")   
  9. public class User implements java.io.Serializable   
  10. {   
  11.     private String id;   
  12.     private String name;   
  13.   
  14.     public User()   
  15.     {   
  16.     }   
  17.   
  18.     public String getId()   
  19.     {   
  20.         return this.id;   
  21.     }   
  22.   
  23.     public void setId(String id)   
  24.     {   
  25.         this.id = id;   
  26.     }   
  27.   
  28.     public String getName()   
  29.     {   
  30.         return this.name;   
  31.     }   
  32.   
  33.     public void setName(String name)   
  34.     {   
  35.         this.name = name;   
  36.     }   
  37. }  
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如下:
Sql代码 复制代码
  1. use HibernateQuickUse;   
  2. drop table if exists User;   
  3.   
  4. create table user (   
  5.     id varchar(32) primary key,   
  6.     name varchar(32)   
  7. );  
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代码 复制代码
  1. <?xml version='1.0' encoding='UTF-8'?>  
  2. <!DOCTYPE hibernate-configuration PUBLIC   
  3.           "-//Hibernate/Hibernate Configuration DTD 3.0//EN"   
  4.           "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  5.   
  6. <hibernate-configuration>  
  7.   
  8.     <session-factory>  
  9.         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>  
  10.         <property name="connection.url">jdbc:mysql://localhost:3306/hibernatequickUse</property>  
  11.         <property name="connection.username">root</property>  
  12.         <property name="connection.password">root</property>  
  13.         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>  
  14.            
  15.         <property name="show_sql">true</property>  
  16.         <mapping resource="org/py/hib/quickstart/User.hbm.xml" />  
  17.   
  18.        
  19.     </session-factory>  
  20.   
  21. </hibernate-configuration>  
<?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代码 复制代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"   
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  4.   
  5. <hibernate-mapping>  
  6.     <class name="org.py.hib.quickstart.User" table="user">  
  7.                 <id name="id" type="java.lang.String" column="id" length="32">  
  8.             <generator class="uuid" />  
  9.         </id>  
  10.   
  11.         <property name="name"  type="java.lang.String" column="name" length="32" />  
  12.     </class>  
  13. </hibernate-mapping>  
<?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下面。代码如下:
Java代码 复制代码
  1. package org.py.hib.quickstart;   
  2.   
  3. import junit.framework.Assert;   
  4. import junit.framework.TestCase;   
  5.   
  6. import org.hibernate.Session;   
  7. import org.hibernate.SessionFactory;   
  8. import org.hibernate.Transaction;   
  9. import org.hibernate.cfg.Configuration;   
  10. import org.junit.After;   
  11. import org.junit.Before;   
  12.   
  13. public class QuickStartTest extends TestCase   
  14. {   
  15.     SessionFactory factory;   
  16.   
  17.     String m_name = "ryanpoy";   
  18.   
  19.     String m_name2 = "ryanpoy2";   
  20.   
  21.     @Before  
  22.     public void setUp() throws Exception   
  23.     {   
  24.         Configuration conf = new Configuration().configure();   
  25.         factory = conf.buildSessionFactory();   
  26.     }   
  27.   
  28.     /**  
  29.      * 测试添加  
  30.      * @throws Exception  
  31.      */  
  32.     public void testSave() throws Exception   
  33.     {   
  34.         System.out.println("\n=== test save ===");   
  35.         User u = new User();   
  36.         u.setName(m_name); // 设置用户名 = m_name   
  37.   
  38.         Session session = null;   
  39.         Transaction tran = null;   
  40.         try  
  41.         {   
  42.             session = factory.openSession();   
  43.             tran = session.beginTransaction();   
  44.             session.save(u);   
  45.             tran.commit();   
  46.   
  47.             Assert.assertEquals(u.getId() != nulltrue);   
  48.         } catch (Exception ex)   
  49.         {   
  50.             tran.rollback();   
  51.             throw ex;   
  52.         } finally  
  53.         {   
  54.             if (session != null)   
  55.             {   
  56.                 try  
  57.                 {   
  58.                     session.close();   
  59.                 } catch (Exception ex)   
  60.                 {   
  61.                     // nothing to do   
  62.                 } finally  
  63.                 {   
  64.                     if (session != null)   
  65.                         session = null;   
  66.                 }   
  67.             }   
  68.         }   
  69.     }   
  70.   
  71.     /**  
  72.      * 测试查询  
  73.      * @throws Exception  
  74.      */  
  75.     public void testFind() throws Exception   
  76.     {   
  77.         System.out.println("\n=== test find ===");   
  78.         Session session = null;   
  79.         try  
  80.         {   
  81.             session = factory.openSession();   
  82.             User u = (User) session.createQuery("from User").list().get(0);   
  83.   
  84.             Assert.assertEquals(true, u.getId() != null);   
  85.             Assert.assertEquals(m_name, u.getName());   
  86.         } catch (Exception ex)   
  87.         {   
  88.             throw ex;   
  89.         } finally  
  90.         {   
  91.             if (session != null)   
  92.             {   
  93.                 try  
  94.                 {   
  95.                     session.close();   
  96.                 } catch (Exception ex)   
  97.                 {   
  98.                     // nothing to do   
  99.                 } finally  
  100.                 {   
  101.                     if (session != null)   
  102.                         session = null;   
  103.                 }   
  104.             }   
  105.         }   
  106.     }   
  107.   
  108.     /**  
  109.      * 测试修改  
  110.      * @throws Exception  
  111.      */  
  112.     public void testModify() throws Exception   
  113.     {   
  114.         System.out.println("\n=== test modify ===");   
  115.         Session session = null;   
  116.         Transaction tran = null;   
  117.         try  
  118.         {   
  119.             session = factory.openSession();   
  120.             tran = session.beginTransaction();   
  121.   
  122.             User u = (User) session.createQuery("from User").list().get(0);   
  123.             u.setName(m_name2);  // 修改用户名 = m_name2.(原来用户名= m_name)   
  124.             tran.commit();   
  125.   
  126.         } catch (Exception ex)   
  127.         {   
  128.             throw ex;   
  129.         } finally  
  130.         {   
  131.             if (session != null)   
  132.             {   
  133.                 try  
  134.                 {   
  135.                     session.close();   
  136.                 } catch (Exception ex)   
  137.                 {   
  138.                     // nothing to do   
  139.                 } finally  
  140.                 {   
  141.                     if (session != null)   
  142.                         session = null;   
  143.                 }   
  144.             }   
  145.         }   
  146.   
  147.         /*  
  148.          * 修改后再查询  
  149.          */  
  150.         System.out.println("\n=== test find after modify ===");   
  151.         try  
  152.         {   
  153.             session = factory.openSession();   
  154.             User u = (User) session.createQuery("from User").list().get(0);   
  155.   
  156.             Assert.assertEquals(true, u.getId() != null);   
  157.             Assert.assertEquals(m_name2, u.getName());   
  158.         } catch (Exception ex)   
  159.         {   
  160.             throw ex;   
  161.         } finally  
  162.         {   
  163.             if (session != null)   
  164.             {   
  165.                 try  
  166.                 {   
  167.                     session.close();   
  168.                 } catch (Exception ex)   
  169.                 {   
  170.                     // nothing to do   
  171.                 } finally  
  172.                 {   
  173.                     if (session != null)   
  174.                         session = null;   
  175.                 }   
  176.             }   
  177.         }   
  178.     }   
  179.   
  180.     /**  
  181.      * 测试删除  
  182.      * @throws Exception  
  183.      */  
  184.     public void testDelete() throws Exception   
  185.     {   
  186.         System.out.println("\n=== test delete ===");   
  187.         Session session = null;   
  188.         Transaction tran = null;   
  189.         try  
  190.         {   
  191.             session = factory.openSession();   
  192.             tran = session.beginTransaction();   
  193.   
  194.             User u = (User) session.createQuery("from User").list().get(0);   
  195.             session.delete(u);   
  196.             tran.commit();   
  197.   
  198.         } catch (Exception ex)   
  199.         {   
  200.             throw ex;   
  201.         } finally  
  202.         {   
  203.             if (session != null)   
  204.             {   
  205.                 try  
  206.                 {   
  207.                     session.close();   
  208.                 } catch (Exception ex)   
  209.                 {   
  210.                     // nothing to do   
  211.                 } finally  
  212.                 {   
  213.                     if (session != null)   
  214.                         session = null;   
  215.                 }   
  216.             }   
  217.         }   
  218.   
  219.         /*  
  220.          * 删除后再查询  
  221.          */  
  222.         System.out.println("\n=== test find after delete ===");   
  223.         try  
  224.         {   
  225.             session = factory.openSession();   
  226.             Integer num = (Integer) session.createQuery("from User").list().size();   
  227.   
  228.             Assert.assertEquals(0, num.intValue());   
  229.         } catch (Exception ex)   
  230.         {   
  231.             throw ex;   
  232.         } finally  
  233.         {   
  234.             if (session != null)   
  235.             {   
  236.                 try  
  237.                 {   
  238.                     session.close();   
  239.                 } catch (Exception ex)   
  240.                 {   
  241.                     // nothing to do   
  242.                 } finally  
  243.                 {   
  244.                     if (session != null)   
  245.                         session = null;   
  246.                 }   
  247.             }   
  248.         }   
  249.     }   
  250.   
  251.     /**  
  252.      *   
  253.      */  
  254.     @After  
  255.     public void tearDown() throws Exception   
  256.     {   
  257.         factory.close();   
  258.     }   
  259.   
  260. }  
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();
	}

}
运行后,我们很欣慰的看到一路绿灯,全部通过了。那么测试没有问题。呵呵(这里的测试可能还不完善。请大家指出。前面说过,我对测试这块也不熟)。
看控制台,会输出如下信息:
Sql代码 复制代码
  1. === test save ===   
  2. Hibernate: insert into hibernatequickuse.user (name, id) values (?, ?)   
  3.   
  4. === test find ===   
  5. Hibernate: select user0_.id as id2_, user0_.name as name2_ from hibernatequickuse.user user0_   
  6.   
  7. === test modify ===   
  8. Hibernate: select user0_.id as id4_, user0_.name as name4_ from hibernatequickuse.user user0_   
  9. Hibernate: update hibernatequickuse.user set name=? where id=?   
  10.   
  11. === test find after modify ===   
  12. Hibernate: select user0_.id as id4_, user0_.name as name4_ from hibernatequickuse.user user0_   
  13.   
  14. === test delete ===   
  15. Hibernate: select user0_.id as id6_, user0_.name as name6_ 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值