适用于MySQL 8和Hibernate 5的示例hibernate.cfg.xml

本文提供了适用于MySQL 8和Hibernate 5的hibernate.cfg.xml配置示例,强调了在生产环境中正确设置Hibernate方言和数据库驱动的重要性,特别是对于不使用JPA仅依赖Hibernate的应用程序。
摘要由CSDN通过智能技术生成

最近在TheServerSide上有一篇文章,希望能提醒Hibernate和JPA开发人员,他们在persistence.xml文件中使用了正确的Hibernate方言和数据库驱动程序。

在生产环境中,有许多应用程序专门使用Hibernate框架而不使用JPA。 这就是为什么我认为使用Hibernate 5发行版中的类为MySQL 8提供示例hibernate.cfg.xml也是有帮助的。

HibernateMySQL方言

最新的Hibernate 5版本包含更新的方言类,必须在MySQL 8的hibernate.cfg.xml文件中引用该类。

<property name ="dialect"> org.hibernate.dialect.MySQL8Dialect </property> 

可以在hibernate.cfg.xml中为MySQL指定许多不同的方言。要选择的正确方言取决于使用的MySQL版本和正在使用的数据库引擎的类型,例如MyISAM或InnoDB 。 如果开发人员未能选择正确的方言,则将在运行时导致无法预测的Hibernate查询结果。

正确的Hibernate MySQL驱动程序

现代MySQL的hibernate.cfg.xml文件所需的另一个更新是对JDBC驱动程序类的更改。

<property name ="connection.driver_class"> com.mysql.cj.jdbc.Driver </property> 

该驱动程序不是Hibernate发行版的一部分,而是作为MySQL网站上提供的JDBC驱动程序包的一部分提供的。

适用于MySQL的示例hibernate.cfg.xml

当开发人员将所有内容放在一起时,一个示例MySQL 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">
<!-- Version 8 MySQL hiberante-cfg.xml example for Hibernate 5 -->
<hibernate-configuration>
  <session-factory>
    <property name ="connection.driver_class"> com.mysql.cj.jdbc.Driver </property>
    <!-- property name="connection.driver_class">com.mysql.jdbc.Driver</property -->
    <property name ="connection.url"> jdbc:mysql://localhost/database </property>
    <property name ="dialect"> org.hibernate.dialect.MySQL8Dialect </property>
    <property name ="connection.username"> root </property>
    <property name ="connection.password"> password </property>
    <property name ="connection.pool_size"> 3 </property>
    <!--property name="dialect">org.hibernate.dialect.MySQLDialect</property-->
    <property name ="current_session_context_class"> thread </property> 
    <property name ="show_sql"> true </property>
    <property name ="format_sql"> true </property>
    <property name ="hbm2ddl.auto"> update </property>
    <!-- mapping class="com.mcnz.jpa.examples.Player" / -->
  </session-factory>
</hibernate-configuration> 

这个MySQL hibernate.cfg.xml示例包括用于生成和格式化SQL的可选设置,以及在任何实体bean需要它们时创建数据库表的说明。

您可以在我的GitHub帐户上找到可正常工作的Hibernate Web应用程序的源代码,该应用程序将此示例hibernate.cfg.xml用于MySQL

翻译自: https://www.theserverside.com/blog/Coffee-Talk-Java-News-Stories-and-Opinions/An-example-hibernatecfgxml-for-MySQL-8-and-Hibernate-5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值