“Hibernate笔记 1:入门(开发步骤)”的版本间差异

来自Wikioe
跳到导航 跳到搜索
 
(未显示同一用户的27个中间版本)
第7行: 第7行:
步骤:
步骤:
# 导入相关 JAR 包;
# 导入相关 JAR 包;
## Hibernate 包;
## Hibernate 依赖包:(位于 Hibernate 源文件中:Hibernate/lib/required/)
## 日志包;(hibernate 本身没有日志输出相关的 jar 包)
##: [[File:Hibernate:JAR包:Hibernate依赖包.png|400px]]
## mysql 驱动包;
## 日志相关包:(hibernate 本身没有日志输出相关的 jar 包)
# 创建实体类;
##: [[File:Hibernate:JAR包:日志相关包.png|400px]]
#* 使用 hibernate 时候,不需要自己手动创建表,hibernate 帮把表创建。
## mysql 驱动包:
##: [[File:Hibernate:JAR包:数据库驱动包.png|400px]]
# '''创建持久化类'''(实体类);
#* 见:<big>'''[[Hibernate笔记_4:核心知识#持久化类的编写规则]]'''</big>
# 创建数据表;
#* 如果配置“hibernate.hbm2ddl.auto”为“update”,则不需要自己手动创建表。
# '''配置映射关系''';(如:“User.hbm.xml”)
# '''配置映射关系''';(如:“User.hbm.xml”)
#: 示例:
#: 示例:
第100行: 第105行:
sessionFactory.close();
sessionFactory.close();
</syntaxhighlight>
</syntaxhighlight>
== 配置文件详解 ==
配置文件是 Hibernate 中相当重要的部分,对于 Hibernate、数据库、orm 等内容的都依赖于配置文件。
1、配置文件格式均为 '''xml''';
2、配置文件中均需要引入 '''dtd''' 约束;
    - (xml 的约束格式包括:dtd、schema,而 Hibernate 的配置文件中均使用 dtd)
=== “映射关系”配置文件 ===
“映射关系”,即:实体类和数据库表一一对应的关系。
关于“''映射关系''配置文件”:
1、''文件名称'' 和 ''位置'' 没有固定要求;
    - 建议:在实体类所在包里面创建,名称为“<实体类名称>.hbm.xml”;
“xxx.hbm.xml”格式:
: <syntaxhighlight lang="xml" highlight="">
...
<hibernate-mapping>
<class name="XXX.XXX.XXX" table="ZZZ">
<id name="xxx" column="zzz">
<generator = "???"></generator>
</id>
<property name="xxx" column="zzz" type="???"></property>
<property name="xxx" column="zzz" type="???"></property>
...
</class>
</hibernate-mapping>
</syntaxhighlight>
# <code>'''<class>'''</code> 用于配置“实体类”与“表”的对应;
#* “name”属性值为“实体类的全路径”;
# <code>'''<id>'''</code> 用于配置“(具有唯一性的)实体类的属性”与“(具有唯一性的)表的字段”的对应;
#* “column”属性可以省略(与“name”一致);
#* <code>'''<generator>'''</code> 用于配置主键的“增长方式”;
#*# '''uuid''';
#*# '''native'''(自增);
# <code>'''<property>'''</code> 用于配置“实体类的属性”与“表的字段”的对应;
#* “column”属性可以省略(与“name”一致);
#* “type”属性用于设置生成表字段的类型(自动对应类型);
示例:“User.hbm.xml”
: <syntaxhighlight lang="xml" highlight="">
...
<hibernate-mapping>
<!-- 实体类和数据库表对应 -->
<class name="cn.itcast.entity.User" table="t_user">
<id name="uid" column="uid">
<generator = "uuid"></generator>
</id>
<property name="username" column="username"></property>
<property name="password" column="password"></property>
<property name="address" column="address"></property>
</class>
</hibernate-mapping>
</syntaxhighlight>
=== Hibernate 核心配置文件 ===
Hibernate 核心配置文件,即“<span style="color: blue">'''hibernate.cfg.xml'''</span>”文件,其名称与位置均是固定的。
关于“Hibernate 核心配置文件”:
1、'''文件名称和位置固定''':
    - 位置:必须位于 src 下。
    - 名称:必须为“hibernate.cfg.xml”。
2、同样需要引入 '''dtd''' 约束;
3、hibernate 操作过程中,只会加载核心配置文件,其他配置文件不会加载。
    - “映射关系配置文件”需要配置到“核心配置文件”中,才会被加载。
“hibernate.cfg.xml”格式:
: <syntaxhighlight lang="xml" highlight="">
...
<hibernate-configuration>
<session-factory>
<!-- 第一部分 数据库信息 -->
...
<!-- 第二部分 hibernate信息 -->
...
<!-- 第三部分 映射文件 -->
<mapping resource="..."/>
<session-factory>
</hibernate-configuration>
</syntaxhighlight>
# 配置数据库信息:
#* 使用不同的数据库驱动(不同版本驱动)时,配置信息可能有差别。【可以从类似“mysql-connector”的包里去找相应内容】
#: 示例:
## 使用“mysql-connector-java-5.0.4-bin.jar”时:
##: <syntaxhighlight lang="xml" highlight="">
<property name="hibernate.connection.driver.class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///hibernate_day01</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">admin</property>
</syntaxhighlight>
## 使用“mysql-connector-java-8.0.11.jar”时:
##: <syntaxhighlight lang="xml" highlight="">
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///hibernate_day02?useSSL=false&amp;serverTimezone=UTC</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">admin</property>
</syntaxhighlight>
# 配置 Hibernate 信息:
#: <syntaxhighlight lang="xml" highlight="">
<!-- 输出底层 sql 语句 -->
<property name="hibernate.show_sql">true</property>
<!-- 输出底层 sql 语句格式 -->
<property name="hibernate.format_sql">true</property>
<!-- hibernate 创建表(update:无则创建,有则更新) -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 配置数据库方言(让 hibernate 框架识别不同数据库特有的方言) -->
<property name="hibernate.dialect">org.hibernate.dialect.MySqlDialect</property>
</syntaxhighlight>
# 配置“映射关系配置文件”:
#* 需要定位到(需要加载的)“映射关系配置文件”所在包的位置。
#: 示例:
#: <syntaxhighlight lang="xml" highlight="">
<mapping resource = "cn/itcast/entity/User.hbm.xml"/>
</syntaxhighlight>
== 核心 API ==
=== Configuration 接口 ===
  Configuration 接口的作用是:对 Hibernate 进行配置、并启动 Hibernate 和连接数据库系统。
Configuration 仅仅是作为一个初始化时的对象,一个 Configeration 实例代表 Hibernate 所有 Java 类到 Sql 数据库映射的集合。
在 Hibernate 的启动过程中,Configuration 类的实例首先定位缺省 XML 配置文件(hibernate.cfg.xml),并读取关的配置项目,然后创建出一个 SessionFactory 对象。
使用:
# 根据默认的 XML 配置文件:
#* 默认加载:src/hibernate.cfg.xml。
#: <syntaxhighlight lang="Java" highlight="">
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sessionFactory = cfg.buildSessionFactory();
</syntaxhighlight>
# 根据自定义的 XML 配置文件:(少用)
#: <syntaxhighlight lang="Java" highlight="">
Configuration cfg = new Configuration();
cfg.configure("cn/config/hibernate2.cfg.xml");
</syntaxhighlight>
=== SessionFactory 接口 ===
SessionFactory 的主要作用是:产生和管理 Session。
通常情况下每一个应用只需要一个 SessionFactory,当需要操作多个数据库时,可以为每个数据库指定一个 SessionFactory。
即:'''“一个 SessionFactory 实例”对应“一个数据存储源”'''。——【'''重量级,整个应用中共享'''】
根据 Configuration 对象创建一个 SessionFactory 对象:
# 在 Hibernate 4 之前:
#: <syntaxhighlight lang="Java" highlight="">
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sessionFactory = cfg.buildSessionFactory();
</syntaxhighlight>
# 在 Hibernate 4 之后:【???】
#: <syntaxhighlight lang="Java" highlight="">
Configuration cfg = new Configuration().configure();
ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
SessionFactory sessionFactory = cfg.buildSessionFactory(sr);
</syntaxhighlight>
SessionFactory 可以通过两种方法产生 Session。
生成 Sessin:
# '''openSession()''':每次打开都是新的 Session,并且需要人为的调用 '''close''' 方法关闭 Session。
#: <syntaxhighlight lang="Java" highlight="">
Session session = sessionFactory.openSession();
</syntaxhighlight>
# '''getCurrentSession()''':从当前上下文中获取 Session 并且会绑定到当前线程:
#: 第一次调用会自动创建一个 Session 实例,如果未手动关闭多次获取的是同一个 Session,事物提交或者回滚时会'''自动关闭''' Session。
#: <syntaxhighlight lang="Java" highlight="">
Session session = sessionFactory.getCurrentSession();
</syntaxhighlight>
#* 需要在配置文件(hibernate.cfg.xml)中添加如下配置:【否则会报错“org.hibernate.HinerbateException: No CurrentSessionContext configured!”】
#*# 如果使用的是'''本地事务'''(JDBC 事务):
#*#: <syntaxhighlight lang="xml" highlight="">
Session session = sessionFactory.getCurrentSession();<property name="current_session_context_class">thread</property>
</syntaxhighlight>
#*# 如果使用的是'''全局事务'''(JTA 事务):
#*#: <syntaxhighlight lang="xml" highlight="">
Session session = sessionFactory.getCurrentSession();<property name="current_session_context_class">jta</property>
</syntaxhighlight>
'''全局事务''':资源管理器管理和协调的事务,可以跨越多个数据库和进程。资源管理器一般使用 XA 二阶段提交协议与“企业信息系统”(EIS)或数据库进行交互。   
'''本地事务''':在单个 EIS 或数据库的本地并且限制在单个进程内的事务。本地事务不涉及多个数据来源。
=== Session ===
Session 用于管理一个数据库的任务单元(增、删、改、查),它是 Java 应用和 Hibernate 之间主要运行接口,是抽象持久性服务概念的主要 API。
【类似于 JDBC 中的连接(“connection”)】
Session 对象是'''非线程安全'''的,因此最好是一个线程只创建一个Session对象(将它设计为局部对象)。
    ——【'''轻量级,不共享''':“一请求”>>“一线程”>>“一session”>>“一事务”】
=== Transaction ===

2022年6月11日 (六) 07:10的最新版本


入门

以下内容展示一个 Hibernate 项目的入门过程。

环境搭建

步骤:

  1. 导入相关 JAR 包;
    1. Hibernate 依赖包:(位于 Hibernate 源文件中:Hibernate/lib/required/)
      Hibernate:JAR包:Hibernate依赖包.png
    2. 日志相关包:(hibernate 本身没有日志输出相关的 jar 包)
      Hibernate:JAR包:日志相关包.png
    3. mysql 驱动包:
      Hibernate:JAR包:数据库驱动包.png
  2. 创建持久化类(实体类);
  3. 创建数据表;
    • 如果配置“hibernate.hbm2ddl.auto”为“update”,则不需要自己手动创建表。
  4. 配置映射关系;(如:“User.hbm.xml”)
    示例:
    ...
    
    <hibernate-mapping>
    	<!-- 实体类和数据库表对应 -->
    	<class name="cn.itcast.entity.User" table="t_user">
    		<id name="uid" column="uid">
    			<generator = "uuid"></generator>
    		</id>
    		<property name="username" column="username"></property>
    		<property name="password" column="password"></property>
    		<property name="address" column="address"></property>
    	</class>
    </hibernate-mapping>
    
  5. 创建 Hibernate 核心配置文件(“hibernate.cfg.xml”);
    示例:
    ...
    
    <hibernate-configuration>
    	<session-factory>
    		
    		<!-- 数据库信息 -->
    		<property name="hibernate.connection.driver.class">com.mysql.jdbc.Driver</property>
    		<property name="hibernate.connection.url">jdbc:mysql:///hibernate_day01</property>
    		<property name="hibernate.connection.username">root</property>
    		<property name="hibernate.connection.password">admin</property>
    
    
    		<!-- hibernate信息 -->
    		<property name="hibernate.show_sql">true</property>
    		<property name="hibernate.format_sql">true</property>
    		<property name="hibernate.hbm2ddl.auto">update</property>
    		<property name="hibernate.dialect">org.hibernate.dialect.MySqlDialect</property>
    		
    		
    		<!-- 映射文件 -->
    		<mapping resource = "cn/itcast/entity/User.hbm.xml"/>
    
    	<session-factory>
    </hibernate-configuration>
    

代码实现

步骤:

  1. 加载 hibernate 核心配置文件:
    	// 到src下面找到名称是hibernate.cfg.xml
    	// 在hibernate里面封装对象
    	Configuration cfg = new Configuration();
    	cfg.configure();
    
  2. 创建 SessionFactory 对象:
    	// 读取 hibernate 核心配置文件内容,创建 sessionFactory
    	// 在过程中,根据映射关系,在配置数据库里面把表创建
    	SessionFactory sessionFactory = cfg.buildSessionFactory();
    
  3. 使用 SessionFactory 创建 session 对象:
    	// 类似于连接
    	Session session = sessionFactory.openSession();
    
  4. 开启事务:
    	Transaction tx = session.beginTransaction();
    
  5. 写具体逻辑 crud 操作:
    	User user = new User();
    	user.setUsername("小马");
    	user.setPassword("123");
    	user.setAddress("美国");
    	
    	session.save(user);
    
  6. 提交事务:
    	tx.commit();
    
  7. 关闭资源:
    	session.close();
    	sessionFactory.close();