注意:不同版本好像会有点不一样,特别是在后续跟spring整合时要注意版本问题。这里用的是Hibernate 3 版本的。。。
===========
结构:
=================
1.SQL脚本
//SQL脚本
CREATE TABLE USER (
USER_ID INT PRIMARY KEY AUTO_INCREMENT
NAME VARCHAR(20),
PASSWORD VARCHAR(12),
TYPE VARCHAR(6)
)
2. pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.lin</groupId>
<artifactId>HibernateFirstDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.10.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.6.10.Final</version>
</dependency>
<!-- MySQL驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.41</version>
</dependency>
<!-- slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>1.7.25</version>
<scope>test</scope>
</dependency>
<!-- jstl、servlet-api、junit -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit-dep</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
3.持久化类User.java 。(持久化类是应用程序中的业务实体类,这里的持久化指的是类的对象能够被持久化,而不是指这些对象处于持久状态。持久化类的对象会被持久化(保存)到数据库中。)
package com.lin.pojo;
import java.io.Serializable;
public class User implements Serializable{
private static final long serialVersionUID = 1L;
private int id;
private String name;
private String password;
private String type;
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", password=" + password + ", type=" + type + "]";
}
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;
}
public User(int id, String name, String password, String type) {
super();
this.id = id;
this.name = name;
this.password = password;
this.type = type;
}
public User() {
super();
}
}
4.表跟实体类的映射User.hbm.xml
(为了完成对象到关系数据库的映射,Hibernate需要知道持久化类的实例应该被如何存储和加载,可以使用xml文件来设置他们之间的映射关系。在以下文件中定义了User类的属性如何映射到User表的列上)
<?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">
<!--
1.通过映射文件可以告诉Hibernate,User类被持久化为数据库中的User表。
2.根据映射文件,Hibernate可以生成足够的信息以产生所有的SQL语句,即User类的实例进行增删改查所需的SQL语句。
-->
<hibernate-mapping>
<!-- name指定持久化类的类名,table指定数据表的表名 -->
<class name="com.lin.pojo.User" table="USER">
<!-- 将User类中的id映射为数据表USER中的主键USER_ID -->
<id name="id" type="java.lang.Integer" column="user_id">
<!-- 指定主键的生成方式 -->
<generator class="increment"/>
</id>
<!-- 映射User类的其他普通属性 -->
<property name="name" type="java.lang.String" column="name" length="20"></property>
<property name="password" type="java.lang.String" column="password" length="12"></property>
<property name="type" type="java.lang.String" column="type" length="6"></property>
</class>
</hibernate-mapping>
5.Hibernate配置文件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配置文件主要用来配置数据库连接以及Hibernate运行时所需的各个属性的值
-->
<hibernate-configuration>
<session-factory>
<!-- 数据库连接设置 -->
<!-- 配置数据库JDBC驱动 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 配置数据库连接URL -->
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<!-- 配置数据库用户名 -->
<property name="hibernate.connection.username">root</property>
<!-- 配置数据库密码 -->
<property name="hibernate.connection.password">root</property>
<!-- 配置JDBC内置连接池 -->
<property name="connection.pool_size">1</property>
<!-- 配置数据库方言 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 输出运行时生成的SQL语句 -->
<property name="show_sql">true</property>
<!-- 列出所有的映射文件 -->
<mapping resource="hibernate/mappings/User.hbm.xml" />
</session-factory>
</hibernate-configuration>
6.Hibernate的辅助工具类HibernateUtil.java
package com.lin.utils;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static Configuration configuration;
//创建线程局部变量threadLocal,用来保存Hibernate的Session
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
//使用静态代码块初始化Hibernate
static{
try{
//如果不指定hibernate的配置文件位置,那么它会默认到classpath路径下查找名为hibernate.cfg.xml的文件
Configuration cfg = new Configuration().configure("/hibernate/hibernate.cfg.xml");
//创建SessionFactory
sessionFactory = cfg.buildSessionFactory();
}catch(Throwable ex){
throw new ExceptionInInitializerError(ex);
}
}
//获得SessionFactory
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
//获得ThreadLocal对象管理的Session实例
public static Session getSession() 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() throws HibernateException {
//从线程局部变量threadLocal中获取之前存入的Session实例
Session session = (Session)threadLocal.get();
threadLocal.set(null);
if(session != null){
session.close();
}
}
//重建SessionFactory
public static void rebuildSessionFactory() {
try{
configuration.configure("/hibernate/hibernate.cfg.xml");
sessionFactory = configuration.buildSessionFactory();
}catch(Exception e){
System.out.println("Error Creating SessionFactory ");
e.printStackTrace();
}
}
//关闭缓存和连接池
public static void shutdown(){
getSessionFactory().close();
}
}
7.Dao接口UserDao.java
package com.lin.dao;
import com.lin.pojo.User;
public interface UserDao {
void save(User user);
User findById(int id);
void delete(User user);
void update(User user);
}
8.Dao接口实现类UserDaoImpl.java
package com.lin.dao.impl;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.lin.dao.UserDao;
import com.lin.pojo.User;
import com.lin.utils.HibernateUtil;
public class UserDaoImpl implements UserDao {
// 添加用户
public void save(User user) {
// 生成Session实例
Session session = HibernateUtil.getSession();
// 创建Transaction实例
Transaction tx = session.beginTransaction();
try {
session.save(user);
tx.commit();// 提交事务
} catch (Exception e) {
e.printStackTrace();
tx.rollback();// 回滚事务
} finally {
HibernateUtil.closeSession();
}
}
// 按id查找用户
public User findById(int id) {
User user = null;
// 生成Session实例
Session session = HibernateUtil.getSession();
// 创建Transaction实例
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) {
// 生成Session实例
Session session = HibernateUtil.getSession();
// 创建Transaction实例
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 session = HibernateUtil.getSession();
// 创建Transaction实例
Transaction tx = session.beginTransaction();
try {
// 使用Session的update方法更新持久化对象
session.update(user);
tx.commit();// 提交事务
} catch (Exception e) {
e.printStackTrace();
tx.rollback();// 回滚事务
} finally {
HibernateUtil.closeSession();
}
}
}
9.测试类UserTest.java(增删改查操作)
package com.lin.test;
import org.junit.Test;
import com.lin.dao.UserDao;
import com.lin.dao.impl.UserDaoImpl;
import com.lin.pojo.User;
public class UserTest {
//添加
@Test
public void testSave(){
UserDao userDao = new UserDaoImpl();
try{
User u = new User();
u.setId(10);
u.setName("linlin123");
u.setPassword("123");
u.setType("user");
userDao.save(u);
}catch(Exception e){
e.printStackTrace();
}
}
//删除
@Test
public void testDelete(){
UserDao userDao = new UserDaoImpl();
//根据id查询用户
User u = userDao.findById(3);
System.out.println(u);
//删除
userDao.delete(u);
System.out.println("成功删除了id为"+u.getId()+"的用户!");
}
//修改
@Test
public void testUpdate(){
UserDao userDao = new UserDaoImpl();
//根据id查询用户
User u = userDao.findById(2);
System.out.println(u);
u.setName("杨");
u.setType("admin");
System.out.println(u);
//修改
userDao.update(u);
System.out.println("成功修改了id为"+u.getId()+"的用户信息!");
}
}