orm概念
orm即object/relation mapping, 對象/關系數據庫映射。orm是一種規范,完成面向對象編程語言到關系數據庫之間的映射。j2ee中的jpa就是一種orm規范。
orm框架有很多,例如jpa, hibernate,ibatis等。
hibernate簡介
hibernate是jboss旗下,同時也是rethat組織的產品(jboss加入了rethat),是目前非常流行的orm框架。
hibernate中的重要概念為po(persistent object), hibernate采用低入侵的設計,這里的po完全是一個普通的java類(pojo),其數據庫操作功能完全由hibernate實現,不需要pojo實現任何接口或者繼承任何超類。
hibernate環境搭建(eclipse環境)
1.下載框架
hibernate框架,官網下載 http://www.hibernate.org/downloads
目前最新版是5.2.2,為了兼容和穩定起見我下載的是4.3.11版,hibernate-release-4.3.11.final.zip ,解壓后看到主要目錄如下,
-project , 這個目錄下放了很多demo project
-documentation 下面放了各種文檔和教程,最重要的應該是hibernate api, 即 javadocs
-lib 下面有很多二級目錄,里面放了各種jar包,hibernate是模塊化的,其中required是hibernate框架基礎jar包,其他目錄是一些擴展包,例如lib\optional\c3p0下面放了數據庫連接池的jar包。
另外,還需要下載日志框架包slf4j,hibernate會用它來在執行時候輸出日志。
我下載的是1.6.1版本,可以在官網的數據倉庫中找到 http://www.slf4j.org/dist/
2. 導入各種jar包
先在eclipse中新建一個project,然后新建一個user library,例如叫做 hibernate-4-3-11,注意不要勾選system library,否則后面在讀取hibernate配置文件時候一直會報 java.lang.nullpointerexception 異常。
導入以下jar包
-hibernate下的 lib\require下的所有jar包(10個),這是框架基本jar包
-hibernate下的lib\optional\c3p0的所有jar包,這是數據庫連接池jar包,為hibernate框架提供數據源
-slf4框架下的slf4j-api-1.6.1.jar (這是api) 和 slf4j-nop-1.6.1.jar (這是具體實現) 兩個包
我將所有jar包集中放在了一個目錄里方便今后遷移,所有jar包如下,
將以上15個jar都添加進user library中去。
3.創建一個實體類
new類將要用來與數據庫中的一張表對應,它只是一個普通類(pojo),我們放在src/hib路徑下,后面hibernate將會根據配置文件創建數據表
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
package hib; public class news { public int getid() { return id; } public void setid( int id) { this .id = id; } public string gettitle() { return title; } public void settitle(string title) { this .title = title; } public string getcontent() { return content; } public void setcontent(string content) { this .content = content; } private int id; private string title; private string content; } |
4.創建表映射文件
在news類相同的路徑下創建一個xml文件news.hbm.xml,這個文件與news.java對應,叫做映射文件,是一個hibernate將依據這個文件操作數據庫。
通過某些插件,可以依據實體類news.java 自動創建news.hbm.xml,不過我還是先收工創建一下。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<?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 package = "hib" > < class name= "news" table= "news_table" > <id name= "id" column= "id" > <generator class = "identity" /> </id> <property name= "title" type= "string" column= "title" /> <property name= "content" type= "string" column= "content" /> </ class > </hibernate-mapping> |
news.hbm.xml的語法在hibernate提供的手冊(hibernate-release-4.3.11.final/documentation/manual/en-us/html_single/index.html)1.1.3. the mapping file 中已經有詳細描述,
每一個持久化的實體類(例如上面的news.java),都需要有一個到數據表的映射,這里的<class>元素就是一個映射
表的主鍵用<id>元素表示,其他字段則用<property>元素表示,每個字段元素中可以添加name, colume, type屬性,分別表示字段名稱和類型
5.創建hibernate主配置文件
hibernate配置文件的默認名稱是hibernate.cfg.xml,我們創建這個文件并放在src根目錄,文件內容如下,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
<?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.driver_class" >com.mysql.jdbc.driver</property> <property name= "connection.url" >jdbc:mysql: //127.0.0.1:3306/think_blog?useunicode=true&characterencoding=utf-8</property> <!-- 指定字符集的方式--> <property name= "connection.username" >root</property> <property name= "connection.password" ></property> <property name= "hibernate.c3p0.max_size" > 20 </property> <property name= "hibernate.c3p0.min_size" > 1 </property> <property name= "hibernate.c3p0.timeout" > 5000 </property> <property name= "hibernate.c3p0.max_statements" > 100 </property> <property name= "hibernate.c3p0.idle_test_period" > 3000 </property> <property name= "hibernate.c3p0.acquire_increment" > 2 </property> <property name= "hibernate.c3p0.validate" > true </property> <property name= "dialect" >org.hibernate.dialect.mysqldialect</property> <!--數據庫方言--> <!--自動建表及打印sql --> <property name= "hbm2ddl.auto" >update</property> <property name= "show_sql" > true </property> <mapping resource= "hib/news.hbm.xml" /> </session-factory> </hibernate-configuration> |
對上面的關鍵點解釋如下:
數據庫連接字符串:如果要指定字符集,在url后面加上?useunicode=true&characterencoding=utf-8, 但因為url要放在xml文件中,需要將&符號轉義成"&"
我也使用使用<property name="connection.charset">utf8</property> 這種方式兼容中文,但是好像并不起作用
數據庫方言:我使用的是mysql數據庫,最開始我使用的數據庫方言配置是org.hibernate.dialect.mysqlinnodbdialect,但是發現無法通過hibernate自動建表,后來發現換成org.hibernate.dialect.mysqldialect就行了。
所有數據庫方言配置可以在手冊中找到 ,hibernate-release-4.3.11.final/documentation/manual/en-us/html_single/index.html#tutorial-firstapp-mapping 的 3.4.1. sql dialects
是否根據實體類和映射文件自動建表:<property name="hbm2ddl.auto">update</property>
打印sql到控制臺:<property name="show_sql">true</property>
6. 創建測試類
newsmanager也放在hib路徑下,在這個類中初始化hibernate執行數據庫操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
package hib; import org.hibernate.session; import org.hibernate.sessionfactory; import org.hibernate.transaction; import org.hibernate.cfg.configuration; public class newsmanager { public static void main(string[] args) { //實例化configuration //configure()方法默認加載 /hibernate.cfg.xml configuration conf = new configuration().configure(); //用configuration創建sessionfactory sessionfactory sf = conf.buildsessionfactory(); //用sessionfactory打開session session sess = sf.opensession(); //開始事務 transaction tx = sess.begintransaction(); //創建消息實例 news n = new news(); //設置消息標題和消息內容 n.settitle( "天王蓋地虎" ); n.setcontent( "寶塔鎮河妖" ); //保存消息 sess.save(n); //提交事務 tx.commit(); //關閉session 和 sessionfactory sess.close(); sf.close(); system.out.println( "執行完畢" ); } } |
注意上面的configuration().configure()方法,是從默認的路徑src下加載hibernate配置文件hibernate.cfg.xml。
啟動mysql數據庫(確保存在上面配置文件中的數據庫名),再在eclipse中執行newsmanager類結果如下,可以看到在末尾答應出了sql語句,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
dec 23 , 2016 2 : 57 : 38 pm org.hibernate.annotations.common.reflection.java.javareflectionmanager <clinit> info: hcann000001: hibernate commons annotations { 4.0 . 5 . final } dec 23 , 2016 2 : 57 : 38 pm org.hibernate.version logversion info: hhh000412: hibernate core { 4.3 . 11 . final } dec 23 , 2016 2 : 57 : 38 pm org.hibernate.cfg.environment <clinit> info: hhh000206: hibernate.properties not found dec 23 , 2016 2 : 57 : 38 pm org.hibernate.cfg.environment buildbytecodeprovider info: hhh000021: bytecode provider name : javassist dec 23 , 2016 2 : 57 : 38 pm org.hibernate.cfg.configuration configure info: hhh000043: configuring from resource: /hibernate.cfg.xml dec 23 , 2016 2 : 57 : 38 pm org.hibernate.cfg.configuration getconfigurationinputstream info: hhh000040: configuration resource: /hibernate.cfg.xml dec 23 , 2016 2 : 57 : 38 pm org.hibernate.internal.util.xml.dtdentityresolver resolveentity warn: hhh000223: recognized obsolete hibernate namespace http: //hibernate.sourceforge.net/. use namespace http://www.hibernate.org/dtd/ instead. refer to hibernate 3.6 migration guide! dec 23 , 2016 2 : 57 : 38 pm org.hibernate.cfg.configuration addresource info: hhh000221: reading mappings from resource: hib/news.hbm.xml dec 23 , 2016 2 : 57 : 39 pm org.hibernate.internal.util.xml.dtdentityresolver resolveentity warn: hhh000223: recognized obsolete hibernate namespace http: //hibernate.sourceforge.net/. use namespace http://www.hibernate.org/dtd/ instead. refer to hibernate 3.6 migration guide! dec 23 , 2016 2 : 57 : 39 pm org.hibernate.cfg.configuration doconfigure info: hhh000041: configured sessionfactory: null dec 23 , 2016 2 : 57 : 39 pm org.hibernate.c3p0.internal.c3p0connectionprovider configure info: hhh010002: c3p0 using driver: com.mysql.jdbc.driver at url: jdbc:mysql: //127.0.0.1:3306/think_blog?useunicode=true&characterencoding=utf-8 dec 23 , 2016 2 : 57 : 39 pm org.hibernate.c3p0.internal.c3p0connectionprovider configure info: hhh000046: connection properties: {user=root, password=****} dec 23 , 2016 2 : 57 : 39 pm org.hibernate.c3p0.internal.c3p0connectionprovider configure info: hhh000006: autocommit mode: false dec 23 , 2016 2 : 57 : 39 pm com.mchange.v2.log.mlog <clinit> info: mlog clients using java 1.4 + standard logging. dec 23 , 2016 2 : 57 : 39 pm com.mchange.v2.c3p0.c3p0registry banner info: initializing c3p0- 0.9 . 2.1 [built 20 -march- 2013 10 : 47 : 27 + 0000 ; debug? true ; trace: 10 ] dec 23 , 2016 2 : 57 : 39 pm com.mchange.v2.c3p0.impl.abstractpoolbackeddatasource getpoolmanager info: initializing c3p0 pool... com.mchange.v2.c3p0.poolbackeddatasource @49eb2a4c [ connectionpooldatasource -> com.mchange.v2.c3p0.wrapperconnectionpooldatasource @92efcc58 [ acquireincrement -> 2 , acquireretryattempts -> 30 , acquireretrydelay -> 1000 , autocommitonclose -> false , automatictesttable -> null , breakafteracquirefailure -> false , checkouttimeout -> 0 , connectioncustomizerclassname -> null , connectiontesterclassname -> com.mchange.v2.c3p0.impl.defaultconnectiontester, debugunreturnedconnectionstacktraces -> false , factoryclasslocation -> null , forceignoreunresolvedtransactions -> false , identitytoken -> 1hgeby99lbs898r1pl3km1|187a62fa, idleconnectiontestperiod -> 3000 , initialpoolsize -> 1 , maxadministrativetasktime -> 0 , maxconnectionage -> 0 , maxidletime -> 5000 , maxidletimeexcessconnections -> 0 , maxpoolsize -> 20 , maxstatements -> 100 , maxstatementsperconnection -> 0 , minpoolsize -> 1 , nesteddatasource -> com.mchange.v2.c3p0.drivermanagerdatasource @e332f0e7 [ description -> null , driverclass -> null , factoryclasslocation -> null , identitytoken -> 1hgeby99lbs898r1pl3km1|4a84466d, jdbcurl -> jdbc:mysql: //127.0.0.1:3306/think_blog?useunicode=true&characterencoding=utf-8, properties -> {user=******, password=******} ], preferredtestquery -> null, propertycycle -> 0, statementcachenumdeferredclosethreads -> 0, testconnectiononcheckin -> false, testconnectiononcheckout -> false, unreturnedconnectiontimeout -> 0, usestraditionalreflectiveproxies -> false; useroverrides: {} ], datasourcename -> null, factoryclasslocation -> null, identitytoken -> 1hgeby99lbs898r1pl3km1|2c6d9d9c, numhelperthreads -> 3 ] dec 23 , 2016 2 : 57 : 40 pm org.hibernate.dialect.dialect <init> info: hhh000400: using dialect: org.hibernate.dialect.mysqldialect dec 23 , 2016 2 : 57 : 40 pm org.hibernate.engine.jdbc.internal.lobcreatorbuilder usecontextuallobcreation info: hhh000424: disabling contextual lob creation as createclob() method threw error : java.lang.reflect.invocationtargetexception dec 23 , 2016 2 : 57 : 40 pm org.hibernate.engine.transaction.internal.transactionfactoryinitiator initiateservice info: hhh000399: using default transaction strategy (direct jdbc transactions) dec 23 , 2016 2 : 57 : 40 pm org.hibernate.hql.internal.ast.astquerytranslatorfactory <init> info: hhh000397: using astquerytranslatorfactory dec 23 , 2016 2 : 57 : 40 pm org.hibernate.tool.hbm2ddl.schemaupdate execute info: hhh000228: running hbm2ddl schema update dec 23 , 2016 2 : 57 : 40 pm org.hibernate.tool.hbm2ddl.schemaupdate execute info: hhh000102: fetching database metadata dec 23 , 2016 2 : 57 : 40 pm org.hibernate.tool.hbm2ddl.schemaupdate execute info: hhh000396: updating schema dec 23 , 2016 2 : 57 : 40 pm org.hibernate.tool.hbm2ddl.databasemetadata gettablemetadata info: hhh000262: table not found: news_table dec 23 , 2016 2 : 57 : 40 pm org.hibernate.tool.hbm2ddl.databasemetadata gettablemetadata info: hhh000262: table not found: news_table dec 23 , 2016 2 : 57 : 40 pm org.hibernate.tool.hbm2ddl.databasemetadata gettablemetadata info: hhh000262: table not found: news_table dec 23 , 2016 2 : 57 : 40 pm org.hibernate.tool.hbm2ddl.schemaupdate execute info: hhh000232: schema update complete hibernate: insert into news_table (title, content) values (?, ?) 執行完畢 |
同時我們查看mysql數據庫,發現在think_blog庫下多了一張表news_table,同時在表中我們插入了一條數據,
到此,我們的hibernate環境就算是配置成功了,并且成功執行了一個基本的demo。
從測試類中可以總結hibernate的一般步驟,
-加載hibernate配置文件(hibernate.cfg.xml,默認從src目錄加載),從而獲得hibernate的configuration實例
-通過configuration的實例創建session工廠
-通過session工廠打開一個session
-通過session開起一個事務
-進行實體類的set或者get操作
-將實體類的操作結果保存進session
-提交事務
-關閉session及session工廠資源
以上步驟完全是面向對象的編程方式,不直接操作數據庫,但是通過hibernate完成了數據庫操作,這便是hibernate的基本原理。
這篇hibernate之環境搭建及demo分享就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/fysola/p/6215051.html