SpringBoot整合mybatis简单案例过程解析
人气:0这篇文章主要介绍了SpringBoot整合mybatis简单案例过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
1.在springboot项目中的pom.xml中添加mybatis的依赖
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency>
2.在src/main/resources/application.yml中配置数据源信息
# DB Configation spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT username: root password: root # JAPConfigration jpa: database: mysql show-sql: true generate-ddl: true
在连接数据库的过程中可能会出现SQLException,可能是时区问题导致的,加上url路径后面的“serverTimezone = GMT”即可
3.在主启动类的同级创建po包和mapper包,在po包中创建实体类,编写pojo;在mapper包中创建mapper接口和mapper映射文件
mapper.java
package com.hxy.springbootdemo1.demo.mapper; import com.hxy.springbootdemo1.demo.pojo.MUser; import java.util.List; public interface UserMapper { List<MUser> getUserList(); }
mapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.hxy.springbootdemo1.demo.mapper.UserMapper"> <select id="getUserList" resultType="com.hxy.springbootdemo1.demo.pojo.MUser"> select * from user </select> </mapper>
4.手动配置mybatis的包扫描
在主启动类添加@MapperScan
如果出现错误:org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.offcn.mapper.UserMapper.getUserList
有如下两种方法解决:
1 把映射文件 放到resources 目录下 结构目录一模一样
2 修改配置文件pom.xml
<build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.*</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
您可能感兴趣的文章:
加载全部内容