Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
MyBatis Mapper
https://mapper.mybatis.io
Admin
A new generation of MyBatis Mapper, simple to use, no configuration required.
Tokens:
104,291
Snippets:
499
Trust Score:
8
Update:
9 hours ago
Context
Chat
Benchmark
39.67
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Create Example instance with new Example<>() Source: https://mapper.mybatis.io/docs/v2.x/5.service Shows how to obtain an Example<T> instance by directly instantiating it with new Example<>(). This is an alternative to using the default example() method provided by ExampleService. ```java Example<User> example = new Example<>(); ``` -------------------------------- ### selectCursorByExample(E example) Source: https://mapper.mybatis.io/docs/v2.x/2.4.cursormapper 根据 Example 条件查询,返回游标类型的结果集,允许逐个从数据库取值。 ```APIDOC ## selectCursorByExample(E example) ### Description 根据 Example 条件查询,返回游标类型的结果集,允许逐个从数据库取值。 ### Method selectCursorByExample ### Endpoint CursorMapper.selectCursorByExample(E example) ### Parameters - **example** (E) - Required - Example 对象,包含查询条件 ### Response #### Success Response - **Cursor<T>** - 游标对象,用于逐个获取查询结果 #### Response Example ```java Cursor<User> userCursor = mapper.selectCursorByExample(example); Iterator<User> userIterator = userCursor.iterator(); while (userIterator.hasNext()) { User u = userIterator.next(); // 处理每条记录 } ``` ``` -------------------------------- ### Example Usage with ExampleMapper Source: https://mapper.mybatis.io/docs/v2.x/2.3.examplemapper Demonstrates how to use Example with ExampleMapper methods like deleteByExample and updateByExample, including the use of clear() to reuse the Example object. ```APIDOC ## Example Usage with ExampleMapper ### Description Shows how to create an Example, use it with ExampleMapper methods, and reuse it after calling clear(). ### Example ```java Example<User> example = new Example(); example.createCriteria().andGreaterThan(User::getId, 10L).andLike(User::getUserName, "殷%"); Assert.assertEquals(3, exampleMapper.deleteByExample(example)); example.clear(); example.createCriteria().andEqualTo(User::getId, 1L); User user = new User(); user.setId(1L); user.setUserName("男主角"); Assert.assertEquals(1, exampleMapper.updateByExample(user, example)); ``` ``` -------------------------------- ### selectByExample(E example) Source: https://mapper.mybatis.io/docs/v2.x/2.3.examplemapper Queries a list of entities based on the Example conditions. ```APIDOC ## selectByExample(E example) ### Description Queries a list of entities based on the Example conditions. ### Method Interface method ### Signature `List<T> selectByExample(E example)` ### Parameters - **example** (E) - Required - The Example object containing the query conditions. ### Returns - **List<T>** - A list of entities matching the conditions. ``` -------------------------------- ### example() Source: https://mapper.mybatis.io/docs/v2.x/2.3.examplemapper Returns a new Example<T> object for building query conditions. This is a default method that can be overridden. ```APIDOC ## example() ### Description Returns a new `Example<T>` object for building query conditions. This is a default method that can be overridden. ### Method Default method ### Signature `default Example<T> example()` ### Returns - **Example<T>** - A new Example object. ``` -------------------------------- ### startSql and endSql usage example Source: https://mapper.mybatis.io/docs/v2.x/2.3.examplemapper Example showing how to set startSql and endSql together to wrap a query. ```java example.setStartSql("select * from ("); example.setEndSql(") tmp limit 1"); ``` -------------------------------- ### Example 条件中使用字符串字段名和列名 Source: https://mapper.mybatis.io/docs/v2.x/2.5.fnmapper 演示在 Example 的 createCriteria 中使用 Fn.field 和 Fn.column 指定字段名或列名。 ```java //使用字段名 example.createCriteria().andEqualTo(Fn.field(User.class, "roleId"), user.getRoleId()); //使用列名 example.createCriteria().andEqualTo(Fn.column(User.class, "role_id"), user.getRoleId()); ``` -------------------------------- ### countByExample(E example) Source: https://mapper.mybatis.io/docs/v2.x/2.3.examplemapper Counts the number of records matching the Example conditions. ```APIDOC ## countByExample(E example) ### Description Counts the number of records matching the Example conditions. ### Method Interface method ### Signature `int countByExample(E example)` ### Parameters - **example** (E) - Required - The Example object containing the count conditions. ### Returns - **int** - The number of matching records. ``` -------------------------------- ### Example with single-level OR condition using andOr Source: https://mapper.mybatis.io/releases/1.0.3 Shows how to build an Example with a single-level OR condition using andOr and orPart. The example uses UserMapper2 and Example<User> to create criteria with andEqualTo and andLike. Note that nested andOr inside andOr is not supported. ```java //example: UserMapper2 mapper = sqlSession.getMapper(UserMapper2.class); Example<User> example = mapper.example(); example.createCriteria() .andEqualTo(User::getSex,"男") .andOr(example.orPart() .andLike(User::getUserName,"杨%"), example.orPart() .andLike(User::getUserName,"俞%") .andLike(User::getUserName,"%舟")); ``` ```sql xxx WHERE ( sex = ? AND ( ( name LIKE ? ) OR ( name LIKE ? AND name LIKE ? ) ) ) ``` -------------------------------- ### clear() Method Source: https://mapper.mybatis.io/docs/v2.x/2.3.examplemapper Resets all settings on the Example object, allowing it to be reused. Note that allowCriteriaEmpty is reset to false even if the Example was created with Example(true). ```APIDOC ## clear() Method ### Description Clears all settings on the Example object, making it reusable. This includes clearing oredCriteria, orderByClause, distinct, selectColumns, startSql, endSql, and setting allowCriteriaEmpty to false. ### Method clear() ### Parameters None ### Return Value void ### Example ```java Example<User> example = new Example(); example.createCriteria().andGreaterThan(User::getId, 10L).andLike(User::getUserName, "殷%"); // ... use example ... example.clear(); // reset for reuse ``` ``` -------------------------------- ### updateByExample(T entity, E example) Source: https://mapper.mybatis.io/docs/v2.x/2.3.examplemapper Updates all fields of the entity based on the Example conditions. ```APIDOC ## updateByExample(T entity, E example) ### Description Updates all fields of the entity based on the Example conditions. ### Method Interface method ### Signature `int updateByExample(@Param("entity") T entity, @Param("example") E example)` ### Parameters - **entity** (T) - Required - The entity containing the new values. - **example** (E) - Required - The Example object containing the update conditions. ### Returns - **int** - The number of updated records. ``` -------------------------------- ### selectOneByExample(E example) Source: https://mapper.mybatis.io/docs/v2.x/2.3.examplemapper Queries a single entity based on the Example conditions. Returns an Optional that may be empty if no record is found. ```APIDOC ## selectOneByExample(E example) ### Description Queries a single entity based on the Example conditions. Returns an Optional that may be empty if no record is found. ### Method Interface method ### Signature `Optional<T> selectOneByExample(E example)` ### Parameters - **example** (E) - Required - The Example object containing the query conditions. ### Returns - **Optional<T>** - An Optional containing the entity if found, otherwise empty. ``` -------------------------------- ### deleteByExample(E example) Source: https://mapper.mybatis.io/docs/v2.x/2.3.examplemapper Deletes records based on the Example conditions. ```APIDOC ## deleteByExample(E example) ### Description Deletes records based on the Example conditions. ### Method Interface method ### Signature `int deleteByExample(E example)` ### Parameters - **example** (E) - Required - The Example object containing the delete conditions. ### Returns - **int** - The number of deleted records. ``` -------------------------------- ### Generated SQL for ExampleWrapper Source: https://mapper.mybatis.io/docs/v2.x/1.getting-started SQL generated by the ExampleWrapper example, showing the WHERE clause with conditions. ```sql SELECT id,name AS userName,sex FROM user WHERE ( sex = ? AND ( ( id > ? ) OR ( id < ? ) ) ) OR ( name LIKE ? ) ``` -------------------------------- ### Example usage with deleteByExample and updateByExample Source: https://mapper.mybatis.io/docs/v2.x/2.3.examplemapper Demonstrates using an Example object with clear() to reuse it. First, it creates a criteria with andGreaterThan and andLike, then deletes matching records. After clearing, it sets a new criteria with andEqualTo and updates a user record. ```java Example<User> example = new Example(); example.createCriteria().andGreaterThan(User::getId, 10L).andLike(User::getUserName, "殷%"); Assert.assertEquals(3, exampleMapper.deleteByExample(example)); example.clear(); example.createCriteria().andEqualTo(User::getId, 1L); User user = new User(); user.setId(1L); user.setUserName("男主角"); Assert.assertEquals(1, exampleMapper.updateByExample(user, example)); ``` -------------------------------- ### clear() method implementation Source: https://mapper.mybatis.io/docs/v2.x/2.3.examplemapper Shows the clear() method that resets all Example settings, including oredCriteria, orderByClause, distinct, selectColumns, startSql, endSql, and allowCriteriaEmpty. Note that allowCriteriaEmpty is set to false even if the Example was created with Example(true). ```java /** * 清除所有设置 */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; selectColumns = null; startSql = null; endSql = null; allowCriteriaEmpty = false; } ``` -------------------------------- ### Example<T> selectColumns(Fn<T, Object>... fns) Source: https://mapper.mybatis.io/docs/v2.x/2.3.examplemapper Specifies the columns to select in the query. Accepts one or more method references and appends them to the SELECT clause. Returns the Example instance for chaining. ```APIDOC ## Example<T> selectColumns(Fn<T, Object>... fns) ### Description Specifies the columns to select in the query. Accepts one or more method references and appends them to the SELECT clause. Returns the Example instance for chaining. ### Method selectColumns ### Parameters - **fns** (Fn<T, Object>...) - Required - Method references to the columns to select. ### Return Value - **Example<T>** - The current Example instance for method chaining. ### Example ```java <User> example = exampleMapper.example(); example.selectColumns(User::getUserName, User::getSex); // Can be called multiple times to append columns example.selectColumns(User::getId); ``` This generates SQL like `select name as userName, sex, id from ...`. ``` -------------------------------- ### testExampleUseCondition - Example with useCondition parameter Source: https://mapper.mybatis.io/releases/2.2.2 Shows how to use the new boolean useCondition parameter in Example criteria methods. Conditions are only applied when the boolean is true, allowing dynamic query building. The example counts users matching the criteria and expects 5 results. ```java @Test public void testExampleUseCondition() { try (SqlSession sqlSession = getSqlSession()) { ExampleMapper<User, Example<User>> exampleMapper = sqlSession.getMapper(UserMapper.class); Example<User> example = new Example<>(); User user = new User(); user.setUserName("殷%"); example.createCriteria() .andNotEqualTo(Objects.nonNull(user.getId()), User::getId, user.getId()) .andLike(Utils.isNotBlank(user.getUserName()), User::getUserName, user.getUserName()) .andEqualTo(Utils.isNotBlank(user.getSex()), User::getSex, user.getSex()); Assert.assertEquals(5, exampleMapper.countByExample(example)); } } ``` -------------------------------- ### ENV and SYS variable output example (macOS) Source: https://mapper.mybatis.io/docs/v2.x/7.generator Example output from the code generator showing available SYS and ENV variables on macOS. Use this to find variable names to reference in templates, e.g., ${SYS['user.home']} and ${ENV['HOME']}. ```text [main] TRACE Project - SYS可用参数: [main] TRACE Project - SYS['user.country'] = CN [main] TRACE Project - SYS['user.home'] = /Users/liuzh [main] TRACE Project - SYS['user.dir'] = /Users/liuzh/IdeaProjects/rui/core [main] TRACE Project - ENV可用参数: [main] TRACE Project - ENV['USER'] = liuzh [main] TRACE Project - ENV['PWD'] = /Users/liuzh/IdeaProjects/rui/core [main] TRACE Project - ENV['HOME'] = /Users/liuzh ``` -------------------------------- ### Example<T> orderBy(Fn<T, Object> fn, Order order) Source: https://mapper.mybatis.io/docs/v2.x/2.3.examplemapper Sets the ORDER BY clause using a method reference to a column and a sort order. Returns the Example instance for chaining. ```APIDOC ## Example<T> orderBy(Fn<T, Object> fn, Order order) ### Description Sets the ORDER BY clause using a method reference to a column and a sort order. Returns the Example instance for chaining. ### Method orderBy ### Parameters - **fn** (Fn<T, Object>) - Required - Method reference to the sort column. - **order** (Order) - Required - Sort order (e.g., ASC, DESC). ### Return Value - **Example<T>** - The current Example instance for method chaining. ### Example ```java example.orderBy(User::getId, Example.Order.DESC); ``` This generates `ORDER BY id desc`. ``` -------------------------------- ### orderBy usage example Source: https://mapper.mybatis.io/docs/v2.x/2.3.examplemapper Usage example for the orderBy method, sorting by User::getId in descending order, generating 'ORDER BY id desc'. ```java example.orderBy(User::getId, Example.Order.DESC); ``` -------------------------------- ### selectColumns usage example Source: https://mapper.mybatis.io/docs/v2.x/2.3.examplemapper Usage example for the selectColumns method, specifying columns via method references and showing that multiple calls append additional columns. ```java <User> example = exampleMapper.example(); example.selectColumns(User::getUserName, User::getSex); //可以多次调用追加查询列 example.selectColumns(User::getId); ``` -------------------------------- ### setStartSql(String startSql) Source: https://mapper.mybatis.io/docs/v2.x/2.3.examplemapper Sets the start SQL that is prepended to the generated SQL. Use with caution to prevent SQL injection. ```APIDOC ## setStartSql(String startSql) ### Description Sets the start SQL that is prepended to the generated SQL. Use with caution to prevent SQL injection. ### Method setStartSql ### Parameters - **startSql** (String) - Required - The start SQL to prepend. ### Request Example ```java example.setStartSql("select * from ("); ``` ### Response No return value. ``` -------------------------------- ### BaseMapper 中的 wrapper() 方法定义 Source: https://mapper.mybatis.io/docs/v2.x/2.3.examplewrapper 从 1.2.0 版本开始,BaseMapper 中新增了 wrapper() 方法,返回 ExampleWrapper 对象,用于简化 Example 的使用。 ```java /** * Example 查询封装 */ default ExampleWrapper<T, I> wrapper() { return new ExampleWrapper<>(BaseMapper.this, example()); } ``` -------------------------------- ### ExampleWrapper or() 执行日志 Source: https://mapper.mybatis.io/docs/v2.x/2.3.examplewrapper 上述代码执行时输出的 SQL 日志,展示了生成的 SQL 和参数。 ```log selectByExample - ==> Preparing: SELECT id,name AS userName,sex FROM user WHERE ( sex = ? AND ( ( id > ? ) OR ( id < ? ) ) ) OR ( name LIKE ? ) selectByExample - ==> Parameters: 女(String), 40(Integer), 10(Integer), 张%(String) selectByExample - <== Columns: ID, USERNAME, SEX selectByExample - <== Row: 2, 赵敏, 女 selectByExample - <== Row: 3, 周芷若, 女 selectByExample - <== Row: 4, 小昭, 女 selectByExample - <== Row: 5, 殷离, 女 selectByExample - <== Row: 6, 张翠山, 男 selectByExample - <== Row: 7, 殷素素, 女 selectByExample - <== Row: 9, 张三丰, 男 selectByExample - <== Row: 13, 张松溪, 男 selectByExample - <== Row: 41, 武青婴, 女 selectByExample - <== Row: 46, 郭襄, 女 selectByExample - <== Row: 47, 张君宝, 男 selectByExample - <== Row: 50, 韩姬, 女 selectByExample - <== Row: 51, 黄衫女子, 女 selectByExample - <== Total: 13 ``` -------------------------------- ### ExampleWrapper 基本用法对应的数据库日志 Source: https://mapper.mybatis.io/docs/v2.x/2.3.examplewrapper 展示了上述基本用法示例中所有方法对应的 SQL 日志,包括 Preparing、Parameters 和 Total/Updates 等信息。 ```log countByExample - ==> Preparing: SELECT COUNT( * ) FROM user WHERE ( sex = ? AND ( ( name LIKE ? ) ) ) countByExample - ==> Parameters: 男(String), 杨%(String) countByExample - <== Total: 1 countByExample - ==> Preparing: SELECT COUNT( * ) FROM user WHERE ( sex = ? AND ( ( name LIKE ? ) OR ( name LIKE ? AND name LIKE ? ) ) ) countByExample - ==> Parameters: 男(String), 杨%(String), 俞%(String), %舟(String) countByExample - <== Total: 1 selectByExample - ==> Preparing: SELECT name AS userName,sex FROM user WHERE ( ( ( name LIKE ? ) OR ( sex = ? ) ) ) OR ( id > ? AND id <= ? AND sex = ? ) selectByExample - ==> Parameters: 杨%(String), 男(String), 1(Long), 16(Long), 女(String) selectByExample - <== Total: 44 selectByExample - ==> Preparing: SELECT id,name AS userName,sex FROM user WHERE ( id > ? ) OR ( id <= ? ) OR ( sex = ? ) selectByExample - ==> Parameters: 50(Long), 5(Long), 女(String) countByExample - ==> Preparing: SELECT COUNT( distinct sex ) FROM user WHERE ( id > ? ) OR ( id <= ? ) OR ( sex = ? ) countByExample - ==> Parameters: 50(Long), 5(Long), 女(String) countByExample - <== Total: 1 updateByExampleSetValues - ==> Preparing: UPDATE user SET name = ?, sex = ? WHERE ( name = ? ) updateByExampleSetValues - ==> Parameters: 弓长无忌(String), M(String), 张无忌(String) updateByExampleSetValues - <== Updates: 1 countByExample - ==> Preparing: SELECT COUNT( * ) FROM user WHERE ( sex = ? ) countByExample - ==> Parameters: M(String) countByExample - <== Total: 1 ``` -------------------------------- ### ExampleWrapper 基本用法示例 Source: https://mapper.mybatis.io/docs/v2.x/2.3.examplewrapper 展示了 ExampleWrapper 的常见用法,包括条件查询、or 嵌套、select 列、多次使用 wrapper、更新操作等。注意 contains、startsWith、endsWith 方法会自动添加 %,而 like 和 notLike 需要手动添加。 ```java //获取 Mapper,在 Spring 中可以直接注入使用 UserMapper2 mapper = sqlSession.getMapper(UserMapper2.class); //查询 "sex=男 and (name like '杨%') 的数量 long count = mapper.wrapper().eq(User::getSex, "男") .or( c -> c.startsWith(User::getUserName, "杨") ).count(); Assert.assertEquals(1, count); //查询 "sex=男 and (name like '杨%' or (name like '俞%' and name like '%舟')) 的数量 count = mapper.wrapper().eq(User::getSex, "男") .or( c -> c.startsWith(User::getUserName, "杨"), c -> c.startsWith(User::getUserName, "俞").endsWith(User::getUserName, "舟") ).count(); Assert.assertEquals(2, count); //查询 name 和 sex 列,条件为 (name like '杨%' or sex = '男') or id > 1 and id <= 16 and sex = '女' 的数据 List<User> users = mapper.wrapper() .select(User::getUserName, User::getSex) .or(c -> c.startsWith(User::getUserName, "杨"), c -> c.eq(User::getSex, "男")) .or() .gt(User::getId, 1L) .le(User::getId, 16L) .eq(User::getSex, "女").list(); //构建的wrapper可以多次使用 //查询条件为 id > 50 or id <= 5 or sex = '女' ExampleWrapper<User, Long> wrapper = mapper.wrapper() .gt(User::getId, 50L) .or() .le(User::getId, 5L) .or() .eq(User::getSex, "女"); //使用当前条件获取前5条数据 users = wrapper.top(5); Assert.assertEquals(5, users.size()); //追加条件后查询数量 count = wrapper.select(User::getSex).distinct().count(); Assert.assertEquals(2, count); //根据条件"name=张无忌",更新名字和性别 Assert.assertEquals(1, mapper.wrapper() .set(User::getUserName, "弓长无忌") .set(User::getSex, "M") .eq(User::getUserName, "张无忌").update()); //根据条件"sex=M"查询数量 Assert.assertEquals(1, mapper.wrapper().eq(User::getSex, "M").count()); ``` -------------------------------- ### Example<T> Class Fields Source: https://mapper.mybatis.io/docs/v2.x/2.3.examplemapper Describes the special fields of the Example class that can be used to customize queries. ```APIDOC ## Example<T> Class Fields ### Description Describes the special fields of the Example class that can be used to customize queries. ### Fields - **orderByClause** (String) - Sorting field. - **distinct** (boolean) - Whether to use DISTINCT. - **selectColumns** (String) - Specifies the columns to select. - **startSql** (String) - SQL to prepend to the query. Caution: prevent SQL injection. - **endSql** (String) - SQL to append to the query. Caution: prevent SQL injection. - **oredCriteria** (List<Criteria<T>>) - Multiple condition groups connected by OR. - **allowCriteriaEmpty** (boolean) - Whether to allow empty query conditions. ``` -------------------------------- ### updateByExampleSelective(T entity, E example) Source: https://mapper.mybatis.io/docs/v2.x/2.3.examplemapper Updates only non-null fields of the entity based on the Example conditions. ```APIDOC ## updateByExampleSelective(T entity, E example) ### Description Updates only non-null fields of the entity based on the Example conditions. ### Method Interface method ### Signature `int updateByExampleSelective(@Param("entity") T entity, @Param("example") E example)` ### Parameters - **entity** (T) - Required - The entity containing the new values; only non-null fields will be updated. - **example** (E) - Required - The Example object containing the update conditions. ### Returns - **int** - The number of updated records. ``` -------------------------------- ### ExampleWrapper chain usage Source: https://mapper.mybatis.io/docs/v2.x/1.getting-started Chainable ExampleWrapper usage with eq, or, and startsWith conditions. ```java mapper.wrapper() .eq(User::getSex, "女") .or(c -> c.gt(User::getId, 40), c -> c.lt(User::getId, 10)) .or() .startsWith(User::getUserName, "张").list(); ``` -------------------------------- ### project.yaml 完整配置示例 Source: https://mapper.mybatis.io/docs/v2.x/7.generator 展示代码生成器 project.yaml 的完整配置,包含模板、路径、数据库连接、表配置、类型标签、关键字包装、附加属性和文件结构。所有配置项均以注释说明。 ```yaml # 模板的名字,生成代码的根目录名称 name: mybatis-mapper-demo # 代码生成的路径,可以使用 SYS 和 ENV 等变量,具体包含的内容和运行环境有关 # user.dir 为当前运行命令的目录,path 不设置时的默认值也是当前路径 # 当 path 路径以 .zip 后缀结尾时,会将生成的目录结构和代码放到压缩包中 #【命令行】可以通过 —o 重新指定位置 path: ${SYS['user.dir']}/ # 模板文件所在路径,默认为相对 path 所在的位置,不设置时和 path 相同 #【命令行】可以通过 —T 重新指定位置 templates: mapper-templates # 数据库配置 database: # 数据库连接配置 jdbcConnection: # 使用方言,默认为 JDBC 方式,可能会取不到表或字段注释 # 后续介绍如何通过字典匹配注释值 #【命令行】可以通过 --jdbc.dialect 覆盖 dialect: MYSQL # jdbc驱动 #【命令行】可以通过 --jdbc.driver 覆盖 driver: com.mysql.jdbc.Driver # jdbc连接地址 #【命令行】可以通过 --jdbc.url 覆盖 url: jdbc:mysql://localhost:3306/test?useSSL=false # 用户名 #【命令行】可以通过 --jdbc.user 覆盖 user: root # 密码 #【命令行】可以通过 --jdbc.password 覆盖 password: root # 获取表配置,支持 % 和 _ 模糊匹配,可以配置多个值 # 还有一个支持复杂规则 tableRules 属性后续单独介绍 #【命令行】可以通过 -t table1,table2 覆盖 tables: - '%' # 根据类型对字段类型打标签, 可以通过 column.tags.TAG 的 true/false 来判断当前列是否有该标签 # 主要对列进行分类,方便后续模板中的使用 typeTags: # 示例,针对日期时间设置 jdbcType 标签,生成的代码中,如果有该标签,会指定 jdbcType 的值 jdbcType: - DATE - TIME - TIMESTAMP # 关键字包装,这里的示例针对 MySQL,不提供默认值,需要根据数据库语法进行设置,其中的 %s 为关键字(表名或列名) keywordWrap: "`%s`" # 数据库关键字,列举的关键字会进行包装处理,没有默认值,需要自己配置所有可能的关键字 keywords: - order - desc # 附加属性 #【命令行】可以通过 -AbasePackage=com.company 覆盖或增加新属性 attrs: # 子目录(文件)可以通过 parent.parent...attrs.属性名 可以逐级向上使用属性 # 这里设置了一个基础包名 basePackage: io.mybatis.demo.mybatis # 子目录(文件) files: # 文件名,可以 / 设置多级目录 - name: src/main # 子目录(文件) files: - name: java files: # 包,可以多层,名称可以引用当前结构的所有属性,也可以使用 tables 数据表信息 - name: '${project.attrs.basePackage}' # 设置类型为 package,尽可能都指定,默认会计算,默认为目录。包下面的默认都是包 type: PACKAGE files: # 包名 - name: mapper files: # 模板文件,下面 iter 对 tables 所有表进行迭代,因此这里的模板会根据表的数量进行循环生成 # 迭代循环时,单个迭代对象的默认名为 it,因此这里的 name 就是表名(类名形式)为前缀的 Mapper 接口 - name: '${it.name.className}Mapper.java' # 使用的模板名,会从上面配置的 templates 下面查找 # 包含多级目录时,这里可以指定相对 templates 的路径 file: mapper.java # 可选配置 iter, 迭代的数据对象,当前可选为 tables 为反射的数据库表信息 # iter 值使用 mvel 表达式取值,除 tables 外也可以对当前 yaml 中的集合类型进行迭代,例如 project.files iter: tables # 可选配置 iterName,默认值为 it,在模板和上面的 name 中可以使用改变量的值 # iterName: it # 可选配置 filter, 绑定数据过滤器,使用 mvel 表达式,过滤条件不满足时不执行当前的操作,不生成相应的目录或文件 # filter: tables.size() > 0 # 仅仅是示例,size=0时本身也不会循环 # 可选配置 itFilter,迭代数据过滤器,使用 mvel 表达式,当指定 iter 时,对迭代的数据进行过滤 # 不满足条件时,只忽略当前的 it 数据,下面示例中当表名以 sys 为前缀时生成目录或代码 # iterFilter: it.name.original.o.startsWith("sys") # 可选配置 enabled,默认 true,当前目录(文件)有效,会生成,设置为 false 时忽略 # enabled: true # 可选配置 mode,默认值为 OVERRIDE,生成目录或文件时覆盖,可选值为: # OVERRIDE: 覆盖 # ONCE: 只生成一次,或者如果目录或文件已存在时不生成(目录存在时,子文件也不会生成) # MERGE: 合并已存在的文件和新生成的文件,需要满足规则才能合并 # mode: OVERRIDE # 可选配置 times,默认值 1,默认情况下,模板只经过一次变量替换,有时存在多层变量嵌套时,执行多次才能全部替换 # times: 1 - name: model files: - name: '${it.name.className}.java' # 此处有2种模板示例,分别列出来加了注释 file: model.java # file: model-lombok.java iter: tables - name: service files: - name: '${it.name.className}Service.java' file: service.java iter: tables - name: impl files: - name: '${it.name.className}ServiceImpl.java' file: serviceImpl.java iter: tables - name: resources files: - name: mappers files: - name: '${it.name.className}Mapper.xml' iter: tables file: mapper.xml ``` -------------------------------- ### Unit test for updateByExampleSetValues with TypeHandler Source: https://mapper.mybatis.io/releases/2.2.3 A unit test demonstrating the use of Example with a TypeHandler-configured field. It creates an Example, sets a criteria, and updates a field with an object type, then rolls back the transaction. ```java @Test public void testUpdateByExampleSetValues() { SqlSession sqlSession = getSqlSession(); try { ExampleMapper<UserAuto, Example<UserAuto>> exampleMapper = sqlSession.getMapper(UserAutoBaseMapper.class); Example<UserAuto> example = new Example(); example.createCriteria().andEqualTo(UserAuto::getId, 1L); example.set(UserAuto::getAddress, new UserAuto.Address("河北省", "秦皇岛市")); Assert.assertEquals(1, exampleMapper.updateByExampleSetValues(example)); sqlSession.rollback(); } finally { //不要忘记关闭sqlSession sqlSession.close(); } } ``` -------------------------------- ### Example serviceImpl.java template with Dao suffix Source: https://mapper.mybatis.io/docs/v2.x/7.generator Shows how to use the custom Dao suffix in the service implementation template. The import and class definition must match the configured class name rule. ```java //省略其他 import ${project.attrs.basePackage}.mapper.${it.name.className}Dao; //省略其他 @Service public class ${it.name.className}ServiceImpl extends AbstractService<${it.name.className}, Long, ${it.name.className}Dao> implements ${it.name.className}Service { } ``` -------------------------------- ### Example class special fields Source: https://mapper.mybatis.io/docs/v2.x/2.3.examplemapper Shows the fields added to the Example class: orderByClause, distinct, selectColumns, startSql, endSql, oredCriteria, and allowCriteriaEmpty. The startSql and endSql fields are noted to prevent SQL injection. ```java public class Example<T> { /** * 排序字段 */ protected String orderByClause; /** * 是否使用 distinct */ protected boolean distinct; /** * 指定查询列 */ protected String selectColumns; /** * 起始 SQL,添加到 SQL 前,注意防止 SQL 注入 */ protected String startSql; /** * 结尾 SQL,添加到 SQL 最后,注意防止 SQL 注入 */ protected String endSql; /** * 多组条件通过 OR 连接 */ protected List<Criteria<T>> oredCriteria; /** * 允许Example查询条件为空 */ protected boolean allowCriteriaEmpty; //省略其他 } ```