首先搭建环境,idea+mySQL+mybatis+springBoot创建的demo。
配置文件
在resources
目录下application.yml
文件中
#端口
server:
port: 8080
#连接本地数据库
spring:
datasource:
url: jdbc:mysql://localhost:3306/student_table?useUnicode=true&&characterEncoding=utf-8&&serverTimezone=UTC #注意设置编码格式
username: root
password: *****
#配置mybatis 该配置节点为独立的节点
mybatis:
mapper-locations: classpath:mybatis/*.xml # 注意:一定要对应mapper映射xml文件的所在路径
type-aliases-package: com.zjh.api.demo.entity # 注意:对应实体类的路径
configuration:
map-underscore-to-camel-case: true # 数据库字段下划线自动转驼峰
然后创建一个mybatis
文件夹,再在下面创建UserMapper.xml
文件,返回数据类型和sql语句
<?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.zjh.api.demo.mapper.UserMapper">
<select id="getUserInfo" resultType="com.zjh.api.demo.entity.UserEntity">
select * from student where teacherId = 1
</select>
</mapper>
创建entity
文件夹,创建UserEntity
文件
@JsonInclude(JsonInclude.Include.NON_NULL)
public class UserEntity {
public String name;
public int year;
public int teacherId;
}
创建mapper
文件夹,创建UserMapper
类
@Repository
public interface UserMapper {
//获取用户信息
List<UserEntity> getUserInfo();
}
创建service
文件夹,创建UserService
类
@Repository
public class UserService {
@Autowired
UserMapper mMapper;
public List<UserEntity> getUserInfo(){
return mMapper.getUserInfo();
}
}
创建controller
文件夹,创建UserController
文件
@RestController
public class UserController {
@Autowired
private UserService mUserService;
@RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
public BaseEntity getUserInfo() {
List<UserEntity> userList = mUserService.getUserInfo();
Map<String, Object> map = new HashMap<>();
map.put("student", userList);
if (userList != null) {
return BaseEntity.success(map);
}
return new BaseEntity().setMsg("请求失败").setState(201);
}
}