- 一、基础工作
- 二、springboot整合mybatis案例
1、创建项目springboot项目,勾选JDBC+MySQL驱动
2、导入mybatis-springboot-starter依赖
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.2.2
这里应该注意版本对应
3、编写application.properties配置文件
#数据库配置 根据自己数据库username和password修改
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#整合mybatis
mybatis.type-aliases-package=com.kuang.pojo #给pojo实体类起别名
mybatis.mapper-locations=classpath:mybatis/mapper
@Mapper
@Repository
public interface UserMapper {
List queryUserList();
User queryUserById(int id);
int addUser(User user);
int updateUser(User user);
int deleteUser(int id);
}
3、编写接口实现配置文件UserMapper.xml
配置文件UserMapper.xml的位置
4、编写contoller中UserController
import com.kuang.mapper.UserMapper;
import com.kuang.pojo.User;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import sun.net.util.IPAddressUtil;
import java.util.List;
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/queryUserList")
public List queryUserList(){
List userList = userMapper.queryUserList();
for(User user:userList){
System.out.println(user);
}
return userList;
}
@GetMapping("/queryUserById")
public User queryUserById(){
User user = userMapper.queryUserById(1);
return user;
}
@GetMapping("/addUser")
public String addUser(){
userMapper.addUser(new User(21,"阿毛","123456"));
return "添加成功";
}
@GetMapping("/updateUser")
public String updateUser(){
userMapper.updateUser(new User(1,"秃驴","123465"));
return "更改成功";
}
@GetMapping("/deleteUser")
public String deleteUser(){
userMapper.deleteUser(1);
return "删除成功";
}
}
至此,springboot整合mybatis 并且进行增删改查操作就全部结束了。



