mybatis tkmapper_MybatisPlus[通俗易懂]

mybatis tkmapper_MybatisPlus[通俗易懂]文章目录TKmybatis的使用TKmybatis的常用注解Mapper中的方法(dao继承可用)Example方法设置查询条件TKmybatis的使用pom.xml导入依赖https

TKmybatis的使用

  1. pom.xml导入依赖
        <!-- https://mvnrepository.com/artifact/tk.mybatis/mapper -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper</artifactId>
            <version>4.1.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/tk.mybatis/mapper-spring-boot-starter -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.0.3</version>
        </dependency>

【注意】如果在使用tkmybatis之前,你已经集成过mybatis,有mybatis的起步依赖mapper-spring-boot-starter,那么需要注释mybatis起步依赖,或者不添加tkmybatis的mapper-spring-boot-starter,否则会出报错**java.lang.NoSuchMethodException: tk.mybatis.mapper.provider.ExampleProvider.<init>**

  1. 实体类的相关配置,@Id、@Table、@Column等

TKmybatis的常用注解

注解 作用
@Table 指定该实体类对应的数据库表名 @Table(name = "tb_sy_company_info")
@Id 表示该字段对应数据库表的主键id
@GeneratedValue strategy表示使用数据库自带的主键生成策略,generator配置为”JDBC”,在数据插入完毕之后,会自动将主键id填充到实体类中。
@GeneratedValue(strategy = GenerationType.IDENTITY):主键自增
@Column 属性名和列名不一致进行匹配(数据库表以下划线,类属性是驼峰式)
@Transient注解 忽略作用,不与数据库表任何字段对应

@Table(name = "tb_sy_company_info") //数据库的表
@Data   //lombok 不用写get、set、tostring、构造方法等代码
//供货商(公司)表
public class Company { 
   
    //@Id注解:主键
    //@GeneratedValue(strategy = GenerationType.IDENTITY):主键自增
    //@Column注解:属性名和列名不一致匹配
    //@Transient注解:忽略,不与数据库表任何字段对应
    @Id
    @Column(name = "company_id")
    private String companyId;               //主键(UUID),供应商名称
    @Column(name="company_name")
    private String companyName;             //供货商名称
    @Column(name = "company_contact")
    private String companyContact;          //供货商联系人
    @Column(name = "company_phone")
    private String companyPhone;            //供货商联系电话
    @Column(name = "company_address")
    private String companyAddress;          //供货商地址
    @Column(name = "company_email")
    private String companyEmail;            //供货商邮箱
    @Column(name = "business_license")
    private String businessLicense;         //营业执照照片地址(src)
    @Column(name = "representative_id")
    private String representativeId;        //法人代表身份证证件号
    @Column(name = "representative_name")
    private String representativeName;      //法人代表姓名
    private Integer weight;	                //权重(根据权重排名显示)
    @Column(name = "company_status")
    private Integer companyStatus;         //激活状态 0:停用,1:启用
    @Column(name = "company_size")
    private Integer companySize;           //供货商公司规模
    @Column(name = "create_time")
    private Date createTime;	            //创建时间(申请通过时间)
    @Column(name = "update_time")
    private Date updateTime;	            //最后更新时间
    private String remark;	                //备注(供货商的介绍信息)

    @Transient
    private boolean check;          //忽略,不与数据库表对应(判断是否选中)
}

  1. dao层继承Mapper接口,dao extends Mapper<T>
import tk.mybatis.mapper.entity.Example;
public interface CompanyMapper extends Mapper<Company> { 
   
    //update、delete、select、insert方法可以全部省略,由tkmybatis实现
}

Mapper中的方法(dao继承可用)

Example example = new Example(JavaBean.class);
方法 功能说明
String/Integer insert(Javabean bean) thorws SQLException 整条插入数据(返回值为ID)
int insertSelective(Javabean bean); 有选择性的插入数据
int deleteByPrimaryKey(Integer id) thorws SQLException 按表的主键删除数据
int deleteByExample(UserExample example) thorws SQLException 指定条件删除
long countByExample(UserExample example) thorws SQLException 按条件查询满足条件的个数
Object selectByPrimaryKey(Integer id) thorws SQLException 主键查询,返回一个javabean对象
List selectByExample(UserExample example) thorws SQLException 按指定条件查询
List selectByExampleWithBLOGs(UserExample example) thorws SQLException 按指定条件查询(包括BLOB字段)。只有当数据表中的字段类型有为二进制的才会产生。
int updateByPrimaryKey(Javabean bean) thorws SQLException 按主键更新
int updateByPrimaryKeySelective(Javabean bean) thorws SQLException 主键更新值不为null的字段
int updateByExample(Javabean bean, UserExample example) thorws SQLException 条件更新example
int updateByExampleSelective(Javabean bean, UserExample example) thorws SQLException 条件更新值不为null的字段
  1. 在启动类Application上使用@MapperScan()扫描Mapper接口
@SpringBootApplication
@MapperScan(basePackages = "com.xgf.online_mall.system.mapper")     //扫描mapper包
public class OnlineMallApplication { 
   

    public static void main(String[] args) { 
   
        SpringApplication.run(OnlineMallApplication.class, args);
    }

}
  1. application.properties配置文件配置数据库属性
# 数据库配置
spring:
  datasource: # hikari
    type: com.zaxxer.hikari.HikariDataSource  # 数据库类型,默认就是hikari(如果不改的话可以不写)
    driver-class-name: com.mysql.cj.jdbc.Driver # mysql 8 需要添加时区
    username: root
    password: 861221293
    url: jdbc:mysql://localhost:3306/onlinemall?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8  # serverTimezone=GMT%2B8表示东8区,不然报错time zone

# mybatis配置
mybatis:
  type-aliases-package: com.xgf.online_mall.system.domain # 别名
  mapper-locations: classpath*:com/xgf/online_mall/mapper/*.xml # use xml 使用xml配置的时候需要
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 开启mybatis日志
  1. Service调用
@Service
public class CompanyServiceImpl implements ICompanyService { 
   

    @Autowired
    CompanyMapper companyMapper;

    @Override
    public List<Company> findAll() { 
   
        Example example = new Example(Company.class);  //查询条件
        Example.Criteria criteria = example.createCriteria();
        //criteria.andEqualTo(company); //根据值来拼接出where 条件
        //where by username=?
        //where by name=?
        List<Company> companyList = companyMapper.selectByExample(example);
        return companyList;
    }

    @Override
    public void saveCompany(Company company) { 
   
        try { 
   
            companyMapper.insert(company);  //添加
        }catch (Exception e){ 
   
            e.printStackTrace();
        }

    }
}

Example方法设置查询条件

example 用于添加条件,相当与sql语句中的where后面的条件部分。

Example.Criteria criteria = example.createCriteria();

【注意】

  1. 没写example.createCriteria();,然后执行selectByExample(example)会查询全部数据。
  2. example没加条件,执行查询语句selectByExample(example);也是查询全部。
example方法,criteria方法 说明
example.setOrderByClause(“字段名 ASC”); 添加升序(ASC)排列条件,DESC为降序。example.setOrderByClause("AFTER_CHECK_TIMEDESC");
example.setDistinct(boolean b) 去除重复,boolean类型,true:去重(无重复)
criteria.andXxxIsNull 添加字段xxx为null的条件
criteria.andXxxIsNotNull 添加字段xxx不为null的条件
criteria.andXxxEqualTo(value) 添加字段xxx等于value条件
criteria.andXxxNotEqualTo(value) 添加字段xxx不等于value条件
criteria.andXxxGreaterThan(value) 添加字段xxx大于value条件
criteria.andXxxGreaterThanOrEqualTo(value) 添加字段xxx大于等于value条件
criteria.andXxxLessThan(value) 添加字段xxx小于value条件
criteria.andXxxLessThanOrEqualTo(value) 添加字段xxx小于等于value条件
criteria.andXxxIn(List<?>) 添加字段xxx值在List<?>列表条件
criteria.andXxxNotIn(List<?>) 添加字段xxx值不在List<?>条件
criteria.andXxxLike(“%”+value+”%”) 添加字段xxx值为value的模糊查询条件
criteria.andXxxNotLike(“%”+value+”%”) 添加字段xxx值不为value的模糊查询条件
criteria.andXxxBetween(value1,value2) 添加字段xxx值在value1和value2之间条件
criteria.andXxxNotBetween(value1,value2) 添加字段xxx值不在value1和value2之间条件

7. 创建测试类测试增加查询

@SpringBootTest
public class TestCompanyServiceImpl { 
   

    @Autowired
    CompanyServiceImpl companyService;

    //测试添加
    @Test
    public void test01(){ 
   
        Company company = new Company();
        company.setCompanyId(UUID.randomUUID().toString());
        company.setCompanyName("供货商名称");
        company.setCompanyEmail("email邮箱");
        company.setCompanyContact("供货商联系人");
        company.setCompanyAddress("供货商地址");
        company.setBusinessLicense("c://"+company.getCompanyName()+"/"+"license.jpg");
        company.setRepresentativeId("123456789987654321");
        company.setWeight(2);

        companyService.saveCompany(company);    //保存数据
    }


    //测试查询所有数据
    @Test
    public void test02(){ 
   
        List<Company> companyServiceAll = companyService.findAll();
        System.out.println(companyServiceAll);
    }
}
  1. 测试结果
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

今天的文章mybatis tkmapper_MybatisPlus[通俗易懂]分享到此就结束了,感谢您的阅读。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/77670.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注