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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章