SpringBoot 整合 hibernate 连接 Mysql 数据库

时间:2024-01-28 15:44:49

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

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

 

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

 

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.24</version>
        </dependency>
pom.xml

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

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

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

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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">
    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
    <!--freemarker method-->
    <bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape"/>
<!--    <util:properties id="dbConfig" location="classpath:/config/hibernate/jdbc.properties"  local-override="true"/>-->
    <bean id="dbConfig" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
        <property name="locations" value="classpath:/config/hibernate/jdbc.properties"/>
    </bean>
    <!--  <context:property-placeholder location="classpath:/config/hibernate/jdbc.properties" />-->
    <!-- 添加sessionFactory bane ,注意,该类是Spring提供的 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"  init-method="init" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />

        <property name="initialSize" value="${dbcp.initialSize}" />
        <property name="maxActive" value="${dbcp.maxActive}" />
        <property name="minIdle" value="${dbcp.minIdle}" />
        <property name="maxWait" value="${dbcp.maxWait}" />
        <property name="defaultAutoCommit" value="${dbcp.defaultAutoCommit}" />
        <property name="removeAbandoned" value="${dbcp.removeAbandoned}" />
        <property name="removeAbandonedTimeout" value="${dbcp.removeAbandonedTimeout}" />
        <property name="logAbandoned" value="${dbcp.logAbandoned}"/>

        <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="${dbcp.timeBetweenEvictionRunsMillis}" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="${dbcp.minEvictableIdleTimeMillis}" />
        <property name="validationQuery" value="${dbcp.validationQuery}" />
        <property name="testWhileIdle" value="${dbcp.testWhileIdle}" />
        <property name="testOnBorrow" value="${dbcp.testOnBorrow}" />
        <property name="testOnReturn" value="${dbcp.testOnReturn}" />

        <!-- 打开PSCache,并且指定每个连接上PSCache的大小 如果用Oracle,则把poolPreparedStatements配置为true,mysql可以配置为false。分库分表较多的数据库,建议配置为false。-->
        <property name="poolPreparedStatements" value="${dbcp.poolPreparedStatements}" />
        <property name="maxPoolPreparedStatementPerConnectionSize" value="${dbcp.maxPoolPreparedStatementPerConnectionSize}" />
        <!--        <property name="timeBetweenLogStatsMillis" value="${dbcp.timeBetweenLogStatsMillis}" />-->
        <!--        <property name ="statLogger" ref ="localStatLogger" />-->
        <!-- 配置监控统计拦截的filters -->
        <property name="filters" value="${dbcp.filters}" />
    </bean>
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 注入Hibernate 配置文件路径,前面要加上  classpath:-->
        <property name="packagesToScan">
            <list>
                <value>com.seventeen.entity*</value><!-- 载入hibernate的jpa注解形式的实体类 -->
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.connection.url">${jdbc.url}</prop>
                <prop key="hibernate.connection.driver_class">${jdbc.driver}</prop>
                <prop key="hibernate.connection.autocommit">${hibernate.connection.autocommit}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.autoReconnect">${jdbc.autoReconnect}</prop>
            </props>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

    <bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
        <property name="config">
            <bean class="com.google.code.kaptcha.util.Config">
                <constructor-arg>
                    <props>
                        <prop key="kaptcha.border">no</prop>
                        <prop key="kaptcha.border.color">105,179,90</prop>
                        <prop key="kaptcha.textproducer.font.color">black</prop>
                        <prop key="kaptcha.image.width">90</prop>
                        <prop key="kaptcha.textproducer.font.size">35</prop>
                        <prop key="kaptcha.image.height">46</prop>
                        <prop key="kaptcha.session.key">code</prop>
                        <prop key="kaptcha.textproducer.char.length">4</prop>
                        <prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop>
                        <prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.ShadowGimpy</prop>
                        <prop key="kaptcha.noise.impl">com.google.code.kaptcha.impl.NoNoise</prop>
                    </props>
                </constructor-arg>
            </bean>
        </property>
    </bean>

    <util:properties id="appProperties" location="classpath:/config/app/app.properties"  local-override="true"/>
</beans>
applicationContext.xml

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

<?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="connection.url">jdbc:mysql://127.0.0.1:3306/hk_room_kfyyxt</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    </session-factory>
</hibernate-configuration>
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) 这段代码究竟是什么意思,有大神希望可以给解答一下!