1. 程式人生 > >hibernate連線MySQL資料庫小例子

hibernate連線MySQL資料庫小例子

第一步:導jar包
hibernate5.2.10 的 jar 包和連線 MySQL 的 jar包


第二步:建立 hibernate 配置檔案   hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!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.username">root</property>
    	<property name="connection.password">1230</property>
    	<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    	<property name="connection.url">jdbc:mysql:///hibernate5</property>
    	
    	<!-- 配置 hibernate 的基本資訊 -->
    	<!-- hibernate 所使用的資料庫方言 -->
    	<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
    
    	<!-- 執行操作時是否在控制檯列印SQL -->
    	<property name="show_sql">true</property>
    	
    	<!-- 是否對 SQL 進行格式化 -->
    	<property name="hibernate.format_sql">true</property>
    	
    	<!-- 指定自動生成資料表的策略 -->
    	<property name="hbm2ddl.auto">update</property>
    	
    	<!-- 指定關聯的 .hbm.xml檔案 -->
        <mapping resource="com/loveyiyi/hibernate/hello/News.hbm.xml"/>
    	
    </session-factory>
</hibernate-configuration>

url中的hibernate5為表空間名,需要特別注意的是,MySQL5以上版本的資料庫方言都要改成org.hibernate.dialect.MySQL5InnoDBDialect

第三步:建立持久化類

import java.sql.Date;

public class News {
	
	private Integer id;
	private String title;
	private String author;
	
	private Date datetime;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}



	public Date getDatetime() {
		return datetime;
	}

	public void setDatetime(Date datetime) {
		this.datetime = datetime;
	}

	public News(String title, String author, Date datetime) {
		super();
		this.title = title;
		this.author = author;
		this.datetime = datetime;
	}

	public News() {
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	public String toString() {
		return "News [id=" + id + ", title=" + title + ", author=" + author + ", datetime=" + datetime + "]";
	}	
}

第四步:建立物件-關係對映檔案(用hibernate tools外掛可自動匯入)

<?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 2017-9-13 11:55:55 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
    <class name="com.loveyiyi.hibernate.hello.News" table="NEWS">
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <generator class="native" />
        </id>
        <property name="title" type="java.lang.String">
            <column name="TITLE" />
        </property>
        <property name="author" type="java.lang.String">
            <column name="AUTHOR" />
        </property>
        <property name="datetime" type="java.sql.Date">
            <column name="DATETIME" />
        </property>
    </class>
</hibernate-mapping>
生成的程式碼中預設的generator class為assigned,需要改成native

第五步:編寫訪問資料庫的程式碼

import static org.junit.Assert.*;

import java.sql.Date;

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

import com.loveyiyi.hibernate.hello.News;

public class HibernateTest {

	@Test
	public void test() {
		SessionFactory sessionFactory;  
		Session session;  
		Transaction transaction;

		//建立 Configuration 物件:對應 hibernate 的基本配置資訊和 物件關係對映資訊
		Configuration configuration = new Configuration().configure();
		
		//呼叫Configuration的buildSessionFactory()方法返回一個SessionFactory物件 
		sessionFactory = configuration.buildSessionFactory();  
		
		//從SessionFactory 中獲取 Session 物件
		session = sessionFactory.openSession();  
		
		//開啟事務
		transaction = session.beginTransaction();
		
		//執行儲存操作
		News news = new News("java","javaweb",new Date(new java.util.Date().getTime()));
		session.save(news);
		
		//提交事務
		transaction.commit();
		
		//關閉 Session
		session.close();
		
		//關閉 SessionFactory
		sessionFactory.close();
	}

}
其中獲取SessionFactory和hibernate4.x不一樣,具體區別見此處程式碼註釋部分 此時程式碼執行會報錯,需要在src下新建一個hibernate.properties,裡面寫入 hibernate.temp.use_jdbc_metadata_defaults=false,或者在配置檔案裡設定。因為hibernate預設使用jdbc進行資料傳輸,而使用資料連線池的話需要宣告一下。更新補充:隔了一天,在寫hibernate對映單向一對多的時候忘記聲明瞭,但是工程執行正常,在發現沒寫聲明後,把之前寫的工程中的宣告刪掉,發現都執行正常,不知所以 最後在JUit4下測試,即可在MySQL資料庫中顯示新建的表