創建項目
打開IDEA,選擇New Project,選擇Hibernate,點擊下一步
取名爲test3,點擊Finish,然後等待一下後創建項目成功
創建成功
新建一個包:
com.cerr.hibernate.helloworld
連接數據庫
先點擊右邊的Database,再點擊加號,Data Source,MySQL。
如果右邊沒有顯示Database的話,可以如下操作進行顯示
然後填好對應的信息後點擊Test Connection看看數據庫是否能成功連接。
如果使用的不是MySQL8.0以上的話在連接數據庫時會報錯08001
只需點擊MYSQL更換數據庫版本即可
我是更換到5.1.47就可以了
創建持久化類的映射文件
點擊左邊的Persistence,然後進行如下操作。
點擊OK之後就創建成功了,爲了編程方便,我們手動的對News類加上一個有參構造器和無參構造器,添加後代碼如下:
package com.cerr.hibernate.helloworld;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.Date;
import java.util.Objects;
@Entity
public class News {
private int id;
private String title;
private String author;
private Date date;
public News() {
}
@Id
@Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Basic
@Column(name = "title")
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Basic
@Column(name = "author")
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Basic
@Column(name = "date")
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
News news = (News) o;
return id == news.id &&
Objects.equals(title, news.title) &&
Objects.equals(author, news.author) &&
Objects.equals(date, news.date);
}
@Override
public int hashCode() {
return Objects.hash(id, title, author, date);
}
public News(String title, String author, Date date) {
this.title = title;
this.author = author;
this.date = date;
}
}
對應的映射文件:
<?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>
<class name="com.cerr.hibernate.helloworld.News" table="news" schema="hibernate5">
<id name="id" column="id"/>
<property name="title" column="title"/>
<property name="author" column="author"/>
<property name="date" column="date"/>
</class>
</hibernate-mapping>
配置hibernate.cfg.xml文件
首先我們應該把java的數據庫驅動jar包加入,加入mysql-connector-java-5.1.47-bin.jar
包。
然後打開hibernate.cfg.xml
文件,目前該文件如下:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate5</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<mapping resource="com/cerr/hibernate/helloworld/News.hbm.xml"/>
<mapping class="com.cerr.hibernate.helloworld.News"/>
<!-- <property name="connection.username"/> -->
<!-- <property name="connection.password"/> -->
<!-- DB schema will be updated if needed -->
<!-- <property name="hibernate.hbm2ddl.auto">update</property> -->
</session-factory>
</hibernate-configuration>
我們需要加入一些配置,例如賬號密碼等..,添加後如下:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 配置連接數據庫的基本信息 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate5</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- 配置hibernate的基本信息-->
<!-- hibernate所使用的的數據庫方言 -->
<property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<!-- 執行操作時是否在控制檯打印SQL-->
<property name="show_sql">true</property>
<!-- 是否對SQL進行格式化-->
<property name="format_sql">true</property>
<!-- 指定生成數據表的策略-->
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="com/cerr/hibernate/helloworld/News.hbm.xml"/>
<mapping class="com.cerr.hibernate.helloworld.News"/>
</session-factory>
</hibernate-configuration>
測試
新建一個測試類NewsTest.java
package com.cerr.hibernate.helloworld;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import java.util.Date;
public class NewsTest {
public static void main(String[] args) {
//創建一個Configuration對象
//Configuration對象對應於Hibernate的基本配置信息和對象關係映射文件
Configuration configuration = new Configuration().configure();
//創建一個SessionFactory對象
SessionFactory sessionFactory = configuration.buildSessionFactory();
//創建一個Session對象
Session session = sessionFactory.openSession();
//開啓事務
Transaction transaction = session.beginTransaction();
//執行保存操作
News news = new News("java","cerr",new Date(new java.util.Date().getTime()));
session.save(news);
//提交事務
transaction.commit();
//關閉Session
session.close();
//關閉SessionFactory
sessionFactory.close();
}
}
運行後成功。
下面我們進行解析
關於創建持久化類
- 需要提供一個無參的構造器
使Hibernate可以使用反射來實例化持久化類 - 提供一個標識屬性
- 爲類的持久化類字段聲明訪問方法(
getter/setter
) - 使用非final類
- 重寫
eqauls
和hashCode
方法
如果需要把持久化類的示例放到Set
中,則需要重寫這兩個方法
關於對象關係映射文件
Hibernate採用XML格式的文件來指定對象和關係數據之間的映射,在運行時Hibernate將根據這個映射文件來生成各種SQL語句。映射文件的擴展名爲.hbm.xml
Configuration類
Configuration類負責管理Hibernate的配置信息。包括如下內容
Hibernate運行的底層信息:數據庫的URL,用戶名,密碼,JDBC驅動類,數據庫Dialect,數據庫連接池等。對應於hibernate.cfg.xml
文件。
持久化類與數據表的映射關係(*.hbm.xml
文件)創建Configuration的兩種方式
如果使用屬性文件:hibernate.properties
創建:Configuration configuration = new Configuration();
如果使用Xml文件:hibernate.cfg.xml
創建:Configuration configuration = new Configuration().configure();
SessionFactory接口
針對單個數據庫映射關係經過編譯後的內存鏡像,是線程安全的。
SessionFactory
對象一旦構建完畢,即被賦予特定的配置信息。SessionFactory
是生成Session的工廠構造
SessionFactory
很消耗資源,一般情況下一個應用中只初始化一個SessionFactory
對象。創建
SessionFactory
的步驟
//創建一個Configuration對象
//Configuration對象對應於Hibernate的基本配置信息和對象關係映射文件
Configuration configuration = new Configuration().configure();
//創建一個SessionFactory對象
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session接口
Session是應用程序與數據庫之間交互操作的一個單線程對象,是Hibernate運作的中心,所有持久化對象必須在session的管理下纔可以進行持久化操作,此對象的生命週期很短,Session對象有一個一級緩存。Session相當於JDBC中的Connection。
Transaction(事務)
代表一次原子操作,它具有數據庫事務的概念。所有持久化層都應該在事務管理下執行,即使是隻讀操作。
開啓事務:Transaction tx = session.beginTransaction();
常用方法:
commit()
:提交相關聯的session實例
rollback()
:撤銷事務操作
wasCommitted()
:檢查事務是否提交
Hibernate配置文件的兩個配置項
hibernate.hbm2ddl.auto
:該屬性可幫助程序員實現正向工程,即由Java代碼生成數據庫腳本,進而生成具體的表結構。取值有create
,update
,create-drop
,validate
create
:會根據.hbm.xml
文件來生成數據庫,但是每次運行都會刪除上一次的表,重新生成表,哪怕二次沒有任何改變。
create-drop
:會根據.hbm.xml
文件生成表,但是SessionFactory
一關閉,表就刪除。
update
:最常用的屬性值,會根據.hbm.xml
文件生成表,但若.hbm.xml
文件和數據庫中對應的數據表的表結構不同,hibernate將更新數據表結構,但不會刪除已有的行和列。
validate
:會和數據庫中的表進行比較,若.hbm.xml
文件中的列在數據表中不存在,則拋出異常。format_sql
是否將SQL轉化爲格式良好的SQL,取值爲true
或flase