服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - JAVA教程 - Hibernate之环境搭建及demo分享

Hibernate之环境搭建及demo分享

2021-02-18 12:40云中之歌 JAVA教程

下面小编就为大家分享一篇Hibernate之环境搭建及demo,具有很好的参考价值,希望对大家有所帮助

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 异常。

Hibernate之环境搭建及demo分享

导入以下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包如下,

Hibernate之环境搭建及demo分享

将以上15个jar都添加进user library中去。

Hibernate之环境搭建及demo分享

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环境就算是配置成功了,并且成功执行了一个基本的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

延伸 · 阅读

精彩推荐