springboot 集成mybatis
1、导入jar包
<!--mybatis连接mysql--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.0</version> </dependency>
2、在application.yml配置数据源(此处是mysql)和 mybatis
#连接数据库 spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&serverTimezone=UTC hikari: username: root password: 123456 mybatis: #配置mapper映射文件 classpath代表resources下 mapper-locations: classpath:mapper/*.xml #打开sql执行日志 configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #所有pojo类所在包路径 type-aliases-package: com.wwc.demo.pojo
3、创建实体类对象
public class UserInfo { private int id; private String userName; private String userPwd; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPwd() { return userPwd; } public void setUserPwd(String userPwd) { this.userPwd = userPwd; } public UserInfo(int id, String userName, String userPwd) { this.id = id; this.userName = userName; this.userPwd = userPwd; } public UserInfo() { } @Override public String toString() { return "UserInfo{" + "id=" + id + ", userName='" + userName + '\'' + ", userPwd='" + userPwd + '\'' + '}'; } }
4、创建dao层使用注解@Mapper
@Mapper public interface UserInfoDao { List<UserInfo> getList(); }
5、创建mybatis映射文件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.wwc.demo.dao.UserInfoDao"> <!-- 结果集与实体类映射--> <resultMap id="userInfoMap" type="com.wwc.demo.pojo.UserInfo"> <id property="id" column="id" javaType="int" jdbcType="INTEGER"></id> <result property="userName" column="user_name" javaType="String" jdbcType="VARCHAR"></result> <result property="userPwd" column="user_pwd" javaType="String" jdbcType="VARCHAR"></result> </resultMap> <select id="getList" resultMap="userInfoMap"> select * from user_info </select> </mapper>
6、数据库创建对应的表
7、启动测试成功