1. 程式人生 > >利用Hibernate進行簡單的增刪改查(未使用JPA註解,以Oracle為例)

利用Hibernate進行簡單的增刪改查(未使用JPA註解,以Oracle為例)

第一步、建立一個Java專案,名為Hibernate_one

第二步、載入jar包,在src下建立了lib資料夾,用來存放jar包(jar包必須一個都不能少)。如圖

我連線的資料庫是Oracle,所以得載入Oracle的驅動包ojdbc6,如果用mysql資料庫,可從網上下載mysql的驅動包。並將包buildpath


第三步、配置hibernate(作用是連線資料庫,必不可少!!!)

在src目錄下建立xml檔案,命名為:hibernate.cfg.xml

配置內容如下

<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
  ~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
  -->
<!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>
		<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
		<!-- 資料庫連線地址 --><pre name="code" class="html"><span style="white-space:pre">		</span><!-- 資料庫不同,連線地址不同,可從網上百度 -->
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<span style="white-space:pre">		</span><!-- 資料庫的使用者名稱及密碼 -->
<property name="connection.username">scott</property><property name="connection.password">scott</property><!-- 方言 --><property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<span style="white-space:pre">		</span><!-- 是否顯示sql語句,預設為sql -->
<property name="show_sql">true</property><!-- 格式化語句,避免出現亂碼 --><property name="format_sql">true</property><!-- 
<span style="white-space:pre">		</span>validate 載入hibernate時,驗證資料庫的結構  預設值
		update  載入hibernate時,檢查資料庫,如果表不存在,則建立,如果存在,則更新
		create  每次載入hiberante,都會建立表
		create-drop  每次載入hiberante,建立,解除安裝hiberante時,銷燬
		 -->
		<property name="hbm2ddl.auto">update</property> 
		<!--看你的.hbm檔案放在哪裡,如果用的JPA註解,則該項存放的是持久類的路徑 -->
		<mapping resource="com/aisino/hibernate/Student0923.hbm.xml"/>
		
	</session-factory>
</hibernate-configuration>
以上就是Hibernate配置的詳細,不同資料庫配置語句不同,自己搜尋即可

第四步、建立持久化類,並實現set/get方法及toString。如果使用JPA註解,則在持久類中編寫,而不用編寫對映檔案
       建立一個包,名為com.aisino.hibernate,下面建立持久化類Student0923

package com.aisino.hibernate;


public class Student0923 {
	private int id;
	private String name;
	private int age;
	public Student0923(){
		
	}
	
	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 int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Student0923 [age=" + age + ", id=" + id + ", name=" + name
				+ "]";
	}
	
	
	
}

第五步,編寫對映檔案。命名為:Student0923.hbm.xml。(注意,對映檔案必須與持久化類放同一包下)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- 持久化對映檔案 -->
<hibernate-mapping><pre name="code" class="html"><span style="white-space:pre">	</span><!-- name為持久化類的路徑,table為表名,你要建立的表的名字 -->
<class name="com.aisino.hibernate.Student0923" table="stu_0923"><!-- 持久化類的唯一標識 --><id name="id" column="id">
<span style="white-space:pre">		</span><!-- 設定主鍵 -->
<generator class="native"/></id>
<span style="white-space:pre">		</span><!-- 其餘欄位 -->
<property name="name" column="name"></property><property name="age" column="age"></property></class></hibernate-mapping> 第六步、編寫Hibernate的工具類,如下程式碼
package com.aisino.hibernate.source;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


public class HibernateUtil {

	public static final SessionFactory sessionFactory;  
	public static final ThreadLocal session = new ThreadLocal();  
	
	static{  
		try{  
			Configuration configuration=new Configuration().configure();   
			sessionFactory = configuration.buildSessionFactory();  
		}catch (Throwable ex){  
			System.err.println("Initial SessionFactory creation failed." + ex);  
			throw new ExceptionInInitializerError(ex);  
		}  
	}  
	public static Session currentSession() throws HibernateException{  
		Session s = (Session) session.get();  
		if (s == null)  
		{  
			s = sessionFactory.openSession();  
			session.set(s);  
		}  
		return s;  
	}  
 
	public static void closeSession() throws HibernateException {  
		Session s = (Session) session.get();  
		if (s != null)  
			s.close();  
		session.set(null);  
	}  	
}

第七步、寫一個類CreateTable,進行單元測試,建立表
import org.hibernate.cfg.Configuration;
import org.junit.Test;


public class CreateTable {

	@Test
	public void test(){
<span style="white-space:pre">		</span><!--獲取hibernate的配置 -->
		Configuration configuration = new Configuration();
		configuration.configure();
		
		configuration.buildSessionFactory();
	}
}
執行以上程式碼進行單元測試,將在資料庫中建立表stu_0923

第八步、建一個類Crud,執行增刪改查操作

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

import com.aisino.hibernate.Student0923;


public class Crud {

	@Test
	public void testSavePerson(){
		//載入hibernate的配置檔案
		Configuration configuration = new Configuration();
		configuration.configure();
		//產生sessionFactory
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		//開啟session
		Session session = sessionFactory.openSession();
		//開啟事務
		Transaction transaction = session.beginTransaction();
		//建立一個物件
		Student0923 stu = new Student0923();
		stu.setId(2);
		stu.setName("yang");
		stu.setAge(22);
		session.save(stu);
		
		//事務提交
		transaction.commit();
		//session關閉
		session.close();
	}
	
	
	@Test
	public void testSelect(){
		//載入hibernate的配置檔案
		Configuration configuration = new Configuration();
		configuration.configure();
		//產生sessionFactory
		SessionFactory sessionFactory = configuration.buildSessionFactory();
		//開啟session
		Session session = sessionFactory.openSession();
		List<Student0923> list = session.createQuery("from Student0923").list();
		for (Student0923 student0923 : list) {
			System.out.println(student0923.toString());
		}
		//Student0923 stu=(Student0923) session.get(Student0923.class, 1);
		//System.out.println(stu.toString());
		
		//session關閉
		session.close();
	}
	
	
	@Test
	public void Modify(){
		//載入Hibernate的配置檔案
		Configuration cfg=new Configuration();
		cfg.configure();
		//產生sessionFactory
		SessionFactory sessionFactory=cfg.buildSessionFactory();
		//開啟Session
		Session session=sessionFactory.openSession();
		//開啟事物
		Transaction transaction=session.beginTransaction();
		//載入物件.需要強制轉換,獲得第一條資料的物件
		Student0923 student=(Student0923) session.get(Student0923.class,1);
		//修改資料,注意,get方法的第二個引數是id值,不能修改,只能修改其實的欄位
		student.setAge(100);
		student.setName("tian");
		//強制重新整理
		session.flush();
		
		//提交事物
		transaction.commit();
		//關閉session
		session.close();
	}
	
	@Test
	public void Delete(){
		//載入Hibernate的配置檔案
		Configuration cfg=new Configuration().configure();
		//產生SessionFactory
		SessionFactory sessionFactory=cfg.buildSessionFactory();
		//獲取session
		Session session=sessionFactory.openSession();
		//開啟事物
		Transaction transaction=session.beginTransaction();
		//獲取需要刪除的物件
		Student0923 student=(Student0923)session.get(Student0923.class, 1);
		//刪除
		session.delete(student);
		//強制更新
		session.flush();
		//事物提交
		transaction.commit();
		//關閉session
		session.close();		
	}
	

}

以上增刪改查操作,利用單元測試永興,並在資料庫中檢視。

以下是我的Java專案結構


以上就是簡單的hibernate使用,是非JPA註解的使用。適合初學者檢視,使用JPA方便快捷,之後會在部落格中介紹。可以上網瞭解JPA註解的種類等相關資料

相關推薦

利用Hibernate進行簡單刪改使用JPA註解Oracle

第一步、建立一個Java專案,名為Hibernate_one 第二步、載入jar包,在src下建立了lib資料夾,用來存放jar包(jar包必須一個都不能少)。如圖 我連線的資料庫是Oracle,所以得載入Oracle的驅動包ojdbc6,如果用mysql資料庫,可從網上

使用CoreData進行資料刪改附Demo

       本文主要介紹簡單CoreData的使用,從建立工程到進行資料的增刪改查,關於CoreData中的名詞解釋什麼的不做過多介紹。        首先,建立一個CoreData工程,在建立工程的選項處勾選Use CoreData,建立成功後,會在AppDelegat

Spring + Hibernate實現簡單刪改

一、準備工作: 1.建立資料庫think,建立資料表user,裡面有兩個欄位name和pwd,均為varchar型別。 2.在eclipse中建立SH工程,在lib目錄下匯入相關包:              二、Hibernate的相關準備工作 1.建立com.zt包,在

mysql簡單刪改CRUD

into 數量 分組 varchar 就會 不能 strong unsigned avi 先描述一下查看表中所有記錄的語句以便查看所做的操作(以下所有語句建議自己敲,不要復制以免出錯):     user表,字段有 id, name,age,sex;id為主鍵,自增,插入

Java操作Hbase刪改附帶複合條件查詢以及分頁查詢

  最近專案中用到了Hbase,所以看了下Java操作Hbase的有關API,並根據專案中的需求寫了下增刪改查。閒話少說,先貼原始碼: package com.infobird.test1; import java.io.IOException; import java

利用HTML5上傳檔案並顯示在前端預覽圖片

由於專案中有上傳檔案的功能,所以這次單獨拿出來研究研究,我上網查了查,以前都是用iframe,但是自從HTML5出世之後,就可以利用H5的一些特性來上傳檔案了,啥也不說了,我上程式碼了 <!DOCTYPE html> <html lang

linux驅動由淺入深系列:塊裝置驅動之三塊裝置驅動結構分析mmc

linux驅動由淺入深系列:塊裝置驅動之一(高通eMMC分割槽例項)前一篇文章介紹了塊裝置驅動在linux框架張的位置關係,本文來分析一下驅動本身。塊裝置驅動的模型還是基本基於字元裝置驅動的,可以簡單理解為塊裝置僅僅增加了操作緩衝區,對使用者操作請求進行佇列重排。因此只在有了

阿里雲伺服器部署FTP服務CentOS 7.3 64位vsftpd

一、安裝vsftpd yum -y install vsftpd 二、配置 vsftpd的配置檔案在/etc/vsftpd,其中vsftp.conf檔案是主配置檔案,開啟如下: # Example config file /etc/vsftpd

通過JDBC進行簡單刪改MySQL

mage ron end main exce javax xtend 探索 rman 通過JDBC進行簡單的增刪改查(以MySQL為例) 目錄 前言:什麽是JDBC 一、準備工作(一):MySQL安裝配置和基礎學習 二、準備工作(二):下載數據庫對應的jar包並

通過JDBC進行簡單刪改MySQL轉載

IE trac archive solver ttl 賦值 TP 定義 for 轉載:https://www.cnblogs.com/wuyuegb2312/p/3872607.html 目錄 前言:什麽是JDBC 一、準備工作(一):MySQL安裝配置和基礎學習 二、準備

hibernate簡單程式實現從頁面對資料庫的刪改主從表關聯

      前段時期一直使用三層來寫從頁面對資料庫的增刪改查,今天用hibernate框架來實現從頁面對資料庫的增刪改查, 首先介紹下今天我們要實現的功能, 1、使用者能夠註冊,2、註冊成功後直接跳到登入頁面,3、登入成功後直接跳到對公司、人員的增刪改查, 4、要有對人員介

在java中對數據庫進行刪改

ima ive upd line 增加 key get cat imp 1.java連接MySql數據庫 代碼區域: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

SpringMVC+Spring+HIbernate 簡單刪改例項

SpringMVC+Spring+HIbernate 簡單增刪改查例項 HIbernate配置mysql資料庫的方式 和 Structs+spring+HIbernate 是一樣的。  可以理解為SpringMVC 把

Zookeeper JavaAPI對節點進行刪改詳細步驟

import java.io.IOException; import java.util.List; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.ap

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

最近入門學習Hibernate框架,想分享總結一下踩過的坑和成功後的案例。 所用軟體: eclipse Oracle資料庫 (如果你使用的不是Oracle資料庫可以修改hibernate.cfg.xml裡面的配置)   現在,我們來看一下我們的包結構和資料庫表結構 第一步:建立eclip

MySQL刪改簡單的dos命令操作語句

cmd輸入mysql -uroot -proot   進入mysql        (注意:這裡我mysql的使用者名稱和密碼都是root 你們應該輸入自己的) 檢視資料庫 show data

SSM框架整合實現刪改簡單的實現

SSM框架整合實現增刪改查 檔案結構 POM檔案 <packaging>war</packaging> <!-- 處理亂碼 --> <properties> <!-- 設定專案字符集 -->

Mysql筆記簡單刪改

這是我在學習Mysql之路上做的筆記,今天將它粘出來。這一篇主要是簡單增刪改查。有錯誤的歡迎大家指出。。。 #增刪改查 #建立部門表 CREATE TABLE IF NOT EXISTS tb_d

hibernate對單表刪改CRUD

增刪改查: save update delete get/load(查詢單個記錄) import java.util.Date; import org.hibernate.Session; import org.hibernate.Session

mybatis環境搭建對錶進行刪改通過id查詢所有行list返回通過兩個關鍵字進行查詢

搭建mybatis 開發環境 1.    引入jar包 Mybatis 3.2.2.jar    ojdbc5.jar    log4j-1.2.17.jar(列印日誌,可以看到mybatis的具體實現) 2.    為mybatis 設定執行環境(通過配置檔案) myba