目录结构
application.yml文件
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- mock数据 -->
<dependency>
<groupId>com.github.javafaker</groupId>
<artifactId>javafaker</artifactId>
<version>0.17.2</version>
</dependency>
</dependencies>
xml文件
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.my.learn.mybatis2.mapper.StudentMapper">
<resultMap id="student" type="com.my.learn.mybatis2.domain.Student">
<id column="id" property="id"/>
<result column="name" property="name"/>
</resultMap>
<select id="getById" resultMap="student">
select id,`name` from student where id = #{id}
</select>
<select id="getAll" resultMap="student">
select id,`name` from student
</select>
<insert id="add" parameterType="com.my.learn.mybatis2.domain.Student" useGeneratedKeys="true" keyProperty="id">
insert into student (`name`) value (#{name})
</insert>
<update id="update" parameterType="com.my.learn.mybatis2.domain.Student">
update student set `name`= #{name} where id = #{id}
</update>
<delete id="deleteById" parameterType="Integer">
delete from student where id = #{id}
</delete>
</mapper>
Java文件
//主类
@SpringBootApplication
@MapperScan("com.my.learn.mybatis2.mapper")
public class MybatisSpringDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisSpringDemoApplication.class, args);
}
}
//controller
@RestController
@RequestMapping("/stu")
public class StudentController {
@Autowired
private StudentMapper mapper;
@GetMapping
public List<Student> getAll() {
List<Student> all = mapper.getAll();
return all;
}
@GetMapping("/{id}")
public Student getById(@PathVariable("id") Integer id) {
Student student = mapper.getById(id);
return student;
}
@PostMapping
public Integer add(Student student) {
mapper.add(student);
return student.getId();
}
@PutMapping
public Student update(Student student) {
mapper.update(student);
return mapper.getById(student.getId());
}
@DeleteMapping("/{id}")
public Object deleteById(@PathVariable("id") Integer id) {
mapper.deleteById(id);
return "";
}
}
//实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
private Integer id;
private String name;
}
//mapper
public interface StudentMapper {
Student getById(Integer id);
List<Student> getAll();
void add(Student student);
void update(Student student);
void deleteById(Integer id);
}