MyBatis是一个持久层框架,和Spring没有任何关系,可以用来简化数据库的操作!
创建工作:
创建Spring Boot工程,并导入MyBatis的起步依赖,Mysql的依赖等
配置数据库:
#配置数据库的连接字符串
spring:datasource:url: jdbc:mysql://127.0.0.1:3306/mybatis_test?characterEncoding=utf8username: rootpassword: 自己设定的密码driver-class-name: com.mysql.cj.jdbc.Driver
本文主要讲解使用注解的方式来操作数据库!!
然而操作数据库主要是用来增删改查四个方面,因此,本文着重于增删改查来讲解!!
在操作数据库之前,我们需要创建一个数据库:
-- 创建数据库
DROP DATABASE IF EXISTS mybatis_test;
CREATE DATABASE mybatis_test DEFAULT CHARACTER SET utf8mb4;
-- 使⽤数据数据
USE mybatis_test;
-- 创建表[⽤⼾表]
DROP TABLE IF EXISTS userinfo;
CREATE TABLE `userinfo` (`id` INT ( 11 ) NOT NULL AUTO_INCREMENT,`username` VARCHAR ( 127 ) NOT NULL,`password` VARCHAR ( 127 ) NOT NULL,`age` TINYINT ( 4 ) NOT NULL,`gender` TINYINT ( 4 ) DEFAULT '0' COMMENT '1-男 2-⼥ 0-默认',`phone` VARCHAR ( 15 ) DEFAULT NULL,`delete_flag` TINYINT ( 4 ) DEFAULT 0 COMMENT '0-正常, 1-删除',`create_time` DATETIME DEFAULT now(),`update_time` DATETIME DEFAULT now(),PRIMARY KEY ( `id` )
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4;
-- 添加⽤⼾信息
INSERT INTO mybatis_test.userinfo ( username, `password`, age, gender, phone )
VALUES ( 'admin', 'admin', 18, 1, '18612340001' );
INSERT INTO mybatis_test.userinfo ( username, `password`, age, gender, phone )
VALUES ( 'zhangsan', 'zhangsan', 18, 1, '18612340002' );
INSERT INTO mybatis_test.userinfo ( username, `password`, age, gender, phone )
VALUES ( 'lisi', 'lisi', 18, 1, '18612340003' );
INSERT INTO mybatis_test.userinfo ( username, `password`, age, gender, phone )
VALUES ( 'wangwu', 'wangwu', 18, 1, '18612340004' );
那么,此时我们需要创建一个UserInfo类,使其各个参数名称与数据库参数名称相同(类似)
@Data
public class UserInfo {private Integer id;private String username;private String password;private Integer age;private Integer gender;private String phone;private Integer deleteFlag;private LocalDateTime createTime;private LocalDateTime updateTime;
}
值得注意的是:由于Java参数名称语法的原因,不能带有"_"(下划线),因此,Java中参数名称与数据库中参数名称出现了不一样的情况!!
有了上述的前提,我们便开始步入正题吧!
增:
@Mapper
public interface UserInfoMapper {@Insert("insert into userinfo(id,username,gender,phone,password,age)" +" values(#{id},#{username},#{gender},#{phone},#{password},#{age})")Integer insert(UserInfo userInfo);}
Spring Boot测试:
@Slf4j
@SpringBootTest
class UserInfoMapperTest {@Autowiredprivate UserInfoMapper userInfoMapper;@Testvoid insert() {UserInfo userInfo=new UserInfo();userInfo.setAge(10);//userInfo.setId(14);userInfo.setGender(1);userInfo.setPassword("123456");userInfo.setUsername("zhao");userInfo.setPhone("13512345678");Integer result=userInfoMapper.insert(userInfo);log.info(result.toString());log.info("insert 方法,执行结果:{}",result);}}
测试代码运行结果为:
数据库数据查看:
同理:在增加一个id为9的数据!(方便后续测试自增主键)
数据库查看效果
那么,现在我们对主键id实现自增主键!!
@Mapper
public interface UserInfoMapper {//返回自增id@Options(useGeneratedKeys = true, keyProperty = "id")@Insert("insert into userinfo(id,username,gender,phone,password,age)" +" values(#{id},#{username},#{gender},#{phone},#{password},#{age})")Integer insert(UserInfo userInfo);}
Spring Boot测试代码:
@Slf4j
@SpringBootTest
class UserInfoMapperTest {@Autowiredprivate UserInfoMapper userInfoMapper;@Testvoid insert() {UserInfo userInfo=new UserInfo();userInfo.setAge(10);//不再手动设置主键,使其自增主键// userInfo.setId(9);userInfo.setGender(1);userInfo.setPassword("123456");userInfo.setUsername("zhao");userInfo.setPhone("13512345678");Integer result=userInfoMapper.insert(userInfo);log.info(result.toString());log.info("insert 方法,执行结果:{}",result);}}
数据库查看运行效果:
因此,自增主键得以实现!
删:
根据id来删除数据
@Mapper
public interface UserInfoMapper {@Delete("delete from userinfo where id=#{id}")Integer delete(Integer id);
}
Spring Boot测试代码:(删除id为4的数据)
@Slf4j
@SpringBootTest
class UserInfoMapperTest {@Autowiredprivate UserInfoMapper userInfoMapper;@Testvoid delete() {Integer result =userInfoMapper.delete(4);log.info(result.toString());log.info("delete 方法,执行结果:{}",result);}}
代码的运行结果为:
再次查询数据库:
对比结果,我们可以看出,数据库中id=4的数据已经被删除!!
改:
根据id来改掉其年龄
@Mapper
public interface UserInfoMapper {@Update("update userinfo set age=#{age} where id=#{id}")Integer update(UserInfo userInfo);
}
Spring Boot测试代码:(将id=5的数据其age改为99)
@Slf4j
@SpringBootTest
class UserInfoMapperTest {@Autowiredprivate UserInfoMapper userInfoMapper;@Testvoid update() {UserInfo userInfo=new UserInfo();userInfo.setAge(99);userInfo.setId(5);Integer result=userInfoMapper.update(userInfo);log.info(result.toString());log.info("update 方法,执行结果:{}",result);}
代码的运行结果为:
查询数据库,查看结果:
查:
查的话,涉及到数据库参数名与Java属性名不一致的情况,所以操作不是很容易,但是,方法也不少!我们来看一下吧!
@Mapper
public interface UserInfoMapper {@Select("select id, username, password, age, gender, phone," +" delete_flag, create_time , update_time" +" from userinfo")List<UserInfo> selectAll();}
Spring Boot测试代码:
@Slf4j
@SpringBootTest
class UserInfoMapperTest {@Autowiredprivate UserInfoMapper userInfoMapper;@Testvoid selectAll() {List<UserInfo> list=userInfoMapper.selectAll();log.info(list.toString());}
}
代码的运行结果为:
很显然这是不正确的查询结果!因为数据库中每个参数都有数据 :
那么,我们来看一下解决方案吧!
查1:as起别名
@Mapper
public interface UserInfoMapper {/*** 对字段进行重命名* @return*/@Select("select id, username, password, age, gender, phone," +" delete_flag as deleteFlag, create_time as createTime, update_time as updateTime" +" from userinfo")List<UserInfo> selectAll();}
Spring Boot测试代码:
@Slf4j
@SpringBootTest
class UserInfoMapperTest {@Autowiredprivate UserInfoMapper userInfoMapper;@Testvoid selectAll() {List<UserInfo> list=userInfoMapper.selectAll();log.info(list.toString());}
}
代码的运行结果为:
查询成功!
查2:使用@Result注解
@Mapper
public interface UserInfoMapper {/*** 使用@Result注解* @return*/@Select("select * from userinfo")@Results(id="BaseMap",value = {@Result(property = "create_time", column = "createTime"),@Result(property = "update_time", column = "updateTime"),@Result(property = "delete_flag", column = "deleteFlag")})List<UserInfo> selectAll2();}
Spring Boot测试代码:
@Slf4j
@SpringBootTest
class UserInfoMapperTest {@Autowiredprivate UserInfoMapper userInfoMapper;@Testvoid selectAll2() {List<UserInfo> list=userInfoMapper.selectAll2();log.info(list.toString());}}
运行结果为;
查3:更改application.yml文件配置;
mybatis:configuration: map-underscore-to-camel-case: true #自动驼峰转换
@Mapper
public interface UserInfoMapper {/*** 更改yml文件配置* @return*/@Select("select * from userinfo")List<UserInfo> selectAll3();}
Spring Boot测试代码:
@Slf4j
@SpringBootTest
class UserInfoMapperTest {@Autowiredprivate UserInfoMapper userInfoMapper;@Testvoid selectAll3() {List<UserInfo> list=userInfoMapper.selectAll3();log.info(list.toString());}}
代码的运行结果为:
本文主要是用注解的方式来带领大家了解MyBatis来操作数据库。