1. 程式人生 > >搭建Hibernate框架

搭建Hibernate框架

新建 hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<!--資料庫URL -->
		<property name="connection.url"><!--資料庫IP地址記得更改  -->
			jdbc:oracle:thin:@192.168.43.185:1521:orcl
		</property>
		<!--資料庫使用者 -->
		<property name="connection.username">scott</property>
		<!--資料庫使用者密碼 -->
		<property name="connection.password">tigger</property>
		<!--資料庫JDBC驅動 -->
		<property name="connection.driver_class">
			oracle.jdbc.driver.OracleDriver
		</property>
		<!--每個資料庫都有其對應的Dialect以匹配其平臺特性 --><!--  資料庫方言-->
		<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
		<!--指定當前session範圍和上下文 -->
		<property name="current_session_context_class">thread</property>
		<!--是否將執行期生成的SQL輸出到日誌以供除錯 -->
		<property name="show_sql">true</property>
		<!--是否格式化SQL -->
		<property name="format_sql">true</property>
		<mapping resource="com/it/pojo/Dept.hbm.xml"/>
	</session-factory>


</hibernate-configuration>


新建 公共類 hiberbateUtil

public class hiberbateUtil {
   private static Configuration configuration=null;
   private static SessionFactory factory=null;
   
   
   static {
	    //建立配置檔案
	   configuration=  new Configuration().configure();
	 //建立會話工廠
	   factory=configuration.buildSessionFactory();
	 
   }
   
   private hiberbateUtil() {
	
}
   public static Session  getsession() {
	   
	 //建立會話
	  
	return factory.openSession();
   }
}

dao層事例

package com.it.dao;





import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.it.pojo.Dept;
import com.it.util.hiberbateUtil;

public class DeptDao {
	Session session=hiberbateUtil.getsession();
	Transaction tran=null;
	
	/*
	 * 查詢單個
	 */
	public Dept selOne(int deotno) {
		Dept dept =	(Dept) session.get(Dept.class, deotno);
		return dept;
		
	}

	/*
	 * 查詢所有
	 */
	public List<Dept> selAll(){
		Query  query=session.createQuery("from Dept");
		List<Dept> list=query.list();
		return list;
	}
	
	
	/*
	 * 增加
	 */
	
	public void add(Dept dept) {
		try {
			//開啟事務
			 tran=		session.beginTransaction();
			session.save(dept);
			tran.commit();
		} catch (Exception e) {
			tran.rollback();
		}finally {
			if(session!=null) {
				if(session.isOpen()) {
					session.close();
				}
			}
			
		}
	}
	
	/*
	 * 修改
	 */
	
	public void upd(Dept dept) {
		try {
			//開啟事務
			 tran=		session.beginTransaction();
			session.update(dept);
			tran.commit();
		} catch (Exception e) {
			e.printStackTrace();
			tran.rollback();
		}finally {
			session.close();
		}
	}
	
	/*
	 * 刪除
	 */
	
	public void del(Dept dept) {
		try {
			//開啟事務
			 tran=		session.beginTransaction();
			session.delete(dept);
			tran.commit();
		} catch (Exception e) {
			tran.rollback();
		}finally {
			session.close();
		}
	}
	
	
	
}