目录
3.编写entity,mapper,service,contorller层的代码
1.先创建Spring Boot项目
略
在spring boot的启动类上加入@MapperSacn注解扫描我们的mapper接口,或者在mapper接口上加@Mapper注解
加上注解后spring就可以扫描到我们的mapper接口,然后mybatis自动帮我们生成代理类放入spriing容器.
2.加入相关依赖
<dependencies> <!-- spring boot web依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- lombok依赖--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!-- mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- mybatis整合spring boot的依赖--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
3.编写entity,mapper,service,contorller层的代码
entity
@Data
public class Student implements Serializable {
private Integer id;
private String name;
private Integer age;
private Integer clazzNo;
public Student(Integer id, String name, Integer age, Integer clazzNo) {
this.id = id;
this.name = name;
this.age = age;
this.clazzNo = clazzNo;
}
}
mapper
public interface StudentMapper {
/**
* 查询所有学生信息
* @return
*/
List<Student> queryAllStudents();
}
mapper.xml
<?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.ws.mapper.StudentMapper">
<select id="queryAllStudents" resultType="com.ws.entity.Student">
select id, name, age, clazz_no from student
</select>
</mapper>
service
接口
public interface IStudentService {
List<Student> queryAllStudents();
}
Impl
@Service
public class StudentService implements IStudentService{
@Autowired
public StudentMapper studentMapper;
@Override
public List<Student> queryAllStudents() {
return studentMapper.queryAllStudents();
}
}
contorller
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
IStudentService studentService;
@GetMapping("/query/students")
public List<Student> queryAllStudentList() {
System.out.println("11111111111111");
return studentService.queryAllStudents();
}
}
4.编写yml配置文件,或者propertise配置文件
yml方式
spring:
#mysql连接信息
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/springdb?serverTimezone=GMT%2B8&useSSL=false
username: root
password: root
#mybatis配置
mybatis:
#mapper.xml位置
mapper-locations: classpath:mapper/*.xml
propertise方式
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springdb?serverTimezone=GMT%2B8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
#mybatis配置
mybatis.mapper-locations=classpath:mapper/*.xml