1. 程式人生 > >第一個Hibernate示例,使用Maven來管理jar包

第一個Hibernate示例,使用Maven來管理jar包

注意:不同版本好像會有點不一樣,特別是在後續跟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

<?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">546784</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()+"的使用者資訊!");
	}
}