连接数据库
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,在右方就会显示之前创建的三个表格