图书管理系统(ssm框架) —— 02数据库连接

2021/8/16 19:07:31

本文主要是介绍图书管理系统(ssm框架) —— 02数据库连接,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

连接数据库

database.properties

jdbc.driver = com.mysql.cj.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
jdbc.username = root
jdbc.password = 123456

spring-mapper.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 1.关联数据库配置文件 -->
    <!-- 通过spring 读取 database.properties文件 -->
    <context:property-placeholder location="classpath:database.properties"/>

    <!-- 2.数据库连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!-- 3.sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 创建sqlSessionFactory -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 绑定Mybatis配置文件 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <!-- 4.配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
    <!-- mybatis-spring提供了MapperScannerConfigurer这个类,它将会查找类路径下的映射器并自动将它们创建成MapperFactoryBean -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 扫描Mapper接口包 -->
        <property name="basePackage" value="com.book.mapper , com.user.mapper , com.borrow.mapper"/>
    </bean>
</beans>

测试数据库是否能连接

点击右侧的Database

点击下方的Test Connection,输入sql的用户名和密码

提示 Server returns invalid timezone. Need to set 'serverTimezone' property.

原因是MySQL驱动中默认时区是UTC,与本地时间(中国)相差八个小时,所以链接不上。
解决方法:
在URL后添加 ?serverTimezone=GMT

连接成功后,选择Schemas
勾选之前创建数据库的名称,点击OK,在右方就会显示之前创建的三个表格



这篇关于图书管理系统(ssm框架) —— 02数据库连接的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程