一、引入依赖
在build.gradle文件中的dependencies的对象中引入依赖
implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.4'
二、配置数据库及mybatis
在application.yml文件中配置数据库
spring:
datasource:
url: jdbc:mysql://192.168.0.1:3306/dbName?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&rewriteBatchedStatements=true
username: admin
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
# mybatis的sql xml映射文件
mapper-locations: classpath:mybatis/*Mapper.xml
# 数据库表字段实体
typeAliasesPackage: com.pd.shop.model.entity
三、应用服务配置mapper扫描
@MapperScan(basePackages = "com.pd.shop.mapper")
public class DealerApplication {
public static void main(String[] args) {
SpringApplication.run(DealerApplication.class, args);
}
}
说明: com.pd.shop.mapper 是文件夹路径,文件夹下是接口类,用于调用*Mapper.xml中的数据库sql映射方法。
四、数据表对象实体
package com.pd.shop.model.entity;
import lombok.Data;
@Data
public class UserInfo {
private Long id;
/**
* 用户昵称
*/
private String nickname;
/**
* 1男 0女 -1未知
*/
private Integer sex;
}
五、mybatis的数据库映射文件
UserInfoMapper.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.pd.shop.mapper.UserInfoMapper">
<select id="queryList" resultType="com.pd.shop.model.entity.UserInfo">
SELECT
*
FROM
user_info
</select>
</mapper>
六、Service接口
package com.pd.shop.service;
import com.pd.shop.model.entity.UserInfo;
import java.util.List;
public interface UserInfoService {
List<UserInfo> queryList();
}
七、Service接口实现
package com.pd.shop.service.impl;
import com.pd.shop.mapper.UserInfoMapper;
import com.pd.shop.model.entity.UserInfo;
import com.pd.shop.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserInfoImpl implements UserInfoService {
@Autowired
private UserInfoMapper userInfoMapper;
@Override
public List<UserInfo> queryList(){
return userInfoMapper.queryList();
}
}