SpringBoot整合Mybatis

x33g5p2x  于2021-11-25 转载在 Spring  
字(1.2k)|赞(0)|评价(0)|浏览(594)

一、新建SpringBoot工程

二、添加mybatis相关依赖

添加MyBatis Framework和MySQL Driver依赖

  • 方式一:
    在创建springboot工程的时候直接选择这两个依赖

  • 方式二:
    如果在创建spring boot工程的时候没有选择这两个依赖就在项目创建以后在pom.xml文件中添加以下依赖
  1. <!--mybatis集成springboot依赖-->
  2. <dependency>
  3. <groupId>org.mybatis.spring.boot</groupId>
  4. <artifactId>mybatis-spring-boot-starter</artifactId>
  5. <version>2.2.0</version>
  6. </dependency>
  7. <!--mysql连接数据库驱动-->
  8. <dependency>
  9. <groupId>mysql</groupId>
  10. <artifactId>mysql-connector-java</artifactId>
  11. <scope>runtime</scope>
  12. </dependency>

三、配置mybatis相关信息

  1. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
  2. spring.datasource.url=jdbc:mysql://localhost:3360/whynode
  3. spring.datasource.username=root
  4. spring.datasource.password=123

四、创建实体类和接口

如何使用Lombok

  • 实体类:
  1. @Data //lombok插件
  2. public class Student {
  3. private Integer id;
  4. private String name;
  5. private String sex;
  6. private Integer age;
  7. }
  • 接口
  1. @Mapper
  2. public interface StudentDao {
  3. @Select("select * from t_student where id=#{id}")
  4. Student getById(Integer id);
  5. }

五、测试

  • 测试类
  1. @SpringBootTest
  2. class Ch02SpringbootMybatisApplicationTests {
  3. @Autowired
  4. private StudentDao studentDao;
  5. @Test
  6. void contextLoads() {
  7. Student student = studentDao.getById(2);
  8. System.out.println(student);
  9. }
  10. }
  • 测试结果

相关文章