SpringBoot_MyBatis/MyBatis入门+整合Druid基础

SpringBoot_MyBatis/MyBatisPuls基础

什么是MyBatis

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。 MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs映射成数据库中的记录。

使用MyBatis的时候需要自己手动编写SQL语句,也有代码自动生成工具来简化开发,我一般会使用Mybatis-Plus增强工具包来简化MyBatis的开发。

Mybatis-Plus官网:https://github.com/baomidou/mybatis-plus

同时它还提供了与SpringBoot的集成starter,非常的方便,本篇我将讲解如何在SpringBoot中集成MyBatis-Plus。

创建一个MyBatis程序

01.导入maven依赖

<dependencies>
    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.4</version>
    </dependency>
    
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    
</dependencies>

02.创建一个Dao层Mapper

/**
 * @author CodeWYX
 */
@Mapper
public interface UserMapper {

    @Select("select * from `user` where id=#{id}") //查询语句
    User getUserById(Integer id);
}

03.创建service层

/**
 * @author CodeWYX
 */
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public User getUserById(Integer id){
        return userMapper.getUserById(id);
    }
}

04.创建controller

/**
 * @author CodeWYX
 * @date 2022/1/20 14:29
 */
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/getUser/{id}")
    @ResponseBody
    public User getUser(@PathVariable("id")int id){
        return userService.getUserById(id);
    }
}

05.编写配置文件

# 应用名称
spring.application.name=mybatis
#下面这些内容是为了让MyBatis映射
#指定Mybatis的实体目录
mybatis.type-aliases-package=com.xiao.mybatis.pojo
# 数据库驱动:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据源名称
spring.datasource.name=defaultDataSource
# 数据库连接地址
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai
# 数据库用户名&密码:
spring.datasource.username=root
spring.datasource.password=123456

06.查看运行结果
在这里插入图片描述

至此SpringBoot程序整合MyBatis就做完了,在引入依赖后只需要在配置文件中配置数据库连接即可

MyBatis-Puls

什么是MyBatis-Puls?

MyBatis-Puls 是一个MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

framework

创建一个MyBatisPuls程序

01.导入坐标

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.8</version>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.2</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

02.配置

# 应用名称
spring.application.name=mybatis_puls
# 应用服务 WEB 访问端口
server.port=8080
# 数据库驱动:
spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据源名称
spring.datasource.druid.name=DruidDataSource
# 数据库连接地址
spring.datasource.druid.url=jdbc:mysql://localhost:3306/user?serverTimezone=UTC
# 数据库用户名&密码:
spring.datasource.druid.username=root
spring.datasource.druid.password=123456

03.编写Dao层

@Mapper
public interface UserMapper extends BaseMapper<User> {

}

04.编写Service层

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public User getUserById(Integer id){
        return userMapper.selectById(id);
    }

}

05.编写JavaBean

@Data
public class User {
    private Integer id;
    private String name;
    private String password;
}

06.编写Controller

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/getUser/{id}")
    @ResponseBody
    public User getUser(@PathVariable("id")Integer id){
        return userService.getUserById(id);
    }
}

至此一个简单的MyBatisPuls程序就已经被创建好了,接下来就是更深层次是讲解MyBatis的功能

首先可以看到在编写Dao层的UserMapper接口时候我们继承了一个BaseMapper接口

在这里插入图片描述

这个接口内定义了17个方法 来供我们项目中一些通用的CRUD,接下来就演示一些如何使用这些方法

01.select

​ 01.根据id查询

public User getUserById(Integer id){
    return userMapper.selectById(id);
}

​ 02.根据条件查询(单个返回值)

 public User getUserQueryWrapper(User user){
     QueryWrapper<User> wrapper = new QueryWrapper<>();
     wrapper.eq("name",user.getName());
     return userMapper.selectOne(wrapper);
 }

​ 03.根据条件查询(多条数据)

public List<User> getUserByPassword(String password){
    HashMap<String, Object> map = new HashMap<>();
    map.put("password",password);
    return userMapper.selectByMap(map);
}

​ 04.根据多个id批量查询

public List<User> getUsersByIds(List<Integer> list){
    return userMapper.selectBatchIds(list);
}

​ 05.分页查询

public Page<User> getUsersByPage(Page<User> page){
    return userMapper.selectPage(page,null);
}

02.insert

​ 01.插入数据后 会回写数据

//Servcie层
public Integer insertUser(User user){
    return userMapper.insert(user);
}
//Controller层
@GetMapping("/getUser/username={username}&password={password}")
@ResponseBody
public Integer getUser(@PathVariable("password")String password,@PathVariable("username")String username){
    User user = new User();
    user.setName(username);
    user.setPassword(password);
    userService.insertUser(user);
    return user.getId();
}

03.update

​ 01.根据id修改数据 如果对象中id为空则或id不存在不进行修改 没传的属性不进行修改

public int updateUserById(User user){
    return userMapper.updateById(user);
}

​ 02.条件修改数据 设置wrapper 根据wrapper 来修改数据 如果wrapper 为空 则修改全部数据 user对象中为空的则不修改

public int updateUser(User user){
    UpdateWrapper<User> wrapper = new UpdateWrapper<>();
    wrapper.eq("id",user.getId());
    return userMapper.update(user,wrapper);
}

04.delete

​ 01.根据id删除

public int deleteUserById(Integer id){
    return userMapper.deleteById(id);
}

​ 02.根据条件删除

public int deleteUser(User user){
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.eq("id",user.getId());
    return userMapper.delete(wrapper);
}

​ 03.根据id批量删除

public int deleteUser(List list){
    return userMapper.deleteBatchIds(list);
}
05.高级的条件查询

1、分页查询年龄在18 - 50且id为1、姓名为tom的用户:

List<User> users = userMapper.selectPage(new Page<User>(1,3),
     new QueryWrapper<User>()
        .between("age",18,50)
        .eq("id",1)
        .eq("name","tom")
);

由此案例可知,分页查询和之前一样,new 一个page对象传入分页信息即可。至于分页条件,new 一个QueryWrapper对象,调用该对象的相关方法即可。between方法三个参数,分别是column、value1、value2,该方法表示column的值要在value1和value2之间;eq是equals的简写,该方法两个参数,column和value,表示column的值和value要相等。注意column是数据表对应的字段,而非实体类属性字段。

2、查询id为0且名字中带有z、或者密码中带有a的用户:

List<User> users = userMapper.selectList(
                new QueryWrapper<User>()
               .eq("id",0)
               .like("name","z")
                //.or()//和or new 区别不大
               .orNew()
               .like("passowrd","a")
);

未说分页查询,所以用selectList即可,用QueryWrapper的like方法进行模糊查询,like方法就是指column的值包含value值,此处like方法就是查询last_name中包含“老师”字样的记录;“或者”用or或者orNew方法表示,这两个方法区别不大,用哪个都可以,可以通过控制台的sql语句自行感受其区别。

3、查询名字包含z,根据id排序,简单分页:

List<User> users = userMapper.selectList(
                new QueryWrapper<User>()
                .like("name","z")
                .orderBy("id")//直接orderby 是升序,asc
                .last("desc limit 1,3")//在sql语句后面追加last里面的内容(改为降序,同时分页)
);

简单分页是指不用page对象进行分页。orderBy方法就是根据传入的column进行升序排序,若要降序,可以使用orderByDesc方法,也可以如案例中所示用last方法;last方法就是将last方法里面的value值追加到sql语句的后面,在该案例中,最后的sql语句就变为select ······ order by desc limit 1, 3,追加了desc limit 1,3所以可以进行降序排序和分页

4、根据姓名和密码进行更新:

@Test
public void testEntityWrapperUpdate(){
        User user = new User();
        user.setName("xiao");
        user.setPassword("asdasdas");
        userMapper.update(user,
                new UpdateWrapper<User>()
                .eq("name","zhangsan")
                .eq("password","password")
        );
}

该案例表示把name为zhangsan,password为password的所有用户的信息更新为user中设置的信息。

5、根据条件删除:

public int deleteUser(User user){
    Map<String, Object> map = new HashMap<>();
    map.put("id",user.getId());
    map.put("name",user.getName());

    return userMapper.deleteByMap(map);
}

会自动将map里面的参数拼接成sql执行删除

6、根据条件删除:

public int deleteUser(User user){
    return userMapper.delete(new QueryWrapper<User>()
            .eq("name",user.getName())
            .eq("id",user.getId()));
}

根据QueryWrapper中设置好的条件进行删除

06.注解

@TableName

  • 描述:表名注解,标识实体类对应的表
  • 使用位置:实体类
@TableName("sys_user")
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}
属性类型必须指定默认值描述
valueString“”表名
schemaString“”schema
keepGlobalPrefixbooleanfalse是否保持使用全局的 tablePrefix 的值(当全局 tablePrefix 生效时)
resultMapString“”xml 中 resultMap 的 id(用于满足特定类型的实体类对象绑定)
autoResultMapbooleanfalse是否自动构建 resultMap 并使用(如果设置 resultMap 则不会进行 resultMap 的自动构建与注入)
excludePropertyString[]{}需要排除的属性名 @since 3.3.1

关于 autoResultMap 的说明:

MP 会自动构建一个 resultMap 并注入到 MyBatis 里(一般用不上),请注意以下内容:

因为 MP 底层是 MyBatis,所以 MP 只是帮您注入了常用 CRUD 到 MyBatis 里,注入之前是动态的(根据您的 Entity 字段以及注解变化而变化),但是注入之后是静态的(等于 XML 配置中的内容)。

而对于 typeHandler 属性,MyBatis 只支持写在 2 个地方:

  1. 定义在 resultMap 里,作用于查询结果的封装
  2. 定义在 insertupdate 语句的 #{property} 中的 property 后面(例:#{property,typehandler=xxx.xxx.xxx}),并且只作用于当前 设置值

除了以上两种直接指定 typeHandler 的形式,MyBatis 有一个全局扫描自定义 typeHandler 包的配置,原理是根据您的 property 类型去找其对应的 typeHandler 并使用。

@TableId

  • 描述:主键注解
  • 使用位置:实体类主键字段
@TableName("sys_user")
public class User {
    @TableId
    private Long id;
    private String name;
    private Integer age;
    private String email;
}
属性类型必须指定默认值描述
valueString“”主键字段名
typeEnumIdType.NONE指定主键类型
IdType
描述
AUTO数据库 ID 自增
NONE无状态,该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 INPUT)
INPUTinsert 前自行 set 主键值
ASSIGN_ID分配 ID(主键类型为 Number(Long 和 Integer)或 String)(since 3.3.0),使用接口IdentifierGenerator的方法nextId(默认实现类为DefaultIdentifierGenerator雪花算法)
ASSIGN_UUID分配 UUID,主键类型为 String(since 3.3.0),使用接口IdentifierGenerator的方法nextUUID(默认 default 方法)
ID_WORKER分布式全局唯一 ID 长整型类型(please use ASSIGN_ID)
UUID32 位 UUID 字符串(please use ASSIGN_UUID)
ID_WORKER_STR分布式全局唯一 ID 字符串类型(please use ASSIGN_ID)

@TableField

  • 描述:字段注解(非主键)
@TableName("sys_user")
public class User {
    @TableId
    private Long id;
    @TableFiled("nickname")
    private String name;
    private Integer age;
    private String email;
}
属性类型必须指定默认值描述
valueString“”数据库字段名
existbooleantrue是否为数据库表字段
conditionString“”字段 where 实体查询比较条件,有值设置则按设置的值为准,没有则为默认全局的 %s=#{%s}参考(opens new window)
updateString“”字段 update set 部分注入,例如:当在version字段上注解update="%s+1" 表示更新时会 set version=version+1 (该属性优先级高于 el 属性)
insertStrategyEnumFieldStrategy.DEFAULT举例:NOT_NULL insert into table_a(<if test="columnProperty != null">column</if>) values (<if test="columnProperty != null">#{columnProperty}</if>)
updateStrategyEnumFieldStrategy.DEFAULT举例:IGNORED update table_a set column=#{columnProperty}
whereStrategyEnumFieldStrategy.DEFAULT举例:NOT_EMPTY where <if test="columnProperty != null and columnProperty!=''">column=#{columnProperty}</if>
fillEnumFieldFill.DEFAULT字段自动填充策略
selectbooleantrue是否进行 select 查询
keepGlobalFormatbooleanfalse是否保持使用全局的 format 进行处理
jdbcTypeJdbcTypeJdbcType.UNDEFINEDJDBC 类型 (该默认值不代表会按照该值生效)
typeHandlerClass<? extends TypeHandler>UnknownTypeHandler.class类型处理器 (该默认值不代表会按照该值生效)
numericScaleString“”指定小数点后保留的位数

关于jdbcTypetypeHandler以及numericScale的说明:

numericScale只生效于 update 的 sql. jdbcTypetypeHandler如果不配合@TableName#autoResultMap = true一起使用,也只生效于 update 的 sql. 对于typeHandler如果你的字段类型和 set 进去的类型为equals关系,则只需要让你的typeHandler让 Mybatis 加载到即可,不需要使用注解

FieldStrategy
描述
IGNORED忽略判断
NOT_NULL非 NULL 判断
NOT_EMPTY非空判断(只对字符串类型字段,其他类型字段依然为非 NULL 判断)
DEFAULT追随全局配置
FieldFill
描述
DEFAULT默认不处理
INSERT插入时填充字段
UPDATE更新时填充字段
INSERT_UPDATE插入和更新时填充字段

@Version(opens new window)

  • 描述:乐观锁注解、标记 @Verison 在字段上

@EnumValue

  • 描述:普通枚举类注解(注解在枚举字段上)

@TableLogic

  • 描述:表字段逻辑处理注解(逻辑删除)
属性类型必须指定默认值描述
valueString“”逻辑未删除值
delvalString“”逻辑删除值

@SqlParser

  • 描述:序列主键策略 oracle
  • 属性:value、resultMap
属性类型必须指定默认值描述
valueString“”序列名
clazzClassLong.classid 的类型, 可以指定 String.class,这样返回的 Sequence 值是字符串"1"

@InterceptorIgnore

see 插件主体

@OrderBy

  • 描述:内置 SQL 默认指定排序,优先级低于 wrapper 条件查询
属性类型必须指定默认值描述
isDescbooleantrue是否倒序查询
sortshortShort.MAX_VALUE数字越小越靠前

整合Druid

01.直接使用法

# 应用名称
spring.application.name=mybatis_puls
# 应用服务 WEB 访问端口
server.port=8080
# 数据库驱动:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据源名称
spring.datasource.name=defaultDataSource
# 数据库连接地址
spring.datasource.url=jdbc:mysql://localhost:3306/user?serverTimezone=UTC
# 数据库用户名&密码:
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

02.整合法

# 应用名称
spring.application.name=mybatis_puls
# 应用服务 WEB 访问端口
server.port=8080
# 数据库驱动:
spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据源名称
spring.datasource.druid.name=DruidDataSource
# 数据库连接地址
spring.datasource.druid.url=jdbc:mysql://localhost:3306/user?serverTimezone=UTC
# 数据库用户名&密码:
spring.datasource.druid.username=root
spring.datasource.druid.password=123456
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CodeWYX

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值