Hibernate 在 SSH 整合框架中承担了数据库对象管理和持久化的角色,也被称为反向工程。从构建一个 Hibernate 项目到成功通过对象关系映射将数据插入(持久化)到数据库,总共经历了一天一夜,终于在今天凌晨1点搞定……
关于 Hibernate,网上的教程是不少的,但是往往是旧版本,版本不同即使照着教程敲一遍代码,还是运行不起来,因为有些接口已经不用了。 我选择 IDEA-Hibernate5.x-MySQL 这套现在应该掌握的开发工具组合
IDEA 新建 Hibernate5 项目
参考IntelliJ IDEA Hibernate 从入门到填坑
新建项目时要勾选Hibernate框架。如果项目已经建好了就在项目上右击 Add Framework.
- 新建 Hibernate 项目
下面红框里的文件就是生成的Hibernate配置文件,这是 Hibernate 的核心配置文件。
主要用于配置数据库连接和 Hibernate 运行时所需要的各种属性,Hibernate 在初始化期间会自动在 CLASSPATH 中寻找这个文件,并读取其中的配置信息

- 在现有项目中 Add Framework
右击项目,点击 Add Framework Support

点击OK 下载Hibernate依赖库文件
生成数据库实体类
- 我在 src 下创建了一个 package:hibernate_mapping.model.vo,因为数据库实体类都是 POJO 类,Hibernate 旧版教程里习惯上把他们放到 .vo 为名的包下,但是现在更喜欢放在 .entities 包下
- 添加 Database 连接
在IDE右侧找到Database标签页。点开

点击 ? 号:

连接 MySQL 的数据库:
连接成功后点击 OK:
3. 生成持久化 POJO 类
现在我们到IDE左下角找到 Persistence 标签页,并点开它。
在弹出的菜单上右击,生成数据库对象映射类和相应 xml 文件:

在你的包下将会自动生成如下文件:
Hibernate 配置文件
默认生成的hibernate.cfg.xml 内容如下:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory> <property name="connection.url"/> <property name="connection.driver_class"/> <property name="connection.username"/><property name="connection.password"/> <!-- DB schema will be updated if needed --> <!-- <property name="hbm2ddl.auto">update</property> --> </session-factory>
</hibernate-configuration>
下面是我的项目的数据库连接配置:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD//EN""http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration><session-factory><!-- 最好根据 MySQL 的版本选择对应的 hibernate 方言,而不是 MySQLDialect --><property name="dialect">org.hibernate.dialect.MySQL5Dialect</property><!-- 数据库的连接 --><property name="connection.url">jdbc:mysql://localhost:3306/hibernate_mapping</property><property name="connection.username">root</property><property name="connection.password">123456</property><property name="connection.driver_class">com.mysql.jdbc.Driver</property><!-- Hibernate 出名就出名在“反向工程”,下面的 create,MySQL 中的数据库表会在运行程序时被修改成相应数据库映射的 xml 的配置,相当于重建表 --><property name="hibernate.hbm2ddl.auto">create</property><!-- 下面规定了控制台会输出程序运行时生成和执行的 SQL 语句 --><property name="format_sql">true</property><property name="hibernate.show_sql">true</property><!-- <property name="hbm2ddl.auto">update</property> --><!-- <property name="hbm2ddl.auto">create</property> --><!-- 相应的数据库表的映射文件 --><mapping resource="hibernate_mapping/model/vo/DetailEntity.hbm.xml"/><mapping resource="hibernate_mapping/model/vo/LoginEntity.hbm.xml"/><!-- <property name="connection.username"/> --><!-- <property name="connection.password"/> --><!-- DB schema will be updated if needed --><!-- <property name="hbm2ddl.auto">update</property> --></session-factory>
</hibernate-configuration>