eclipse+hibernate 连接Oracle (二)

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;
    }
}


发表评论

邮箱地址不会被公开。 必填项已用*标注

昵称 *