2、配置数据源和Mapper.xml文件位置org.mybatis.spring.boot mybatis-spring-boot-starter2.2.2 mysql mysql-connector-java
# application-dev.properties spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/login?useUnicode=true&characterEncoding=utf-8&useSSL=false spring.datasource.username=root spring.datasource.password=root123 mybatis.mapper-locations:classpath:mapping/*.xml3、创建目录结构如下 4、编写代码实现getUserById 4.1 编写实体类User
package com.galago.demo_web.entry;
public class User {
private Integer id;
private String username;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer 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;
}
}
4.2 编写UserMapper接口——dao层(数据持久层)
package com.galago.demo_web.mapper;
import com.galago.demo_web.entry.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
@Mapper // 该注解可以帮助mybatis找到mapper接口,生成动态代理类。或者在启动文件配置@MapperScan
public interface UserMapper {
User getUser(Integer id);
}
4.3 编写UserMapper.xml
select * from t_user where id = #{id}
注意:resources/mapping目录下的xml文件名需和Mapper接口名一致
4.4 编写UserService接口——Service层
package com.galago.demo_web.services;
import com.galago.demo_web.entry.User;
import com.galago.demo_web.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
public interface UserService {
User getUser(Integer id);
}
4.5 编写UserServiceImpl实现类——service层
package com.galago.demo_web.impl;
import com.galago.demo_web.entry.User;
import com.galago.demo_web.mapper.UserMapper;
import com.galago.demo_web.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserserviceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getUser(Integer id) {
return userMapper.getUser(id);
}
}
4.6 编写UserController类——Controller层
package com.galago.demo_web.controller;
import com.galago.demo_web.entry.User;
import com.galago.demo_web.impl.UserserviceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@RequestMapping("/user") // 此处表示该类中所有相应请求的方法都是以该地址作为父地址, /user/selectone
@Controller
public class UserController {
@Autowired
UserserviceImpl userserviceImpl;
@RequestMapping("/selectone")
@ResponseBody // 返回值转为json数据
public User getUser(Integer id) {
System.out.println(id);
return userserviceImpl.getUser(id);
}
}
5、测试:



