springboot工程配置Mybatis与简单使用
Mybatis是一款优秀的持久层框架,用于简化JDBC开发
使用Mybatis查询
创建SpringBoot工程,引入相关依赖
springboot的核心配置文件
准备数据表user,实体类User
配置Mybatis(在application.properties中数据库连接信息)
更改字符集便于注释
编写程序,编写持久层接口,定义SQL(注解/XML)
重要接口
@Mapper // 应用程序在运行时会自动扫描到该接口,并创建该接口的实现类,并创建一个Bean对象,注入到Spring容器中
// 是基于动态代理实现的,所以该接口不能被final修饰,也无需实现
// 会自动将该接口的实现类注入到Spring容器中 IOC 容器,bean
实例讲解
配置实体类:
package com.huohuo.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
public class User {
// 从数据库中获取数据并封装成用户对象
private Integer id; // 不建议使用int,因为int默认值是0,容易造成混淆
private String username;
private String password;
private String name;
private Integer age;
在application.properties中配置数据库信息(记得改编码,编译器也会提示)
spring.application.name=springboot-mybatis-quickStart
# 配置数据库连接信息
spring.datasource.url=jdbc:mysql://localhost:3306/你的项目库
# 配置数据库驱动信息
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 配置数据库用户名和密码
spring.datasource.username=username
spring.datasource.password=pwd
编写持久层接口
package com.huohuo.mapper;
import com.huohuo.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper // 应用程序在运行时会自动扫描到该接口,并创建该接口的实现类,并创建一个Bean对象,注入到Spring容器中
// 是基于动态代理实现的,所以该接口不能被final修饰,也无需实现
// 会自动将该接口的实现类注入到Spring容器中 IOC 容器,bean
public interface UserMapper {
/*
* 查询所有用户
*/
@Select("select * from user") // 在这里编写sql语句
List<User> findAll(); // 返回值会自动封装到函数返回对象当中,这里可以返回一个user集合中
}
测试
package com.huohuo;
import com.huohuo.mapper.UserMapper;
import com.huohuo.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
/*
* 代表当前类中的测试方法运行时会启动SpringBoot应用
*/
@SpringBootTest
class SpringbootMybatisQuickStartApplicationTests {
// 注入usermapper容器
@Autowired
private UserMapper userMapper;
@Test
public void testFindAll(){
List<User> userList = userMapper.findAll(); // 根据接口的返回值进行接收
// 遍历集合输出
userList.forEach(System.out::println);
}
}
Mybatis辅助配置
默认在@select中的sql不提示,可以选择注入语言打开提示,右键显示上下文操作+语言注入设置选择mysql
配置项目数据库
配置日志输出
# 配置mybatis日志输出(控制台输出)
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
测试可以看到数据库往返信息
JDBC vs Mybatis
end
致谢:本文参考黑马程序员的视频。
https://www.bilibili.com/video/BV1yGydYEE3H/?vd_source=1b8f9bfb1d0891faf1c70d7678ae56db