SpringBoot 整合 hibernate 连接 Mysql 数据库


前一篇搭建了一个简易的 SpringBoot Web 项目,最重要的一步连接数据库执行增删改查命令!

经过了一天的摸爬滚打,终于成功返回数据!

因为原来项目使用的 SpringMVC + Hibernate5,所以我这里希望继续原来的继续使用,但是现在网上好多都是 SpringBoot + Mybatis 的配置和整合,我没有了解过 Mybatis 和 Hibernate5 哪个更好,看了网上一大堆介绍 Mybatis 的文章后,依旧没明白它好在哪里,如果有大佬愿意希望可以用白话在评论区留下你的见解!

老规矩还是先看一下依赖包 pom.xml 文件

        
            org.springframework.boot
            spring-boot-starter-data-jpa
        
        
            mysql
            mysql-connector-java
        
        
        
            com.alibaba
            druid
            1.1.24
        
pom.xml

 我习惯使用原来的 .xml 配置文件,所以我并没有像网上大部分说的那样直接在 application.properties 文件中写数据库的配置信息

我在 resource/config 下新建一个 applicationContext.xml 文件 【注:千万不能使用 application.xml 文件命名,用这个为 .xml 命名项目是不能读取的!!!】

application.xml文件无法读取亲测失败!!!    抓耳挠腮半天才知道不能这样命名

<?xml version="1.0" encoding="UTF-8"?>

       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/util
       https://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/cache
        http://www.springframework.org/schema/cache/spring-cache.xsd">
    class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
    
    class="freemarker.template.utility.XmlEscape"/>

    class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
        
        
    
    
    
    class="com.alibaba.druid.pool.DruidDataSource"  init-method="init" destroy-method="close">
        
        
        
        

        
        
        
        
        
        
        
        

        
        
        
        
        
        
        
        

        
        
        
        
        
        
        
    
    class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        
        
        
            
                com.seventeen.entity*
            
        
        
            
                ${jdbc.url}
                ${jdbc.driver}
                ${hibernate.connection.autocommit}
                ${hibernate.show_sql}
                ${hibernate.format_sql}
                ${hibernate.dialect}
                ${jdbc.autoReconnect}
            
        
    

    class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        
    

    class="com.google.code.kaptcha.impl.DefaultKaptcha">
        
            class="com.google.code.kaptcha.util.Config">
                
                    
                        no
                        105,179,90
                        black
                        90
                        35
                        46
                        code
                        4
                        宋体,楷体,微软雅黑
                        com.google.code.kaptcha.impl.ShadowGimpy
                        com.google.code.kaptcha.impl.NoNoise
                    
                
            
        
    

    
applicationContext.xml

同时还有 app.properties 、 hibernate.cfg.xml 以及 jdbc.properties

<?xml version="1.0" encoding="utf-8"?>
configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

    
        jdbc:mysql://127.0.0.1:3306/hk_room_kfyyxt
        com.mysql.jdbc.Driver
    
hibernate.cfg.xml
ResPhysicalPath=E:\\cache
ForbidFileType=exe,dll,java,php,js,ftl,jar,sh,bat,shell,msi,sql
UploadImageExt=jpg,png,gif,jpeg,PNG,JPG
UploadImageSize=2
UploadFileExt=jpg,png,gif,jpeg,bmp,pdf,doc,docx,ppt,pptx,xls,xlsx,zip,rar,txt
UploadFileSize=50
UploadFileSizeEnter=500
UploadImageSizeEnter=10
baseView=/WEB-INF/views
app.properties
jdbc.url=jdbc:mysql://127.0.0.1/hk_room_kfyyxt?serverTimezone=Asia/Shanghai
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.username=root
jdbc.password=root
jdbc.autoReconnect=true
dbcp.initialSize=10
dbcp.maxActive=20
dbcp.minIdle=10
dbcp.maxIdle=0
dbcp.maxWait=60000
dbcp.defaultAutoCommit=true
dbcp.removeAbandoned=true
dbcp.removeAbandonedTimeout=1800
dbcp.logAbandoned=true
dbcp.timeBetweenEvictionRunsMillis=60000
dbcp.minEvictableIdleTimeMillis=300000
dbcp.whenExhaustedAction=1
dbcp.validationQuery=select 1
dbcp.testWhileIdle=true
dbcp.testOnBorrow=true
dbcp.testOnReturn=false
dbcp.poolPreparedStatements=false
dbcp.maxPoolPreparedStatementPerConnectionSize=20
dbcp.filters=stat
dbcp.timeBetweenLogStatsMillis=600000
hibernate.hbm2ddl.auto=none
#指定是否打印SQL语句
hibernate.show_sql=false
#格式SQL语句
hibernate.format_sql=true
#自动提交
hibernate.connection.autocommit=true
#dialect注册mysql方法
hibernate.dialect=com.seventeen.core.database.MySQLDialectReg
jdbc.properties

之后我就开始编写函数调用对数据库进行增删改查,我以为这样就可以结束了,但是万万没想到最难的出现了!!!

下面是我写的调用数据库,因为和原来差别不大只展示一下目录:

 我以为完事大吉了,但是出现了一个纠结我半天的问题!!!

我用浏览器访问了,我刚才写的,出现了下面的错误:

 org.springframework.orm.jpa.EntityManagerHolder cannot be cast to org.springframework.orm.hibernate5.SessionHolder

这个问题我上网搜了好久,但是并没有找到有效的解决办法,后来经过不断试验,终于找到了方法。

修改入口文件 :

/**
 * 否则报错:java.lang.ClassCastException:
 *             org.springframework.orm.jpa.EntityManagerHolder cannot be cast to org.springframework.orm.hibernate5.SessionHolder
 */
@SpringBootApplication(exclude= HibernateJpaAutoConfiguration.class)
@ImportResource(locations={"classpath:/config/applicationContext.xml"})
public class KfyyxtApplication {

    public static void main(String[] args) {
        SpringApplication.run(KfyyxtApplication.class, args);
    }

}

原来是  @SpringBootApplication ,经过各种文章讲解终于找得了解决方法,之后再次访问页面终于成功了!!!

到此,SpringBoot 项目 整合 Hibernate 连接 Mysql 数据库成功,但是我依旧没明白  @SpringBootApplication(exclude= HibernateJpaAutoConfiguration.class) 这段代码究竟是什么意思,有大神希望可以给解答一下!