目录
参考:https://blog.csdn.net/fxdaniel/article/details/42420779
工程轮廓
文件轮廓
数据库 mysql
数据库 mysqldb
数据库表 user
hibernate.cfg.xml
User.hbm.xml
数据库操作方法类
UserDAO.java
UserDAOImpl.java
数据库表的映射关系体现
User.java 类成员与数据库表中的字段相对应。
JUnit测试--调用编写好的方法
UserTest.java
数据库准备
mysql
create database mysqldb;
create table user(
user_id int(11) primary key auto_increment,
name varchar(20),
password varchar(12),
type varchar(6));
如果没有设置 auto_increment, java测试类运行会有错误如下:
The database returned no natively generated identity value。
工程准备
使用MyEclipse创建Java Web Project:
添加 Hibernate相关的包(.jar)
mysql连接相关包
mysql-connector-java-5.1.39-bin.jar
Hibernate相关包
antlr-2.7.7.jar
dom4j-1.6.1.jar
hibernate3.jar
hibernate-commons-annotations-4.0.5.Final.jar
hibernate-core-4.3.6.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
jandex-1.1.0.Final.jar
javassist-3.18.1-GA.jar
jboss-logging-3.1.3.GA.jar
jboss-logging-annotations-1.2.0.Beta1.jar
jboss-transaction-api_1.2_spec-1.0.0.Final.jar
slf4j-api-1.6.1.jar
slf4j-nop-1.6.1.jar
hibernate.cfg.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>
<!-- 数据库的JDBC驱动 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 数据库的URL -->
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/mysqldb</property>
<!-- 数据库的用户名和密码 -->
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<!-- 数据库的方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Hibernate自动根据映射文件创建或者更新数据表 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 在控制台输出运行时生成的SQL语句,方便调试 -->
<property name="show_sql">true</property>
<!-- 连接池大小 -->
<property name="connection.pool_size">1</property>
<!-- 列出所有映射文件 -->
<mapping resource="org/hibernate/entity/User.hbm.xml" />
</session-factory>
</hibernate-configuration>
org.hibernate.dao包
UserDAO
package org.hibernate.dao;
import org.hibernate.entity.User;
public interface UserDAO {
void save(User user);
User findById(int id);
void delete(User user);
void update(User user);
}
UserDAOImpl
package org.hibernate.dao;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.entity.HibernateUtil;
import org.hibernate.entity.User;
public class UserDAOImpl implements UserDAO {
// 添加用户
public void save(User user) {
// TODO Auto-generated method stub
// 创建Session实例
Session session = HibernateUtil.getsSession();
// 创建Transaction实例
Transaction tx = session.beginTransaction();
try {
// 使用Session的save方法将持久化对象保存到数据库
session.save(user);
// 提交事务
tx.commit();
} catch (Exception e) {
e.printStackTrace();
// 出现异常,回滚事务
tx.rollback();
} finally {
// 关闭Session连接
HibernateUtil.closeSession();
}
}
// 根据id查找用户
public User findById(int id) {
// TODO Auto-generated method stub
User user = null;
Session session = HibernateUtil.getsSession();
Transaction tx = session.beginTransaction();
try {
// 使用session的get方法获取指定id的用户
user = (User) session.get(User.class, id);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
tx.rollback();
} finally {
HibernateUtil.closeSession();
}
return user;
}
// 删除用户
public void delete(User user) {
// TODO Auto-generated method stub
Session session = HibernateUtil.getsSession();
Transaction tx = session.beginTransaction();
try {
// 使用session的delete方法将持久化对象删除
session.delete(user);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
tx.rollback();
} finally {
HibernateUtil.closeSession();
}
}
// 修改用户信息
public void update(User user) {
Session session = HibernateUtil.getsSession();
Transaction tx = session.beginTransaction();
try {
// 使用session的update方法更新持久化对象
session.update(user);
tx.commit();
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
} finally {
HibernateUtil.closeSession();
}
}
}
org.hibernate.entity包
HibernateUtil
package org.hibernate.entity;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static SessionFactory sessionFactory;
// 创建线程局部变量threadLocal,用来保存Hibernate的Session
private static final ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();
// 使用静态代码块初始化Hibernate
static
{
try
{
// 读取配置文件
Configuration cfg=new Configuration().configure();
// 创建SessionFactory
sessionFactory=cfg.buildSessionFactory();
}catch(Throwable ex)
{
throw new ExceptionInInitializerError(ex);
}
}
// 获得SessionFactory的实例
public static SessionFactory getsSessionFactory()
{
return sessionFactory;
}
// 获得ThreadLocal对象管理的Session
public static Session getsSession() throws HibernateException
{
Session session=(Session) threadLocal.get();
if(session==null||!session.isOpen())
{
if(sessionFactory==null)
{
rebuildSessionFactory();
}
// 通过SessionFactory对象创建Session对象
session=(sessionFactory!=null)?sessionFactory.openSession():null;
// 将Session对象保存到线程局部变量threadLocal中
threadLocal.set(session);
}
return session;
}
// 关闭Session实例
public static void closeSession()
{
// 从线程局部变量threadLocal中获取之前存入的Session实例
Session session=(Session)threadLocal.get();
threadLocal.set(null);
if(session!=null)
{
session.close();
}
}
// 重建SessionFactory
public static void rebuildSessionFactory()
{
Configuration configuration=new Configuration();
configuration.configure("/hibernate.cfg.xml");
sessionFactory=configuration.buildSessionFactory();
}
// 关闭缓存和连接池
public static void shutdown()
{
getsSessionFactory().close();
}
}
User
package org.hibernate.entity;
public class User {
// mysql database table field
private int id;
private String name;
private String password;
private String type;
public User(){
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
User.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2014-12-28 22:18:36 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<!-- name 持久化类的类名,table 数据表的表名,MySQL不区分大小写 -->
<class name="org.hibernate.entity.User" table="USER">
<!-- 将User类中的id属性映射为数据表USER中的主键列user_id -->
<id name="id" type="int">
<column name="USER_ID" />
<generator class="native" />
</id>
<!-- 映射User类的name属性 -->
<property name="name" type="java.lang.String">
<column name="NAME" length="20"/>
</property>
<!-- 映射User类的password属性 -->
<property name="password" type="java.lang.String">
<column name="PASSWORD" length="12"/>
</property>
<!-- 映射User类的type属性 -->
<property name="type" type="java.lang.String">
<column name="TYPE" length="6"/>
</property>
</class>
</hibernate-mapping>
org.hibernate.test包
UserTest
package org.hibernate.test;
import org.hibernate.dao.UserDAO;
import org.hibernate.dao.UserDAOImpl;
import org.hibernate.entity.User;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
public class UserTest {
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
// @Test 注释表名是一个测试方法
@Test
public void testSave() {
UserDAO userDAO=new UserDAOImpl();
try{
User u=new User();
// 设置User对象的各个属性
u.setId(20);
u.setName("zhangsan");
u.setPassword("123456");
u.setType("admin");
// 使用UserDAOImpl的save方法将User对象存入到数据库
userDAO.save(u);
}catch(Exception e){
e.printStackTrace();
}
}
}