SpringBoot 整合Mybatis 纯注解
1、创建项目
此时在项目中已经引入了SpringBoot、mybatis和数据库驱动等相关的包。
2、配置数据源
在application.properties中配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
3、编写实体类
public class User {
private Integer id;
private String name;
private Integer age;
//get、set
}
4、编写mapper
从users表中查询数据
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper {
@Select("select * from users where id = #{id}")
User getUser(@Param("id") Integer id);
}
5、编写Service类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
private final UserMapper userMapper;
@Autowired
public UserService(UserMapper userMapper) {
this.userMapper = userMapper;
}
public User getUser(Integer id){
return userMapper.getUser(id);
}
}
6、编写Controller类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class UserController {
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@RequestMapping("/geyUser")
public Map<String,Object> getUser(Integer id){
Map<String,Object> map = new HashMap<>();
User user = userService.getUser(id);
map.put("name",user.getName());
map.put("age",user.getAge());
return map;
}
}
7、程序入口
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication //自动扫描同级目录下的包,自动装配
@MapperScan("cn.pzhu.example.mapper") //扫描映射类
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}