1. 程式人生 > >Hibernate入門 連線Oracle資料庫 簡單增刪改查

Hibernate入門 連線Oracle資料庫 簡單增刪改查

最近入門學習Hibernate框架,想分享總結一下踩過的坑和成功後的案例。

所用軟體:

eclipse

Oracle資料庫 (如果你使用的不是Oracle資料庫可以修改hibernate.cfg.xml裡面的配置)

 

現在,我們來看一下我們的包結構和資料庫表結構

第一步:建立eclipse專案

                       1.eclipse裡面新建一個Dynamic Web Project專案

                       2.在src中建一個名叫hibernate.cfg.xml的xml檔案和兩個分別叫com.Sakura.maya.model和com.Sakura.maya.test的包。

                       3.在com.Sakura.maya.model包中建兩個類Hibernate.java和Hibernate.hbm.xml的檔案

                       4.在com.Sakura.maya.test包中建立一個叫HibernateAction的類

結構如下:

第二步:引入jar包

包名如下:

第三步:建立資料庫

create table Table_wcc_text( 
  stu_id      number(10)   primary key, 
  stu_name    varchar2(20) not null, 
  stu_sex     varchar2(20)  default 'men' check(stu_sex in('men','women'))
)

結構如下:

 

第四步:加入程式碼

1.Hibernate.java

package com.Sakura.maya.model;

public class Hibernate {
	private int stu_id;
	private String stu_name;
	private String stu_sex;
	public int getStu_id() {
		return stu_id;
	}
	public void setStu_id(int stu_id) {
		this.stu_id = stu_id;
	}
	public String getStu_name() {
		return stu_name;
	}
	public void setStu_name(String stu_name) {
		this.stu_name = stu_name;
	}
	public String getStu_sex() {
		return stu_sex;
	}
	public void setStu_sex(String stu_sex) {
		this.stu_sex = stu_sex;
	}
	@Override
	public String toString() {
		return "HibernateAction [stu_id=" + stu_id + ", stu_name=" + stu_name
				+ ", stu_sex=" + stu_sex + "]";
	}
}

2.Hibernate.hbm.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-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
       <!--  如果不是Oracle資料庫請修改-->
        <!-- <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> --> <!-- 資料庫方言 如果不是Oracle資料庫請修改-->
        <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property><!-- 引用jdbc包 如果不是Oracle資料庫請修改-->
        <property name="hibernate.connection.username">使用者名稱</property>
        <property name="hibernate.connection.password">密碼</property>
        <property name="hibernate.connection.url">jdbc:oracle:資料庫連結</property> <!-- 資料庫連結 -->
        <property name="show_sql">true</property> <!-- true 執行完在控制檯列印SQL語句 -->
            <!-- 表對映載入  -->
        <mapping resource="com/Sakura/maya/model/Hibernate.hbm.xml"/>
        
    </session-factory>
</hibernate-configuration>

3.hibernate.cfg.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">
<hibernate-mapping default-lazy="false" package="com.Sakura.maya.model">    <!-- 匯入包 -->

    <class name="Hibernate" table="Table_wcc_text"> <!-- 表名 -->
        <id name="stu_id">    <!-- 主鍵 -->                        
            <generator class="assigned"/><!-- 如果主鍵是自增長改為class="native" -->
        </id>
        <!-- 對應的各個欄位名 -->
        <property name="stu_name"/>
        <property name="stu_sex"/>
    
    </class>   
</hibernate-mapping>

4.HibernateAction.java

package com.Sakura.maya.test;

import java.util.List;

import javax.security.auth.kerberos.DelegationPermission;

import org.hibernate.*;
import org.hibernate.cfg.*;

import com.Sakura.maya.model.Hibernate;

public class HibernateAction {

	//讀取hibernate.cfg.xml的配置,載入Hiberna的類庫
    Configuration config=new Configuration().configure();
    //根據配置,生成session工廠
    SessionFactory factory= config.buildSessionFactory();
    //用工廠生成session
    Session session =factory.openSession();


	public static void main(String[] args) {

		HibernateAction dl = new HibernateAction();
		dl.SelectAll();
	}

	public void Select(Integer stu_id) {

		// 查詢
		Hibernate data = (Hibernate) session.get(Hibernate.class, stu_id);
		System.out.println(data.getStu_id() + data.getStu_name()
				+ data.getStu_sex());


	}

	public void SelectAll() {
		// 查詢所有
		String hqlString = "from Hibernate";
		Query query = session.createQuery(hqlString);
		List<Hibernate> list = query.list();
		for (Hibernate ll : list) {
			System.out.print(ll);
		}
		session.close();
	}

	public void Insert() {
		//新增
        //1.造物件
		Hibernate data = new Hibernate();
		data.setStu_id('1');
		data.setStu_name("Sakura");
		data.setStu_sex("men");

        //2.用session.save()儲存到資料庫了
		try {
			session.beginTransaction();
			session.save(data);
			session.getTransaction().commit();
			System.out.print("新增成功");
		} catch (Exception ex) {
			session.getTransaction().rollback();
		}

		session.close();

	}

	//刪除
    
	public void Delete(Integer stu_id) {
		//先查出
		Hibernate data = (Hibernate) session.get(Hibernate.class, stu_id);// get?�load?�可以查
		if (data != null) {
			session.beginTransaction();
			//刪除提交資料庫
			session.delete(data);
			System.out.print("刪除成功");
			session.getTransaction().commit();
		}
		session.close();
		
	}

	public void update(Integer stu_id) {
		//修改
        //1.查
		Hibernate data = (Hibernate) session.load(Hibernate.class, stu_id);

		if (data != null) {
			session.beginTransaction();
			//2.改
			data.setStu_name("Sakura1");
			data.setStu_sex("women");
			//3.提交
			session.update(data);
			session.getTransaction().commit();
		}

		session.close();
		System.out.print("修改成功");
	}

}

OK!就搭建成功了!

 

在搭建之中遇見的小問題:

     1.顯示連線不到資料庫

       解決方法:可能是你不是oracle資料庫在hibernate.cfg.xml中修改連線方法。

     2.報錯:javax/transaction/Synchronization

       解決方法:你需要下載一個jta.jar包

     3.報錯:找不到hibernate.cfg.xml檔案

       解決方法:缺少jar包或者放的位置不對,放在src