问题描述
在配置Hibernate的数据库连接的Driver,url等参数时,连接失败。我使用的是hibernate 5.1.17的版本,mysql是8.0.11.我之前项目平时使用的DRIVER和url都是连接正常的,但是到了hibernate就不对了
报错语句:
aused by: java.sql.SQLNonTransientConnectionException: Cannot load connection class because of underlying exception: com.mysql.cj.exceptions.WrongArgumentException: Malformed database URL, failed to parse the connection string near '=Asia/Shanghai'.
我平时使用的
Driver:com.mysql.cj.jdbc.Driver
url:jdbc:mysql://localhost:3306/hibernate?useSSL=false&serverTimezone=Asia/Shanghai
问题所在
反正肯定是Driver和URL错了,最后发现是URl错了(在hibernate错,不代表其他地方是错的)
解决方法
在hibernate.cfg.xml 将url更改为:
jdbc:mysql://localhost:3306/hibernate?useSSL=false&serverTimezone=UTC
完整的hibernate.cfg.xml文件:
<?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/hibernate?useSSL=false&serverTimezone=UTC</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">mima</property>
<!--配置hibernate的方言 指定这是哪个数据库-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 下面是可选参数-->
<!-- 打印sql,可以实现将sql语句打印到后台-->
<property name="hibernate.show_sql">true</property>
<!--格式化sql:让上面打印的sql语句更好看,不然默认是都整合为一行 -->
<property name="hibernate.format_sql">true</property>
<!-- 告诉hibernate你的映射文件在那里-->
<mapping resource="com/svllen/hibernate/demo/Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
你如果使用的hibernate是5.3的话,可能你连接数据库的方法有错误(我也没验证过,是在一篇博客中发现的)。以下是解决方法
更改你的调用数据库方法
注释的代码都是之前的代码
//1.加载Hibernate的核心配置文件:hibernate.cfg.xml
//Configuration configuration = new Configuration().configure();
// configuration.addResource("com/svllen/hibernate/demo/Customer.hbm.xml");
StandardServiceRegistry sr=new StandardServiceRegistryBuilder().configure().build();
SessionFactory sessionFactory=new MetadataSources(sr).buildMetadata().buildSessionFactory();
//2.创建一个SessionFactory对象:类似于JDBC中连接池
//SessionFactory sessionFactory = configuration.buildSessionFactory();
//3.通过SessionFactory获取到Session对象:类似于JDBC中的Connection
Session session = sessionFactory.openSession();
//4.手动开启事务
Transaction transaction = session.beginTransaction();
//5.编写代码
Customer customer = new Customer();
customer.setCust_name("张三");
customer.setCust_industry("农业");
customer.setCust_phone("12345");
customer.setCust_level("老总");
session.save(customer);
//6.提交事务
transaction.commit();
//7.资源释放
session.close();
sessionFactory.close();
}