您好,登錄后才能下訂單哦!
ORM概念
ORM即Object/Relation Mapping, 對(duì)象/關(guān)系數(shù)據(jù)庫映射。ORM是一種規(guī)范,完成面向?qū)ο缶幊陶Z言到關(guān)系數(shù)據(jù)庫之間的映射。J2EE中的JPA就是一種ORM規(guī)范。
ORM框架有很多,例如JPA, Hibernate,iBATIS等。
Hibernate簡介
Hibernate是JBoss旗下,同時(shí)也是RetHat組織的產(chǎn)品(JBoss加入了RetHat),是目前非常流行的ORM框架。
Hibernate中的重要概念為PO(Persistent Object), Hibernate采用低入侵的設(shè)計(jì),這里的PO完全是一個(gè)普通的java類(POJO),其數(shù)據(jù)庫操作功能完全由Hibernate實(shí)現(xiàn),不需要POJO實(shí)現(xiàn)任何接口或者繼承任何超類。
Hibernate環(huán)境搭建(Eclipse環(huán)境)
1.下載框架
Hibernate框架,官網(wǎng)下載 http://www.hibernate.org/downloads
目前最新版是5.2.2,為了兼容和穩(wěn)定起見我下載的是4.3.11版,hibernate-release-4.3.11.Final.zip ,解壓后看到主要目錄如下,
-project , 這個(gè)目錄下放了很多demo project
-documentation 下面放了各種文檔和教程,最重要的應(yīng)該是Hibernate API, 即 javadocs
-lib 下面有很多二級(jí)目錄,里面放了各種jar包,Hibernate是模塊化的,其中required是Hibernate框架基礎(chǔ)jar包,其他目錄是一些擴(kuò)展包,例如lib\optional\c3p0下面放了數(shù)據(jù)庫連接池的jar包。
另外,還需要下載日志框架包SLF4J,Hibernate會(huì)用它來在執(zhí)行時(shí)候輸出日志。
我下載的是1.6.1版本,可以在官網(wǎng)的數(shù)據(jù)倉庫中找到 http://www.slf4j.org/dist/
2. 導(dǎo)入各種jar包
先在Eclipse中新建一個(gè)project,然后新建一個(gè)user library,例如叫做 hibernate-4-3-11,注意不要勾選system library,否則后面在讀取Hibernate配置文件時(shí)候一直會(huì)報(bào) java.lang.NullPointerException 異常。
導(dǎo)入以下jar包
-hibernate下的 lib\require下的所有jar包(10個(gè)),這是框架基本jar包
-hibernate下的lib\optional\c3p0的所有jar包,這是數(shù)據(jù)庫連接池jar包,為Hibernate框架提供數(shù)據(jù)源
-slf4框架下的slf4j-api-1.6.1.jar (這是api) 和 slf4j-nop-1.6.1.jar (這是具體實(shí)現(xiàn)) 兩個(gè)包
我將所有jar包集中放在了一個(gè)目錄里方便今后遷移,所有jar包如下,
將以上15個(gè)jar都添加進(jìn)user library中去。
3.創(chuàng)建一個(gè)實(shí)體類
New類將要用來與數(shù)據(jù)庫中的一張表對(duì)應(yīng),它只是一個(gè)普通類(POJO),我們放在src/hib路徑下,后面Hibernate將會(huì)根據(jù)配置文件創(chuàng)建數(shù)據(jù)表
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.創(chuàng)建表映射文件
在News類相同的路徑下創(chuàng)建一個(gè)xml文件News.hbm.xml,這個(gè)文件與News.java對(duì)應(yīng),叫做映射文件,是一個(gè)Hibernate將依據(jù)這個(gè)文件操作數(shù)據(jù)庫。
通過某些插件,可以依據(jù)實(shí)體類News.java 自動(dòng)創(chuàng)建News.hbm.xml,不過我還是先收工創(chuàng)建一下。
<?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提供的手冊(cè)(hibernate-release-4.3.11.Final/documentation/manual/en-US/html_single/index.html)1.1.3. The mapping file 中已經(jīng)有詳細(xì)描述,
每一個(gè)持久化的實(shí)體類(例如上面的News.java),都需要有一個(gè)到數(shù)據(jù)表的映射,這里的<class>元素就是一個(gè)映射
表的主鍵用<id>元素表示,其他字段則用<property>元素表示,每個(gè)字段元素中可以添加name, colume, type屬性,分別表示字段名稱和類型
5.創(chuàng)建Hibernate主配置文件
Hibernate配置文件的默認(rèn)名稱是Hibernate.cfg.xml,我們創(chuàng)建這個(gè)文件并放在src根目錄,文件內(nèi)容如下,
<?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> <!--數(shù)據(jù)庫方言--> <!--自動(dòng)建表及打印sql --> <property name="hbm2ddl.auto">update</property> <property name="show_sql">true</property> <mapping resource="hib/News.hbm.xml" /> </session-factory> </hibernate-configuration>
對(duì)上面的關(guān)鍵點(diǎn)解釋如下:
數(shù)據(jù)庫連接字符串:如果要指定字符集,在url后面加上?useUnicode=true&characterEncoding=UTF-8, 但因?yàn)閡rl要放在xml文件中,需要將&符號(hào)轉(zhuǎn)義成"&"
我也使用使用<property name="connection.charset">utf8</property> 這種方式兼容中文,但是好像并不起作用
數(shù)據(jù)庫方言:我使用的是MySQL數(shù)據(jù)庫,最開始我使用的數(shù)據(jù)庫方言配置是org.hibernate.dialect.MySQLInnoDBDialect,但是發(fā)現(xiàn)無法通過Hibernate自動(dòng)建表,后來發(fā)現(xiàn)換成org.hibernate.dialect.MySQLDialect就行了。
所有數(shù)據(jù)庫方言配置可以在手冊(cè)中找到 ,hibernate-release-4.3.11.Final/documentation/manual/en-US/html_single/index.html#tutorial-firstapp-mapping 的 3.4.1. SQL Dialects
是否根據(jù)實(shí)體類和映射文件自動(dòng)建表:<property name="hbm2ddl.auto">update</property>
打印SQL到控制臺(tái):<property name="show_sql">true</property>
6. 創(chuàng)建測(cè)試類
NewsManager也放在hib路徑下,在這個(gè)類中初始化Hibernate執(zhí)行數(shù)據(jù)庫操作
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) { //實(shí)例化Configuration //configure()方法默認(rèn)加載 /hibernate.cfg.xml Configuration conf = new Configuration().configure(); //用Configuration創(chuàng)建SessionFactory SessionFactory sf = conf.buildSessionFactory(); //用SessionFactory打開Session Session sess = sf.openSession(); //開始事務(wù) Transaction tx = sess.beginTransaction(); //創(chuàng)建消息實(shí)例 News n = new News(); //設(shè)置消息標(biāo)題和消息內(nèi)容 n.setTitle("天王蓋地虎"); n.setContent("寶塔鎮(zhèn)河妖"); //保存消息 sess.save(n); //提交事務(wù) tx.commit(); //關(guān)閉session 和 SessionFactory sess.close(); sf.close(); System.out.println("執(zhí)行完畢"); } }
注意上面的Configuration().configure()方法,是從默認(rèn)的路徑src下加載Hibernate配置文件Hibernate.cfg.xml。
啟動(dòng)mysql數(shù)據(jù)庫(確保存在上面配置文件中的數(shù)據(jù)庫名),再在Eclipse中執(zhí)行NewsManager類結(jié)果如下,可以看到在末尾答應(yīng)出了SQL語句,
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 (?, ?) 執(zhí)行完畢
同時(shí)我們查看mysql數(shù)據(jù)庫,發(fā)現(xiàn)在think_blog庫下多了一張表News_table,同時(shí)在表中我們插入了一條數(shù)據(jù),
到此,我們的Hibernate環(huán)境就算是配置成功了,并且成功執(zhí)行了一個(gè)基本的demo。
從測(cè)試類中可以總結(jié)Hibernate的一般步驟,
-加載Hibernate配置文件(Hibernate.cfg.xml,默認(rèn)從src目錄加載),從而獲得Hibernate的Configuration實(shí)例
-通過Configuration的實(shí)例創(chuàng)建Session工廠
-通過Session工廠打開一個(gè)session
-通過session開起一個(gè)事務(wù)
-進(jìn)行實(shí)體類的set或者get操作
-將實(shí)體類的操作結(jié)果保存進(jìn)session
-提交事務(wù)
-關(guān)閉session及session工廠資源
以上步驟完全是面向?qū)ο蟮木幊谭绞?,不直接操作?shù)據(jù)庫,但是通過Hibernate完成了數(shù)據(jù)庫操作,這便是Hibernate的基本原理。
這篇Hibernate之環(huán)境搭建及demo分享就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。