配置 hibernate.cfg.xml 是 Hibernate 入门最关键的一步,需严格遵循 DTD 规范,正确设置数据库连接四要素、方言、自动建表策略、SQL 输出及映射声明。

配置 hibernate.cfg.xml 是 Hibernate 入门最关键的一步,它相当于整个 ORM 框架的“启动说明书”。只要把数据库连接、方言、映射关系这几项配对,后续的增删改查就能自动运转。
这个 XML 文件必须符合 Hibernate 的 DTD 规范,开头声明和根节点要写全:
<?xml version="1.0" encoding="UTF-8"?><hibernate-configuration></hibernate-configuration>,里面只允许一个 <session-factory></session-factory>
这是最常出错的部分,四项缺一不可,且名称要带 hibernate. 前缀(新版本推荐)或直接用旧名(如 connection.url),但别混用:
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>(MySQL 8+ 用 cj,老版本用 com.mysql.jdbc.Driver)<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8</property>(URL 中务必加时区和编码参数,否则中文乱码或时间异常)<property name="hibernate.connection.username">root</property><property name="hibernate.connection.password">your_password</property>这几项不配好,程序可能连表都建不出来,或者 SQL 完全看不到:
<property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>(必须和数据库版本匹配,MySQL 5.7 用 MySQL5InnoDBDialect,8.0+ 推荐 MySQL8Dialect)<property name="hibernate.hbm2ddl.auto">update</property>(开发阶段常用:create 每次重建,validate 只校验,none 关闭自动管理)<property name="hibernate.show_sql">true</property> 和 <property name="hibernate.format_sql">true</property>(调试必备,让控制台输出可读 SQL)<property name="hibernate.current_session_context_class">thread</property>(保证同一线程内 Session 复用,避免频繁 open/close)Hibernate 不会自动扫描所有类,必须告诉它哪些实体需要管理:
配完保存为 src/main/resources/hibernate.cfg.xml,确保在 classpath 根路径下。Hibernate 启动时会自动加载它——不需要手动指定路径。
以上就是hibernate.cfg.xml文件怎么配置 Hibernate入门教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号