MyBatis 的注解实现方法

MyBatis 的注解实现方法

在这里插入图片描述

引入依赖

在springBoot项目中下载了EditStarters插件的,可以直接在配置文件处右键
在这里插入图片描述
点击generate
在这里插入图片描述
再次点击这个插件
在这里插入图片描述
在SQL中将图中的勾上就可以啦
在这里插入图片描述

添加配置

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/mybatis_test?characterEncoding=utf8&useSSL=false
    username: root
    password: 111111
    driver-class-name: com.mysql.cj.jdbc.Driver

这里需要注意的是,需要连接的数据库的名称,这里我们使用mybatis_test,还要注意个人的用户名和密码

创建表

-- 创建数据库
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这样一个表,下面我们要通过mybatis来操作数据库,就需要用到实体类的映射关系

package com.example.demo.model;

import lombok.Data;

import java.util.Date;
@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 Date createTime;
    private Date updateTime;

}

实体类的属性名与表中的字段名⼀⼀对应

创建mapper接口

这里创建的接口,后缀最好是以mapper结尾,因为在工作中,mapper里面都是存放的操作数据库的相关代码,而正因为如此,我们可以给他加上一个@Mapper注解来将这个类交给spring来管理,
这里为什么创建的是接口,而不是类,因为接下来我们要实现的操作数据库的方法都不会对齐进行实现,我们只需要将方法定义出来,剩下的交给我们这次的主题,注解来实现

@Insert

对于数据中的添加数据的操作,我们可以先创建一个insert方法

package com.example.demo.mapper;

import com.example.demo.model.UserInfo;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface mapper {
    Integer insert(UserInfo userInfo);
}

创建完成之后,我们需要使用@Insert来编写我们的sql代码

package com.example.demo.mapper;

import com.example.demo.model.UserInfo;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface mapper {
    @Insert(("insert into userinfo (username,password,age,gender,phone) " +
            "values (#{username},#{password},#{age},#{gender},#{phone})"))
    Integer insert(UserInfo userInfo);
}

这里的#中的username代表Java对象的属性,前面的代表数据库中的字段属性
既然我们是添加数据,那么我们就需要给该方法传递一个需要添加的对象,返回值则是对于sql的返回值

@Delete

对于数据中的删除数据的操作,根据上面的操作,我们也可以使用注解的方法实现

package com.example.demo.mapper;

import com.example.demo.model.UserInfo;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface mapper {
    @Insert(("insert into userinfo (username,password,age,gender,phone) " +
            "values (#{username},#{password},#{age},#{gender},#{phone})"))
    Integer insert(UserInfo userInfo);
    @Delete("delete from userinfo where id=#{id}")
    Integer delete(Integer id);
}

@Select

这里需要注意,创建数据库中的表的适合,我们使用的delete_flag,而创建实体类的适合,我们创建的是deleteFlag,很显然,名字格式不同,这会导致查询时,会因为数据格式不同,而导致显示不出对应的数据
怎么解决呢,有三种解决方法,sql中对数据库属性名进行重命名,很显然,这是不优雅的,下面我们介绍另外两种解决方法

@Results和@ResultMap

            @Results( id = "BaseMap",value = {@Result(column = "delete_flag",property = "deleteFlag"),
            @Result(column = "create_time",property = "createTime"),
            @Result(column = "update_time",property = "updateTime")})

在进行上述定义之后,想在其他地方使用时,就可以使用@ResultMap注解来实现

    @Select("select * from userinfo")
    @Results( id = "BaseMap",value = {@Result(column = "delete_flag",property = "deleteFlag"),
            @Result(column = "create_time",property = "createTime"),
            @Result(column = "update_time",property = "updateTime")})
    List<UserInfo> selectAll();
    @Select("select id,username,password,age,gender,phone,delete_flag,create_time,update_time from userinfo where id=#{id}")
    @ResultMap("BaseMap")
    List<UserInfo> select(Integer id);

通过配置文件解决

mybatis:
  configuration:
    map-underscore-to-camel-case: true

在配置文件中加入以上代码,即可实现自动转驼峰

@Update

    @Update("update userinfo set password=#{password} where id=#{id}")
    Integer upDate(UserInfo userInfo);

@Options

当我们想要查看数据库中的自增变量时,我们就可以使用@Options来对变量进行映射

@Options(useGeneratedKeys = true,keyProperty = "id")
/***********************基本描述**********************************/ 0、根据表可以单独生成javaBean后缀可以自定义 1、工具本身是非常简单的,每个人都能做就是使用模板替换生成相应文件 2、工具主要针对SpringMvc+Mybatis注解+Mysql生成对象,dao、sqlDao、interface、实现接口 3、根据表生成Excel 4、生成成功后倒入到自己对应的项目中,然后Ctrl+Shipt+O(Eclipse快速倒入包)实现 5、里面因为运用的是注解,所以很多包我就没有提供了因为这些都是很基础的东西,不会的同学可以去网上查看搭建Mybatis注解 6、生成了些什么,具体主要是对单表的增、删、改、查(分页) /********************************/ /********************************/ /*************完全免费***********/ /********************************/ /********************************/ 如果大家喜欢可以再给我提其他功能,有时间我加上 /*********************************************************************************/ 模板介绍: MySql.Data.dll :连接Mysql基本dl我们的的驱动。 foxjava.exe :直接运行程序 xml : Excel文件夹 ##### TemplateXml.xml 根据数据库对应表生成字段描述,生成后最好用WPS打开,然后重新另存为office认识的Excel template : 文件生成模板(非常重要的不能修改) ##### BasePojo.template 所有基础表对象都要继承,方便序列化(系统自动生成) ##### Pager.template 分页对象 (系统自动生成) ##### dao.template 数据库接口Dao(mybatis接口方式,在方法上写sql,复杂的使用sqlProvider) ##### daoSqlProvider.template 复杂sql提供者 ##### service.template 对外开放的接口 ##### serviceImpl.template 实现开放接口,基本数据操作逻辑 /*********************************************************************************/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值