• 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包,其他目录是一些扩展包,例如liboptionalc3p0下面放了数据库连接池的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 equire下的所有jar包(10个),这是框架基本jar包

    -hibernate下的liboptionalc3p0的所有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 package hib;
     2 
     3 public class News {
     4     public int getId() {
     5         return id;
     6     }
     7     public void setId(int id) {
     8         this.id = id;
     9     }
    10     public String getTitle() {
    11         return title;
    12     }
    13     public void setTitle(String title) {
    14         this.title = title;
    15     }
    16     public String getContent() {
    17         return content;
    18     }
    19     public void setContent(String content) {
    20         this.content = content;
    21     }
    22     private int id;
    23     private String title;
    24     private String content;
    25     
    26 }

    4.创建表映射文件

    在News类相同的路径下创建一个xml文件News.hbm.xml,这个文件与News.java对应,叫做映射文件,是一个Hibernate将依据这个文件操作数据库。

    通过某些插件,可以依据实体类News.java 自动创建News.hbm.xml,不过我还是先收工创建一下。

     1 <?xml version="1.0"  encoding="UTF-8"?>    
     2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
     3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
     4 
     5 <hibernate-mapping package="hib">
     6     <class name="News" table="news_table">
     7         <id name="id" column="id">
     8             <generator class="identity" />
     9         </id>
    10         <property name="title" type="string" column="title" />
    11         <property name="content" type="string" column="content" />
    12     </class>
    13 </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 <?xml version="1.0" encoding="UTF-8"?>  
     2 <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
     3                                          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
     4 
     5 <hibernate-configuration>
     6     <session-factory>
     7     
     8         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
     9         <property name="connection.url">jdbc:mysql://127.0.0.1:3306/think_blog?useUnicode=true&amp;characterEncoding=UTF-8</property> <!-- 指定字符集的方式-->
    10         <property name="connection.username">root</property>
    11         <property name="connection.password"></property> 
    12 
    13         <property name="hibernate.c3p0.max_size">20</property>
    14         <property name="hibernate.c3p0.min_size">1</property>
    15     
    16         <property name="hibernate.c3p0.timeout">5000</property>
    17     
    18         <property name="hibernate.c3p0.max_statements">100</property>
    19         <property name="hibernate.c3p0.idle_test_period">3000</property>
    20         <property name="hibernate.c3p0.acquire_increment">2</property>
    21         <property name="hibernate.c3p0.validate">true</property>
    22         <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!--数据库方言-->
    23       <!--自动建表及打印sql -->
    24         <property name="hbm2ddl.auto">update</property>
    25         <property name="show_sql">true</property>
    26         <mapping resource="hib/News.hbm.xml" />
    27     </session-factory>
    28 </hibernate-configuration>

     对上面的关键点解释如下:

    • 数据库连接字符串:如果要指定字符集,在url后面加上?useUnicode=true&characterEncoding=UTF-8, 但因为url要放在xml文件中,需要将&符号转义成"&amp;"
    • 我也使用使用<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 package hib;
     2 
     3 import org.hibernate.Session;
     4 import org.hibernate.SessionFactory;
     5 import org.hibernate.Transaction;
     6 import org.hibernate.cfg.Configuration;
     7 
     8 public class NewsManager {
     9     public static void main(String[] args) {
    10         //实例化Configuration
    11         //configure()方法默认加载  /hibernate.cfg.xml
    12         Configuration conf = new Configuration().configure();
    13         //用Configuration创建SessionFactory
    14         SessionFactory sf = conf.buildSessionFactory();
    15         //用SessionFactory打开Session
    16         Session sess = sf.openSession();
    17         //开始事务
    18         Transaction tx = sess.beginTransaction();
    19         //创建消息实例
    20         News n = new News();
    21         //设置消息标题和消息内容
    22         n.setTitle("天王盖地虎");
    23         n.setContent("宝塔镇河妖");
    24         //保存消息
    25         sess.save(n);
    26         //提交事务
    27         tx.commit();
    28         //关闭session 和 SessionFactory
    29         sess.close();
    30         sf.close();    
    31         System.out.println("执行完毕");
    32     }
    33 }

    注意上面的Configuration().configure()方法,是从默认的路径src下加载Hibernate配置文件Hibernate.cfg.xml。

    启动mysql数据库(确保存在上面配置文件中的数据库名),再在Eclipse中执行NewsManager类结果如下,可以看到在末尾答应出了SQL语句,

     1 Dec 23, 2016 2:57:38 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
     2 INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
     3 Dec 23, 2016 2:57:38 PM org.hibernate.Version logVersion
     4 INFO: HHH000412: Hibernate Core {4.3.11.Final}
     5 Dec 23, 2016 2:57:38 PM org.hibernate.cfg.Environment <clinit>
     6 INFO: HHH000206: hibernate.properties not found
     7 Dec 23, 2016 2:57:38 PM org.hibernate.cfg.Environment buildBytecodeProvider
     8 INFO: HHH000021: Bytecode provider name : javassist
     9 Dec 23, 2016 2:57:38 PM org.hibernate.cfg.Configuration configure
    10 INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
    11 Dec 23, 2016 2:57:38 PM org.hibernate.cfg.Configuration getConfigurationInputStream
    12 INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
    13 Dec 23, 2016 2:57:38 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
    14 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!
    15 Dec 23, 2016 2:57:38 PM org.hibernate.cfg.Configuration addResource
    16 INFO: HHH000221: Reading mappings from resource: hib/News.hbm.xml
    17 Dec 23, 2016 2:57:39 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
    18 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!
    19 Dec 23, 2016 2:57:39 PM org.hibernate.cfg.Configuration doConfigure
    20 INFO: HHH000041: Configured SessionFactory: null
    21 Dec 23, 2016 2:57:39 PM org.hibernate.c3p0.internal.C3P0ConnectionProvider configure
    22 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
    23 Dec 23, 2016 2:57:39 PM org.hibernate.c3p0.internal.C3P0ConnectionProvider configure
    24 INFO: HHH000046: Connection properties: {user=root, password=****}
    25 Dec 23, 2016 2:57:39 PM org.hibernate.c3p0.internal.C3P0ConnectionProvider configure
    26 INFO: HHH000006: Autocommit mode: false
    27 Dec 23, 2016 2:57:39 PM com.mchange.v2.log.MLog <clinit>
    28 INFO: MLog clients using java 1.4+ standard logging.
    29 Dec 23, 2016 2:57:39 PM com.mchange.v2.c3p0.C3P0Registry banner
    30 INFO: Initializing c3p0-0.9.2.1 [built 20-March-2013 10:47:27 +0000; debug? true; trace: 10]
    31 Dec 23, 2016 2:57:39 PM com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager
    32 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 ]
    33 Dec 23, 2016 2:57:40 PM org.hibernate.dialect.Dialect <init>
    34 INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
    35 Dec 23, 2016 2:57:40 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
    36 INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
    37 Dec 23, 2016 2:57:40 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
    38 INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
    39 Dec 23, 2016 2:57:40 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
    40 INFO: HHH000397: Using ASTQueryTranslatorFactory
    41 Dec 23, 2016 2:57:40 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
    42 INFO: HHH000228: Running hbm2ddl schema update
    43 Dec 23, 2016 2:57:40 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
    44 INFO: HHH000102: Fetching database metadata
    45 Dec 23, 2016 2:57:40 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
    46 INFO: HHH000396: Updating schema
    47 Dec 23, 2016 2:57:40 PM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
    48 INFO: HHH000262: Table not found: news_table
    49 Dec 23, 2016 2:57:40 PM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
    50 INFO: HHH000262: Table not found: news_table
    51 Dec 23, 2016 2:57:40 PM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
    52 INFO: HHH000262: Table not found: news_table
    53 Dec 23, 2016 2:57:40 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
    54 INFO: HHH000232: Schema update complete
    55 Hibernate: insert into news_table (title, content) values (?, ?)
    56 执行完毕
    View Code

    同时我们查看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的基本原理。

  • 相关阅读:
    scrapy爬取相似页面及回调爬取问题(以慕课网为例)
    爬取网易云课堂、网易公开课课程数据
    用户行为数据分析笔记
    redis学习笔记
    索引原理及几种索引类型区别
    平衡二叉树,B树,B+树的概念及区别
    RF, GBDT, XGB区别
    无偏估计
    Redis分布式锁的正确实现方式
    Mybatis 你了解多少?
  • 原文地址:https://www.cnblogs.com/fysola/p/6215051.html
Copyright © 2020-2023  润新知