企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
**1. 引入mybatis-spring-boot-starter依赖** ```xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.13</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.24</version> </dependency> </dependencies> ``` **2. `resources/application.yml`** ```properties spring: datasource: username: root password: uhg</flEt3dff url: jdbc:mysql://localhost:3306/learndb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai driver-class-name: com.mysql.cj.jdbc.Driver mybatis: type-aliases-package: com.learn.boot10.pojo mapper-locations: mapper/**Mapper.xml ``` **3. 实体层** ```java @Data public class Student { private Integer id; private String name; private Integer age; private String gender; } ``` **4. dao层** ```java @Repository public interface StudentDao { Student findById(@Param("id") Integer id); } ``` *`resources/mapper/StudentMapper.xml`* ```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.learn.boot10.dao.StudentDao"> <select id="findById" parameterType="integer" resultType="student"> select id,`name`,age,gender from student where id=#{id} </select> </mapper> ``` **5. 启动类扫描dao层** ```java @SpringBootApplication //扫描dao层 @MapperScan("com.learn.boot10.dao") public class Boot10Application { public static void main(String[] args) { SpringApplication.run(Boot10Application.class, args); } } ``` **6. 查询数据库** ```java @RestController @RequestMapping("/student") public class StudentController { @Autowired private StudentDao studentDao; @RequestMapping("/find/{id}") public Student findById(@PathVariable("id") Integer id) { Student student = studentDao.findById(id); System.out.println(student); //{id=1, name=张三, age=25, gender=男生} return student; } } ```