Hibernate的開發前準備以及入門操作

Hibernate是一個非常好用的ORM框架,本篇博客將會講述Hibernate的簡單入門的操作。

在開發前我們可以下載hibernate tools利於開發,下載地址如下:

https://sourceforge.net/projects/jboss/files/JBossTools/JBossTools4.1.x/hibernatetools-Update-4.1.1.Final_2013-12-08_01-06-33-B605.zip/download

下載完是hibernatetools-Update-4.1.2.Final_2014-03-18_15-46-19-B706.zip這樣的一個壓縮包,打開eclipse的help==>Install New Software==>Add==>Archive選擇剛纔下載的壓縮包之後默認下一步即可。配置完hibernate tools我們正式進行Hibernate的測試。

1.首先我們需要將Hibernate的包以及數據庫驅動包加載進來

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
		</dependency>

		<!-- hibernate所需的依賴 -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.2.4.Final</version>
		</dependency>

		<!-- 數據庫驅動包 -->
		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>oracle_driver</artifactId>
			<version>oracle11g</version>
		</dependency>

2.編寫hibernate.cfg.xml配置文件,因爲安裝了hibernate tools我們只需new==>Hibernate  Configuration File即可得到模板,我們再繼續加入需要的配置信息

<?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="connection.username">mytest</property>
		<property name="connection.password">a</property>
		<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
		<property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
		<!-- 方言 -->
		<property name="dialect">org.hibernate.dialect.OracleDialect</property>

		<!-- 是否在運行的時候顯示sql語句 -->
		<property name="show_sql">true</property>
		<!-- 顯示的sql語句是否進行排版 -->
		<property name="format_sql">true</property>
		<!-- 表結構生成策略 -->
		<property name="hbm2ddl.auto">create</property>
		<!-- getCurrentSession所需的參數(本地事務) -->
		<property name="hibernate.current_session_context_class">thread</property>
	</session-factory>
</hibernate-configuration>

3.編寫實體類

package com.yc.entity;

import java.sql.Blob;
import java.util.Date;

public class Student {
	private int sid;
	private String sname;
	private String  gender;
	private Date birthday;
	private String address;
	private Blob picture;

	public Student() {

	}
	public Student(int sid, String sname, String gender, Date birthday,String address) {
		this.sid = sid;
		this.sname = sname;
		this.gender = gender;
		this.birthday = birthday;
		this.address = address;
	}

	public int getSid() {
		return sid;
	}
	public void setSid(int sid) {
		this.sid = sid;
	}
	public String getSname() {
		return sname;
	}
	public void setSname(String sname) {
		this.sname = sname;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public Blob getPicture() {
		return picture;
	}
	public void setPicture(Blob picture) {
		this.picture = picture;
	}

	public String toString() {
		return "Student [sid=" + sid + ", sname=" + sname + ", gender="
				+ gender + ", birthday=" + birthday + ", address=" + address
				+ ", picture=" + picture + "]";
	}
}

4.編寫映射文件,並在cfg文件加上映射路徑,右擊Student類new==>Hibernate XML Mapping file自動生成如下文件

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2016-8-7 14:39:26 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.yc.entity.Student" table="STUDENT">
        <id name="sid" type="int">
            <column name="SID" />
            <generator class="sequence" >
            	<!-- 使用序列 -->
            	<param name="sequence">seq_student_aId</param>
            </generator>
        </id>
        <property name="sname" type="java.lang.String">
            <column name="SNAME" />
        </property>
        <property name="gender" type="java.lang.String">
            <column name="GENDER" />
        </property>
        <!-- type="date" 只獲取年月日的數據格式 -->
        <property name="birthday" type="date">
            <column name="BIRTHDAY" />
        </property>
        <property name="address" type="java.lang.String">
            <column name="ADDRESS" />
        </property>
        <property name="picture" type="java.sql.Blob">
     		<column name="PICTURE"></column>   	
        </property>
    </class>
</hibernate-mapping>
在cfg文件中加入映射信息

<!-- 映射 -->
<mapping resource="Student.hbm.xml"/>


5.編寫測試類測試

package com.yc.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.Date;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.yc.entity.Info;
import com.yc.entity.Student;

public class StudentTest {
	private SessionFactory sessionFactory;
	private Session session;
	private Transaction transaction;
	
	@Before
	public void init(){
		// 創建配置對象
		Configuration config = new Configuration().configure();
		
		// 創建服務註冊對象
		ServiceRegistry serviceRegistry=new 
				ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
		//ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
		
		// 創建會話工廠對象
		sessionFactory = config.buildSessionFactory(serviceRegistry);
		
		//創建會話對象
		session = sessionFactory.openSession();
		
		//開啓事務
		transaction = session.beginTransaction();
	}
	
	@After
	public void destory(){
		//提交事務
		transaction.commit();
		
		//關閉會話
		session.close();
		
		//關閉會話工廠
		sessionFactory.close();
	}

	@Test
	public void testSave() {
		Student stu=new Student(1000, "張三", "男", new Date(), "湖南衡陽");
		session.save(stu);
	}

6.運行結果



OK,到此我們的Hibernate開發準備已經完成,並且測試了其是否成功,下篇博客我們將介紹對單表的CRUD操作。

發佈了36 篇原創文章 · 獲贊 4 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章