注意:不同版本好像會有點不一樣,特別是在後續跟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()+"的用戶信息!");
}
}