今天学习了SpringBoot +Mybatis进行CRUD的操作,步骤如下:
- 配置数据源,在这里我用的是阿里的Druid数据源
- 配置mybatis配置,标注了映射的xml都来自哪个包,映射对象是namespace,来自哪个pojo类。
- 写POJO。POJO一定要与数据库内容相对应。
- 写Maper接口,Maper接口是用来导入引用的类.
- 写相关的映射
第一步:配置druid数据源:
spring:
datasource:
username: root
password: zlx21421
url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
第二步,配置mybatis
mybatis:
mapperLocations: classpath:mybatis/Mapper/*.xml
type-aliases-package: com.examples.pojo
第三步,写pojo
package com.examples.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private int id;
private String department_name;
}
第四步,写maper接口
package com.examples.Mapper;
import com.examples.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Mapper
@Repository
public interface UserMapper {
List<User> queryList();
int queryUserById(int id);
int deleteUser(int id);
int addUser(User user);
int updateUser(User user);
}
第五步。写映射
<?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="com.examples.Mapper.UserMapper">
<select id="queryList" resultType="User">
select * from department;
</select>
<select id ="queryUserById" resultType="User">
select * from department where id=#{id};
</select>
<insert id ="addUser" parameterType="User">
insert into department (id,department_name) value(#{id},#{department_name});
</insert>
</mapper>
最后一步写Controller
package com.examples.controller;
import com.examples.Mapper.UserMapper;
import com.examples.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/queryUserList")
public List<User> queryUserList() {
List<User> Lists = userMapper.queryList();
for (User user : Lists) {
System.out.println(user);
}
return Lists;
}
@GetMapping("/addUser/{id}/{department_name}")
public String addUser(@PathVariable int id, @PathVariable String department_name) {
userMapper.addUser(new User(id, department_name));
return "ok";
}
}
完成啦~~~~