hibernate入门使用系列 说明篇+快速构建篇

转载:http://www.iteye.com/topic/189635
说明篇


写这个 入门使用 系列的文章,算是一个简单的复习吧。

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


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


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

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

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

快速构建篇

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

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

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

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



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





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

Java代码
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;
}
}

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代码
use HibernateQuickUse;   
drop table if exists User;

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

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代码
<?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>

<?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代码
<?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 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代码
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();
}

}

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代码
=== 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_

=== 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包是原代码。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值