Hibernate5.3版本连接MySQL8的一系列问题解决
MySQL8.0以后,用的连接驱动改变了,driver必须加上.cj。如com.mysql.cj.jdbc.Driver。url为jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC。驱动更新为
5.0版本的驱动不能使用。
Hibernate的hibernate.cfg.xml配置为
<!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="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
<mapping resource="com/pojo/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
注意:&符号在Hibernate不可用,需写成&使用MySQL8Dialect
User.hbm.xml配置为
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.pojo.User" table="hbm">
<id name="id">
<generator class="native"/>
</id>
<property name="name"></property>
<property name="psw"></property>
</class>
</hibernate-mapping>
在Hibernate5.3下,需要使用新的方法建立SessionFactory,4.3版本下的方法会报错
package com.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
//import org.hibernate.cfg.Configuration;
import com.pojo.User;
public class Test01 {
public static void main(String[] args) {
// Configuration cfg = new Configuration().configure();
// ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
// SessionFactory sf = cfg.buildSessionFactory(sr);
StandardServiceRegistry sr=new StandardServiceRegistryBuilder().configure().build();
SessionFactory sf=new MetadataSources(sr).buildMetadata().buildSessionFactory();
Session session = sf.openSession();
Transaction ts = session.beginTransaction();
User user = new User();
user.setName("王五");
user.setPsw("333");
session.save(user);
ts.commit();
}
}
注意:注释掉的为4.3版本的方法,不可用。导包切记不要导错。
此内容为本人多次查阅网上资料整理出来。