Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装。使得Java程序员可以运用面向对象的思想对数据库进行操作。
一、hibernate的使用
- 使用hibernate首先需要一个java工程。
- 之后创建一个lib文件夹,导入hibernate所需要的jar包。
- 所需jar包可在hibernate的官网上进行下载
- 做完这些之后就可以进行使用hibernate了。
- 首先,需要对hibernate进行一个基本的配置。
- 在src下创建一个hibernate.cfg.xml。写入如下配置
<?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="hibernate.connection.username">root</property><!-- 用户名 -->
<property name="hibernate.connection.password">root</property><!-- 密码 -->
<property name="hibernate.connection.driver_classurl">com.mysql.jdbc.Driver</property><!-- 数据库驱动 -->
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_test</property><!--数据库地址 -->
<!-- 配置hibernate的基本信息 -->
<!-- hibernate所使用的数据库方言 -->
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<!--执行操作时是否在控制台输出SQL -->
<property name="show_sql">true</property>
<!-- 是否都SQL进行格式化 -->
<property name="format_sql">true</property>
<!-- 指定自动生成数据表的策略 -->
<property name="hbm2ddl.auto">update</property>
<!-- 指定关联文件 -->
<mapping resource=""/>
</session-factory>
</hibernate-configuration>
- hibernate.cfg.xml的配置大致可以分为:数据库的基本信息、hibernate的基本信息 .
- 数据库的基本信息:用户名,密码,数据库驱动 ,数据库地址 。
- hibernate的基本信息:hibernate所使用的数据库方言,执行操作时是否在控制台输出SQL,是否都SQL进行格式化,生成数据表的策略 update creat,指定关联文件。
注意:数据库基本信息需要根据使用者的数据库进行配置。编者这里使用的是MySql数据库。数据库的方言也需要根据本地数据库进行配置。具体配置请参考:hibernate-release-5.0.6.Final\hibernate-release-5.0.6.Final\project\etc\hibernate.properties 文件。
总结:基础的配置文件就写好了。在写的时候大家也可以参考hibernate-release-5.0.6.Final\hibernate-release-5.0.6.Final\project\etc\hibernate.cfg.xml文件。