Hibernate CRUD项目运行报JdbcEnvironment服务创建异常
Hibernate 5.6.9 连接MySQL 8抛出JdbcEnvironment服务创建失败异常修复
你这个异常完全是hibernate.cfg.xml配置错误导致的,没有其他玄学问题,三处配置错误直接导致JDBC环境初始化失败:
具体错误与对应修复
- 错误1:混用容器JNDI数据源配置和本地直连配置
你在本地JavaSE环境跑main方法,没有部署到WebLogic容器,却配置了hibernate.connection.datasource和WebLogic的JNDI初始上下文工厂,Hibernate启动时会优先走JNDI查找数据源,找不到直接抛出服务创建异常。
直接删除以下两行无效配置:<property name="hibernate.connection.datasource">jdbc/myDS</property> <property name="jndi.class">weblogic.jndi.WLInitialContextFactory</property> - 错误2:JDBC连接URL格式错误
你配置的hibernate.connection.url属性值多拼了javax.persistence.jdbc.url=前缀,Hibernate拿到的是非法连接串,根本无法建立数据库连接。同时MySQL 8.x必须配置时区参数,否则会报公共密钥检索、时区不匹配的连带错误。
将URL配置替换为:<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatestudent?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true</property> - 错误3:引用了过时不存在的事务工厂类
你配置的org.hibernate.transaction.JDBCTransactionFactory是Hibernate 3版本的旧类,Hibernate 5.6中已经移除了该类,会触发类加载失败。Hibernate 5默认已经适配本地JDBC事务,不需要额外配置事务工厂。
直接删除以下行:<property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
其他可选优化点
- 当前
hbm2ddl.auto配置为create,每次启动程序都会删除并重建Student表,测试通过后建议改成update,避免表数据被清空。 - 你的代码中手动给主键id赋值为987,由于主键策略配置为
GenerationType.AUTO,Hibernate会自动生成主键id,手动赋值可能引发主键冲突,不需要手动设值的话删掉obj_Student.setId(987);即可。 - POJO类中三个属性没加
@Column注解不影响运行,Hibernate默认会按属性名映射同名字段,不需要额外补注解。
修复后可用配置参考
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatestudent?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">password</property> <property name="hibernate.connection.autocommit">false</property> <property name="connection.pool_size">4</property> <property name="current_session_context_class">thread</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="hbm2ddl.auto">update</property> <mapping class ="com.Student"/> </session-factory> </hibernate-configuration>
替换配置后重新运行main方法即可正常插入数据,控制台会输出对应的建表、插入SQL日志。
内容的提问来源于stack exchange,提问作者Karna79
相关产品推荐
相关产品推荐

