SpringBoot整合Mybatis

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

一、新建SpringBoot工程

二、添加mybatis相关依赖

添加MyBatis Framework和MySQL Driver依赖

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

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

三、配置mybatis相关信息

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

四、创建实体类和接口

如何使用Lombok

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

五、测试

  • 测试类
@SpringBootTest
class Ch02SpringbootMybatisApplicationTests {
    @Autowired
    private StudentDao studentDao;
    
    @Test
    void contextLoads() {
        Student student = studentDao.getById(2);
        System.out.println(student);
    }
}
  • 测试结果

相关文章

微信公众号

最新文章

更多