mybatis中Mapper接口文件以及Example类实例解析

本文详细介绍如何使用MyBatis的Example和Condition类进行复杂的条件查询,包括创建查询实例、设置排序、定义查询条件等,并提供了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建Condition类继承Example类:

public class Condition extends Example {
    public Condition(Class<?> entityClass) {
        super(entityClass);
    }

    public Condition(Class<?> entityClass, boolean exists) {
        super(entityClass, exists);
    }

    public Condition(Class<?> entityClass, boolean exists, boolean notNull) {
        super(entityClass, exists, notNull);
    }
}

在controller中调用Condition类:

@PostMapping("/kjlist")
    public Result kjlist() {
        Condition condition = new Condition(Zwsx.class);
        Condition.Criteria criteria = condition.createCriteria();   //創建實例
        criteria.andEqualTo("type","1").andEqualTo("flag", "1").andEqualTo("xsbz","1");
        condition.setOrderByClause("seq");  //將seq字段升序排列
        //相當於:select * from tb_zwsx where type = '1' and flag = '1' and xsbz = '1' order by seq asc
        //從tb_zwsx表查詢出快捷事項的四個結果:新生重名查詢、身份證進度辦理查詢、單位/從業人員、房屋/居住人員
        List<Zwsx> list = zwsxService.findByCondition(condition);
        return ResultGenerator.genSuccessResult(list);
    }

下列是Example类:

	Example example = new Example();  
    example.setOrderByClause("字段名 ASC"); //升序排列,desc为降序排列。  
    example.setDistinct(false)//去除重复,boolean型,true为选择不重复的记录。  
    Criteria criteria = new Example().createCriteria();  
    is null;is not null;  
    equal to(value);not equal to(value);  
    GreaterThan(value);GreaterThanOrEqualTo(value);  
    LessThan(value); LessThanOrEqualTo(value);  
    in(item,item,item,...);not in(item,item,item,...);  
    like("%"+value+"%");not like("%"+value+"%");  
    Between(value1,value2);not between(value1,value2)  
      
       
      
    mybatis中mapper的实例函数:  
    int countByExample(UserExample example) thorws SQLException:按条件计数。  
    int deleteByPrimaryKey(Integer id) thorws SQLException:按主键删除。  
    int deleteByExample(UserExample example) thorws SQLException:按条件删除。  
    String/Integer insert(User record) thorws SQLException:插入(返回值为id值)  
    User selectByPrimaryKey(Integer id) thorws SQLException:按主键查询。  
    List<?>selectByExample(UserExample example) thorws SQLException:按条件查询  
    List<?>selectByExampleWithBLOGs(UserExample example) thorws SQLException:按  
      
    条件查询(包括BLOB字段)。只有当数据表中的字段类型有为二进制的才会产生。  
    int updateByPrimaryKey(User record) thorws SQLException:按主键更新  
    int updateByPrimaryKeySelective(User record) thorws SQLException:按主键更新  
      
    值不为null的字段  
    int updateByExample(User record, UserExample example) thorws SQLException:   
      
    按条件更新  
    int updateByExampleSelective(User record, UserExample example) thorws    
      
    SQLException:按条件更新值不为null的字段  
      
    mybatis中mapper的实例函数详解:  
    ① selectByPrimaryKey()  
      
    User user = ##Mapper.selectByPrimaryKey(100); 相当于select * from user where  
      
    id = 100selectByExample()selectByExampleWithBLOGs()  
      
    UserExample example = new UserExample();  
    Criteria criteria = example.createCriteria();  
    criteria.andUsernameEqualTo("joe");  
    criteria.andUsernameIsNull();  
    example.setOrderByClause("username asc,email desc");  
    List<?>list = Mapper.selectByExample(example);  
    相当于:select * from user where username = 'joe' and username is null order by username asc,email desc  
    注:在iBator 生成的文件UserExample.java中包含一个static 的内部类 Criteria ,  
      
    在Criteria中有很多方法,主要是定义SQL 语句where后的查询条件。  
      
    ③ insert()  
      
    User user = new User();  
    user.setId(101);  
    user.setUsername("test");  
    user.setPassword("123")  
    user.setEmail("joe@163.com");  
    ##Mapper.insert(user);  
    相当于:insert into user(ID,username,password,email) values (101,'test','123','joe@163.com');updateByPrimaryKey()updateByPrimaryKeySelective()  
      
    User user =new User();  
    user.setId(101);  
    user.setUsername("joe");  
    user.setPassword("joe");  
    user.setEmail("joe@163.com");  
    ##Mapper.updateByPrimaryKey(user);  
    相当于:update user set username='joe',password='joe',email='joe@163.com' where id=101  
      
    User user = new User();  
    user.setId(101);  
    user.setPassword("joe");  
    ##Mapper.updateByPrimaryKeySelective(user);  
    相当于:update user set password='joe' where id=101updateByExample()updateByExampleSelective()  
      
    UserExample example = new UserExample();  
    Criteria criteria = example.createCriteria();  
    criteria.andUsernameEqualTo("joe");  
    User user = new User();  
    user.setPassword("123");  
    ##Mapper.updateByPrimaryKeySelective(user,example);  
    相当于:update user set password='123' where username='joe'deleteByPrimaryKey()  
      
    ##Mapper.deleteByPrimaryKey(101);  相当于:delete from user where id=101deleteByExample()  
      
    UserExample example = new UserExample();  
    Criteria criteria = example.createCriteria();  
    criteria.andUsernameEqualTo("joe");  
    ##Mapper.deleteByExample(example);  
    相当于:delete from user where username='joe'countByExample()  
      
    UserExample example = new UserExample();  
    Criteria criteria = example.createCriteria();  
    criteria.andUsernameEqualTo("joe");  
    int count = ##Mapper.countByExample(example);  
    相当于:select count(*) from user where username='joe'  
### MyBatis 中 `mapper.xml` 文件的作用及用途 #### 1. 映射核心功能 在 MyBatis 框架中,`mapper.xml` 是用于定义 SQL 语句及其与 Java 方法之间映射关系的核心配置文件。它允许开发者将数据库中的表结构与 Java 对象进行关联,从而实现数据的持久化操作[^1]。 #### 2. 数据库交互支持 通过 `mapper.xml` 文件,可以灵活地编写各种类型的 SQL 查询语句(如 SELECT、INSERT、UPDATE 和 DELETE),并将其绑定到对应的 Java 接口方法上。这种设计使得开发人员能够更加专注于业务逻辑而无需手动管理 JDBC 的复杂细节。 #### 3. 配置结构说明 一个典型的 `mapper.xml` 文件通常由以下几个部分组成: - **XML 声明**:指定文档编码方式。 - **DOCTYPE 定义**:声明该文件遵循 MyBatis 的 DTD 规范。 - **<mapper> 根节点**:设置命名空间(namespace),对应于某个具体的 DAO 或者 Mapper 接口。 - **SQL 节点**:包括 `<select>`、`<insert>`、`<update>` 和 `<delete>` 等标签来描述具体的操作行为。 #### 4. 创建过程指导 为了方便项目管理和维护,在 IntelliJ IDEA 开发环境中可以通过特定步骤快速创建标准格式化的 `mapper.xml` 文件。例如,利用自定义模板机制简化重复劳动,并确保生成的内容符合框架要求[^2]。 #### 5. 解决常见问题 如果遇到 IDE 提示无法识别表字段或者表名的情况,则需确认是否已正确安装必要的插件组件,比如 "Database Tools and SQL" 和 "Java SQL Libraries"[^3]。 ```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.mapper.UserMapper"> <!-- Example of a select query --> <select id="selectUserById" resultType="com.example.model.User"> SELECT * FROM users WHERE id = #{id} </select> </mapper> ``` 上述代码片段展示了一个简单的 `mapper.xml` 实例,其中包含了针对用户表的一个查询操作。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值