Hibernate 环境搭建 Hibernate之环境搭建及demo分享
云中之歌 人气:0ORM概念
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将会根据配置文件创建数据表
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,不过我还是先收工创建一下。
<?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根目录,文件内容如下,
<?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执行数据库操作
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语句,
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分享就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
加载全部内容