1.确定需求、
输入:前端访问http://localhost:8080/hello
输出:前端显示后端从数据库读取的数据
2.新建项目的子模块
新建模块mybatis
3.MySQL 数据库配置、添加数据
创建数据库, 添加表, 添加表的字段, 添加数据
4.编写代码
新建controller、service、mapper、domain 包
新建mapper 资源目录
新建controller、service、mapper、domain 对应的Java 文件
新建mapper 资源目录Java mapper 对应的XML 文件
controller
import com.example.mybatis.domain.User;
import com.example.mybatis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class HelloController {
@Autowired
private UserService userService;
@GetMapping("/hello")
public List<User> hello()
{
return userService.selectAllUser();
}
}
service
public class User {
public int id;
private String name;
private int age;
public String sex;
public String createTime;
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
@Override
public String toString(){
return "User{"+
"id="+id+
", name '" + name + '\''+
", age="+ age+
", sex="+ sex+
",createTime='" + createTime +'\''+
'}';
}
}
mapper
import com.example.mybatis.domain.User;
import java.util.List;
public interface UserMapper {
public List<User> selectAllUser();
}
domain
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.mybatis.mapper")
public class MybatisApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisApplication.class, args);
}
}
5.编译代码、构建程序、执行SpringBoot 程序
7.测试SpringBoot 后端接口