---
title: "简单易懂的hibernate例子"
author: "ldb2741"
date: "2009-08-26T19:47:00Z"
tags: []
slug: "hibernate"
draft: false
lastmod: "2009-08-26T19:47:00Z"
id: 580731
url: "https://ldb2741.iteye.com/blog/580731"
---

数据库文件：myproject.sql

/*  
MySQL Data Transfer  
Source Host: localhost  
Source Database: myproject  
Target Host: localhost  
Target Database: myproject  
Date: 2009/8/26 17:23:12  
\*/

SET FOREIGN\_KEY\_CHECKS=0;  
\-- ----------------------------  
\-- Table structure for users  
\-- ----------------------------  
DROP TABLE IF EXISTS \`users\`;  
CREATE TABLE \`users\` (  
\`id\` int(11) NOT NULL AUTO\_INCREMENT,  
\`name\` varchar(255) COLLATE utf8\_unicode\_ci DEFAULT NULL,  
\`password\` varchar(255) COLLATE utf8\_unicode\_ci DEFAULT NULL,  
\`email\` varchar(255) COLLATE utf8\_unicode\_ci DEFAULT NULL,  
PRIMARY KEY (\`id\`)  
) ENGINE=InnoDB AUTO\_INCREMENT=39 DEFAULT CHARSET=utf8 COLLATE=utf8\_unicode\_ci;

\-- ----------------------------  
\-- Records  
\-- ----------------------------  
INSERT INTO \`users\` VALUES ('34', '测试4', '123456', ['ok@ujs.edu.cn'](mailto:'ok@ujs.edu.cn'));  
INSERT INTO \`users\` VALUES ('35', '测试5', '123456', ['ok@ujs.edu.cn'](mailto:'ok@ujs.edu.cn'));  
INSERT INTO \`users\` VALUES ('36', '测试6', '123456', ['ok@ujs.edu.cn'](mailto:'ok@ujs.edu.cn'));  
INSERT INTO \`users\` VALUES ('37', '测试7', '123456', ['ok@ujs.edu.cn'](mailto:'ok@ujs.edu.cn'));  
INSERT INTO \`users\` VALUES ('38', '测试8', '123456', ['ok@ujs.edu.cn'](mailto:'ok@ujs.edu.cn'));

实体类：User.java

package usermap;

public class User {  
private int id;  
private String name;  
private String password;  
private String email;

public String getEmail() {  
return email;  
}

public void setEmail(String email) {  
this.email = email;  
}

public String getName() {  
return name;  
}

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

public String getPassword() {  
return password;  
}

public void setPassword(String password) {  
this.password = password;  
}

public int getId() {  
return id;  
}

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

}

hibernate类：HibernateBase.java

package usermap;

import org.hibernate.\*;  
import org.hibernate.cfg.\*;  
import java.util.\*;  
import java.io.IOException;  
import java.io.PrintWriter;

public abstract class HibernateBase {  
protected SessionFactory sessionFactory;// 会话工厂，用于创建会话  
protected Session session;// hibernate会话  
protected Transaction transaction; // hiberante事务

public HibernateBase() throws HibernateException {  
this.initHibernate();  
}

// 帮助方法  
protected void initHibernate() throws HibernateException {

// 装载配置，构造SessionFactory对象  
sessionFactory = new Configuration().configure().buildSessionFactory();  
}

/\**  
\*开始一个hibernate事务  
\*/  
protected void beginTransaction() throws HibernateException {

session = sessionFactory.openSession();  
transaction = session.beginTransaction();  
}

/\**  
\*结束一个hibernate事务。  
\*/  
protected void endTransaction(boolean commit) throws HibernateException {

if (commit) {  
transaction.commit();  
} else {  
// 如果是只读的操作，不需要commit这个事务。  
transaction.rollback();  
}  
session.close();}  
}

bean类：UserBean.java

package usermap;

import org.hibernate.\*;  
import org.hibernate.cfg.\*;  
import java.util.\*;

/\**  
\* 和course相关的业务逻辑  
\*/  
public class UserBean extends HibernateBase {  
public UserBean() throws HibernateException {  
super();  
}

/\**  
\* 增加一个Course  
\*/  
public void addUser(User user) throws HibernateException {  
beginTransaction();  
session.save(user);  
endTransaction(true);  
}

/\**  
\* 查询系统中所有的Course，返回的是包含有Course持久对象的Iterator。  
\*/  
public Iterator getAllUsers() throws HibernateException {  
String queryString = "from User u order by u desc";  
beginTransaction();  
Query query = session.createQuery(queryString);  
Iterator it = query.iterate();  
return it;  
}

/\**  
\* 删除给定ID的course  
\*/  
public void deleteUser(String id) throws HibernateException {  
beginTransaction();  
User user = (User) session.load(User.class, id);  
session.delete(user);  
endTransaction(true);  
}

/\**  
\* 按course的名字进行模糊查找，返回的是包含有Course持久对象的Iterator。  
\*/  
public Iterator getSomeUser(String name) throws HibernateException {  
String queryString = "select u from User as u where u.name like :name";  
beginTransaction();  
Query query = session.createQuery(queryString);  
query.setString("name", "%" + name + "%");  
Iterator it = query.iterate();  
return it;  
}  
}  
user的映射：User.hbm.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](http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd)"&gt;

&lt;hibernate-mapping&gt;  
&lt;class name="usermap.User" table="users"&gt;  
&lt;id name="id"&gt;  
&lt;generator class="native"/&gt;  
&lt;/id&gt;  
&lt;property name="name"/&gt;  
&lt;property name="password"/&gt;  
&lt;property name="email"/&gt;  
&lt;/class&gt;  
&lt;/hibernate-mapping&gt;

hibernate全局配置：hibernate.cfg.xml

&lt;?xml version="1.0" encoding="utf-8"?&gt;

&lt;!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"[http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd](http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd)"&gt;

&lt;hibernate-configuration&gt;

&lt;session-factory&gt;

&lt;!-- 显示实际操作数据库时的SQL --&gt;

&lt;property name="show\_sql"&gt;false&lt;/property&gt;

&lt;!-- SQL 方言，这边设定的是MySQL --&gt;

&lt;property name="dialect"&gt;org.hibernate.dialect.MySQLDialect&lt;/property&gt;

&lt;!-- JDBC 驱动程序 --&gt;

&lt;property name="connection.driver\_class"&gt;com.mysql.jdbc.Driver&lt;/property&gt;

&lt;!-- JDBC URL　注意这边我设定的所使用的编码 --&gt;

&lt;property name="connection.url"&gt;jdbc:mysql://localhost:3306/myproject&lt;/property&gt;

&lt;!-- 数据库使用者 --&gt;

&lt;property name="connection.username"&gt;root&lt;/property&gt;

&lt;!-- 数据库密码 --&gt;

&lt;property name="connection.password"&gt;123456&lt;/property&gt;

&lt;!-- 以下设置对象与数据库表格映像文件 --&gt;  
&lt;mapping resource="usermap/User.hbm.xml"/&gt;

&lt;/session-factory&gt;

&lt;/hibernate-configuration&gt;

测试网页：index.jsp

&lt;%@ page language="java" contentType="text/html; charset=UTF-8"  
pageEncoding="UTF-8"%&gt;  
&lt;%@ page import="usermap.User"%&gt;  
&lt;%@ page import="usermap.UserBean"%&gt;  
&lt;%@ page import="java.util.\*"%&gt;  
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "[http://www.w3.org/TR/html4/loose.dtd](http://www.w3.org/TR/html4/loose.dtd)"&gt;  
&lt;html&gt;  
&lt;head&gt;  
&lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;  
&lt;title&gt;Insert title here&lt;/title&gt;  
&lt;/head&gt;  
&lt;body&gt;

&lt;%  
UserBean ub=new UserBean();  
Iterator ii=ub.getAllUsers();

int i=0;  
while(ii.hasNext()&&i&lt;3){  
User u=(User)ii.next();  
out.print(u.getId()+u.getName()+"&lt;br&gt;");  
i++;  
}

%&gt;  
&lt;/body&gt;  
&lt;/html&gt;