1、引入依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.1</version>
</dependency>
2、连接mysql数据库
1、连接数据库
2、指定数据库
3、配置文件
1、实体类
package com.example.demo.entity;
public class User {
private Integer id;
private String name;
private String password;
private String sex;
private String email;
private String qq;
public User(Integer id, String name, String password, String sex, String email, String qq) {
this.id = id;
this.name = name;
this.password = password;
this.sex = sex;
this.email = email;
this.qq = qq;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
}
2、接口类
package com.example.demo.mapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface UserMapping {
public List<User> getAllUser();
}
3、mybatis映射文件
<?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.example.demo.mapper.UserMapping">
<select id="getAllUser" resultType="com.example.demo.entity.User">
select * from user
</select>
</mapper>
4、配置mybatis文件(application.yaml)
(1)接口及其实体类路径
mybatis:
mapper-locations: classpath:mybatis/*.xml
type-aliases-package: com.example.demo.entity
5、controller调用
package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.sql.DataSource;
import java.util.List;
@RestController
public class UserController {
@Autowired
UserMapping userMapping;
@GetMapping("/Alluser")
public List<User> getAllUser(){
List<User> allUser = userMapping.getAllUser();
return allUser;
}
}
6、访问路径及其显示
http://localhost:8080/Alluser