TKmybatis的使用,MyBatis的Mapper接口、Example方法

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
@GeneratedValuestrategy表示使用数据库自带的主键生成策略,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. 测试结果
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
`tk.mybatis.mapper.common.example` 包中提供了一些通用的 Mapper 方法,其中包括了 `deleteByExample` 方法,用于根据条件删除数据库中的数据。使用方法时,需要在 Mapper 接口中继承 `tk.mybatis.mapper.common.example.DeleteByExampleMapper` 接口,并传入一个 `Example` 对象作为参数,该对象中包含了删除数据的条件。具体的示例代码如下: ```java public interface UserMapper extends Mapper<User>, DeleteByExampleMapper<User> { } public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public int deleteUserByExample(String name, int age) { // 创建 Example 对象 Example example = new Example(User.class); Example.Criteria criteria = example.createCriteria(); // 设置查询条件 criteria.andEqualTo("name", name); criteria.andEqualTo("age", age); // 调用 deleteByExample 方法删除用户 return userMapper.deleteByExample(example); } } ``` 在上述代码中,我们定义了一个 `UserMapper` 接口,该接口继承了 `Mapper<User>` 和 `DeleteByExampleMapper<User>` 接口,其中 `Mapper<User>` 是 `tk.mybatis.mapper.common.Mapper` 接口的泛型实现,用于提供基本的 CRUD 操作;`DeleteByExampleMapper<User>` 接口则提供了 `deleteByExample` 方法,用于根据条件删除数据库中的数据。在 `UserServiceImpl` 中,我们通过创建一个 `Example` 对象,并设置查询条件,最后调用 `deleteByExample` 方法删除满足条件的用户。其中,`Example` 对象也是 MyBatis 自动生成的,它根据实体类中的属性生成了一些查询条件的方法,我们可以通过 `example.createCriteria()` 方法获取到一个 `Criteria` 对象,并在该对象中设置查询条件。
评论 40
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值