开发流程图
先选择springboot项目创建,此处3.0以上的springboot项目最低都要java17版本
让数据库表中的属性名和实体类中的属性名保持一致就可以完成查询结果的自动封装。
2.引入myabtis相关依赖,配置mybatis
这里可以手动选择mybatis框架的依赖和mysql的驱动,不需要进去再引入。
使用mybatis连接数据库需要
1.驱动类的全类名
2.数据库连接的url
3.用户名和密码
使用Springboot整合mybatis时需要把这些配置信息配置在application.properties中
3.编写sql语句
在springboot中编写sql语句有注解和XML两种方式
。
使用注解开发需要定义一个持久层的接口叫做UserMapper,同时加上一个@Mapper注解标识当前接口是mybatis中的持久层接口。
在Mapper接口定义方法加上注解@Select指定当前方法是一个查询操作,sql语句的执行结果会自动封装到方法的返回值。
创建好项目后在pom.xml文件里面有一个如下依赖,这个mysql驱动包是目前最新版本,不需要标定mysql版本了
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
使用如下的建表语句创建一个新表
create table user(
id int unsigned primary key auto_increment comment 'ID',
name varchar(100) comment '姓名',
age tinyint unsigned comment '年龄',
gender tinyint unsigned comment '性别, 1:男, 2:女',
phone varchar(11) comment '手机号'
) comment '用户表';
insert into user(id, name, age, gender, phone) VALUES (null,'白眉鹰王',55,'1','18800000000');
insert into user(id, name, age, gender, phone) VALUES (null,'金毛狮王',45,'1','18800000001');
insert into user(id, name, age, gender, phone) VALUES (null,'青翼蝠王',38,'1','18800000002');
insert into user(id, name, age, gender, phone) VALUES (null,'紫衫龙王',42,'2','18800000003');
insert into user(id, name, age, gender, phone) VALUES (null,'光明左使',37,'1','18800000004');
insert into user(id, name, age, gender, phone) VALUES (null,'光明右使',48,'1','18800000005');
select * from user;
在项目中创建与之对应的实体类并生成对应的setters和getters方法还有有参构造和无参构造方法
数据库准备好了,实体类准备好了,接下来要连接mybatis和mysql数据库,在springboot默认创建的properties文件中配置数据库的连接信息如下
#驱动类名称
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#数据库连接的url
spring.datasource.url=jdbc:mysql://localhost:3306/test1
#连接数据库的用户名
spring.datasource.username=root
#连接数据库的密码
spring.datasource.password=1234
创建Mapper成的接口UserMapper,并加上一个@Mapper的注解
加上该注解后,在运行时会自动生成该接口的实现类对象(代理对象),并将该对象交给IOC容器管理
工作都准备好了,接下来要做测试了,按照标准的Maven项目结构,单元测试的代码要写在test目录下
UserMapper原本是个接口,是不能调用的,但是加上@Mapper注解后在IOC容器里面已经有了一个bean对象,这时就可以通过依赖注入的形式将bean注入。
随后使用声明的对象的方法进行查询并输出
直接输出list结果如下
也可以基于stream流的方式输出
userList.stream().forEach(user->{
System.out.println(user);
});
配置SQL提示(简化开发)
在写mapper接口时sql语句不会报错,这很容易导致运行时出现错误。