1、找到程序的入口:
FrameApplication:运行-----右键--> Run 'FrameApplication'
2.Controller
IndexController
UserController:
package wang.doug.frame.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import wang.doug.frame.model.User;
import wang.doug.frame.service.UserService;
@RestController //说明UserController这个类是一个控制类
@RequestMapping("/testSBoot") //访问这个类的路径(网址)
public class UserController {
@Autowired //相当于new UserService();
private UserService userService; //UserService这个类封装了Mapper(代理)Mapper帮我们去数据库查数据了
/**
* 从数据库中查数据
* UserService Class
* @return
*/
@RequestMapping("/getUser/{id}") //getUser这个方法的路径(网址)/{id}参数的占位符
public User getUser(@PathVariable int id) { //@PathVariable 路径变量接收器
return userService.selById(id);
}
}
3.Service(服务层):UserService这个类封装了Mapper(代理)Mapper帮我们去数据库查数据了,返回的结果是User类型
package wang.doug.frame.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import wang.doug.frame.dao.UserMapper;
import wang.doug.frame.model.User;
@Service
public class UserService {
@Autowired
UserMapper userMapper;
public User selById(int id){
return userMapper.selById(id);
//在这里要注意:需要一个文件UserMapper.xml,当中有真正的查询语句(Statement)
}
}
4.实体类User
package wang.doug.frame.model;
public class User {
private int id;
private String userName;
private String passWord;
private String realName;
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 getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", passWord='" + passWord + '\'' +
", realName='" + realName + '\'' +
'}';
}
}
5、 MyBatis查询数据库的接口: 我们用MyBatis查询数据库,主要就设计这个接口
package wang.doug.frame.dao;
import org.springframework.stereotype.Repository;
import wang.doug.frame.model.User;
@Repository //仓库: 会让MyBatis自动实现未实现的方法
public interface UserMapper {
User selById(int id);
6.配置文件UserMapper.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="wang.doug.frame.dao.UserMapper">
<select id="selById" parameterType="java.lang.Integer" resultType="wang.doug.frame.model.User">
select * from user where id = #{value}
</select>
</mapper>