eclipse+hibernate 連線Oracle (二)

wangchuanbaodhcc發表於2011-08-16
2.建立People類,該類相當於一個javabean
package com.example.bean;

public class People {
	private int id;
	private String name;
	private String status;
	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 getStatus() {
		return status;
	}
	public void setStatus(String status) {
		this.status = status;
	}
	

}


3.在SRC目錄下建立people.hbm.xml檔案,用於和資料庫中表people對映
<?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"> 
<hibernate-mapping package="com.example.bean">
	<class name="com.example.bean.People" table="people">
		<id name="id">
	    <generator class="assigned"/>
		</id>
		     <property name="name"/>
		     <property name="status"/>
	</class>
</hibernate-mapping>

4.在SRC目錄下建立hibernate.cfg.xml檔案,用於和資料庫的連線
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory>
		<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver
		</property>
		<property name="hibernate.connection.url">jdbc:oracle:thin:@10.10.111.95:1521:orcl</property>
		<property name="hibernate.connection.username">system</property>
		<property name="hibernate.connection.password">java</property>
		<property name="hibernate.connection.pool_size">100</property>
		<property name="show_sql">false</property>
		<property name="dialect">org.hibernate.dialect.OracleDialect</property>	
		<mapping resource="people.hbm.xml"/>
	</session-factory>
</hibernate-configuration>

5.建立幫助類 用來建立、刪除會話,和得到會話 工廠
package com.example.util;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class DbUtil {
	
	
	private static final SessionFactory sessionFactory;
	@SuppressWarnings("unchecked")
	public static final ThreadLocal session=new ThreadLocal();
	static{
	     sessionFactory=new Configuration().configure().buildSessionFactory();
	}
    @SuppressWarnings("unchecked")
	public static Session currentSession() throws HibernateException{
    	Session s=(Session)session.get();
    	if(s==null||!s.isOpen()){
    		s=sessionFactory.openSession();
    		session.set(s);
    	}
    	return s;
    }
    
    public static void closeSession()throws HibernateException{
    	Session s=(Session)session.get();
    	session.set(null);
    	if(s!=null)
    		s.close();
    }
    
    public SessionFactory getSessionFactory(){
    	return sessionFactory;
    }
}






相關文章