### 按 Example 更新 Source: https://context7.com/abel533/mapper/llms.txt 使用 `Example` 对象指定更新条件,并提供要更新的记录对象,可以按条件选择性更新。 ```java Example updateEx = new Example(Country.class); updateEx.createCriteria().andEqualTo("countrycode", "TL"); Country record = new Country(); record.setCountryname("UpdatedName"); countryMapper.updateByExampleSelective(record, updateEx); ``` -------------------------------- ### 排序 (Example) Source: https://context7.com/abel533/mapper/llms.txt 在 `Example` 对象中指定多字段排序规则,支持升序和降序。 ```java Example sorted = new Example(Country.class); sorted.orderBy("id").desc().orderBy("countryname").orderBy("countrycode").asc(); countryMapper.selectByExample(sorted); // SQL: ... ORDER BY id DESC, countryname, countrycode ASC ``` -------------------------------- ### 通用 Example 基本用法 Source: https://context7.com/abel533/mapper/llms.txt 使用 `Example` 对象构建动态 SQL 条件,支持链式调用、OR/AND 组合、悲观锁等。查询结果可能超过一条。 ```java Example example = new Example(Country.class); example.setForUpdate(true); // FOR UPDATE 悲观锁 example.createCriteria() .andGreaterThan("id", 100) .andLessThan("id", 151); example.or().andLessThan("id", 41); List countries = countryMapper.selectByExample(example); // SQL: SELECT ... WHERE ( id > 100 AND id < 151 ) OR ( id < 41 ) FOR UPDATE ``` -------------------------------- ### 动态 SQL (Example) Source: https://context7.com/abel533/mapper/llms.txt 根据条件动态构建 `Example` 对象,适用于查询条件不确定的场景。仅追加非 null 的查询条件。 ```java Example dynamic = new Example(Country.class); Example.Criteria criteria = dynamic.createCriteria(); if (query.getCountryname() != null) { criteria.andLike("countryname", query.getCountryname() + "% "); } if (query.getId() != null) { criteria.andGreaterThan("id", query.getId()); } countryMapper.selectByExample(dynamic); ``` -------------------------------- ### Builder 模式 (Example) Source: https://context7.com/abel533/mapper/llms.txt 使用 `Example.builder()` 链式调用构建 `Example` 对象,提供更简洁的语法,支持指定查询列、条件、排序和悲观锁。 ```java Example built = Example.builder(Country.class) .select("countryname") .where(Sqls.custom().andGreaterThan("id", 100)) .orderByAsc("countrycode") .forUpdate() .build(); countryMapper.selectByExample(built); // SQL: SELECT countryname FROM country WHERE ( id > 100 ) ORDER BY countrycode ASC FOR UPDATE ``` -------------------------------- ### 按 Example 删除 Source: https://context7.com/abel533/mapper/llms.txt 使用 `Example` 对象指定删除条件,当 `safeDelete=true` 时,必须提供条件以防止误删。 ```java Example deleteEx = new Example(Country.class); deleteEx.createCriteria().andLike("countryname", "Test%"); countryMapper.deleteByExample(deleteEx); ``` -------------------------------- ### 去重和指定查询列 (Example) Source: https://context7.com/abel533/mapper/llms.txt 设置 `Example` 的 `distinct` 属性为 `true` 并使用 `selectProperties` 指定查询列,实现去重查询。 ```java Example distinct = new Example(Country.class); distinct.setDistinct(true); distinct.selectProperties("id", "countryname"); countryMapper.selectByExample(distinct); // SQL: SELECT DISTINCT id, countryname FROM country ``` -------------------------------- ### Example of Creating an Example with a Mismatched Entity Class Source: https://github.com/abel533/mapper/wiki/3.config/3.config Illustrates a scenario where an `Example` object is created for `City.class` but then used with a `countryMapper`. Enabling `checkExampleEntityClass` would flag this as an error. ```java Example example = new Example(City.class); example.xxx...;//设置条件的方法 countryMapper.selectByExample(example); ``` -------------------------------- ### MBG Generated Example for Distinct Queries Source: https://github.com/abel533/mapper/wiki/6.example/6.example Shows how to use an MBG-generated Example class to fetch distinct records based on specified criteria. This is similar to the deletion example but for selecting unique rows. ```java CountryExample example = new CountryExample(); //设置 distinct example.setDistinct(true); example.createCriteria().andCountrynameLike("A%"); example.or().andIdGreaterThan(100); List countries = mapper.selectByExample(example); ``` -------------------------------- ### Generic Example for Sorting Source: https://github.com/abel533/mapper/wiki/6.example/6.example Demonstrates how to specify multiple sorting orders for a query using the generic Example class, including ascending and descending options for different fields. ```java Example example = new Example(Country.class); example.orderBy("id").desc().orderBy("countryname").orderBy("countrycode").asc(); List countries = mapper.selectByExample(example); ``` -------------------------------- ### Example Condition Builder Source: https://context7.com/abel533/mapper/llms.txt The `Example` class provides a dynamic condition builder for generic Mappers, supporting chained calls, OR/AND combinations, sorting, and distinct queries. ```APIDOC ## Example Condition Builder `Example` is a dynamic condition builder provided by generic Mapper, supporting chained calls, OR/AND combinations, sorting, and de-duplication. ```java // 6.2 Basic Example Usage Example example = new Example(Country.class); example.setForUpdate(true); // FOR UPDATE pessimistic lock example.createCriteria() .andGreaterThan("id", 100) .andLessThan("id", 151); example.or().andLessThan("id", 41); List countries = countryMapper.selectByExample(example); // SQL: SELECT ... WHERE ( id > 100 AND id < 151 ) OR ( id < 41 ) FOR UPDATE // 6.2.2 Dynamic SQL (append conditions as needed) Example dynamic = new Example(Country.class); Example.Criteria criteria = dynamic.createCriteria(); if (query.getCountryname() != null) { criteria.andLike("countryname", query.getCountryname() + "%" ); } if (query.getId() != null) { criteria.andGreaterThan("id", query.getId()); } countryMapper.selectByExample(dynamic); // 6.2.3 Sorting Example sorted = new Example(Country.class); sorted.orderBy("id").desc().orderBy("countryname").orderBy("countrycode").asc(); countryMapper.selectByExample(sorted); // SQL: ... ORDER BY id DESC, countryname, countrycode ASC // 6.2.4 Distinct + Specify Query Columns Example distinct = new Example(Country.class); distinct.setDistinct(true); distinct.selectProperties("countryname", "id"); countryMapper.selectByExample(distinct); // SQL: SELECT DISTINCT id, countryname FROM country // 6.3 Builder Pattern (more concise) Example built = Example.builder(Country.class) .select("countryname") .where(Sqls.custom().andGreaterThan("id", 100)) .orderByAsc("countrycode") .forUpdate() .build(); countryMapper.selectByExample(built); // SQL: SELECT countryname FROM country WHERE ( id > 100 ) ORDER BY countrycode ASC FOR UPDATE // 6.2 Update by Example Example updateEx = new Example(Country.class); updateEx.createCriteria().andEqualTo("countrycode", "TL"); Country record = new Country(); record.setCountryname("UpdatedName"); countryMapper.updateByExampleSelective(record, updateEx); // 6.2 Delete by Example (requires a condition when safeDelete=true) Example deleteEx = new Example(Country.class); deleteEx.createCriteria().andLike("countryname", "Test%" ); countryMapper.deleteByExample(deleteEx); ``` ``` -------------------------------- ### Example Builder for Querying with Lock Source: https://github.com/abel533/mapper/wiki/6.example/6.example Demonstrates using the Example.builder API to construct a query with specific selection, filtering, ordering, and locking clauses. This provides a more fluent API for building Example objects. ```java Example example = Example.builder(Country.class) .select("countryname") .where(Sqls.custom().andGreaterThan("id", 100)) .orderByAsc("countrycode") .forUpdate() .build(); List countries = mapper.selectByExample(example); ``` -------------------------------- ### Generic Example for Querying with Lock Source: https://github.com/abel533/mapper/wiki/6.example/6.example Illustrates using the generic Example class to construct a query with specific criteria and ordering, including setting the FOR UPDATE clause for locking. ```java Example example = new Example(Country.class); example.setForUpdate(true); example.createCriteria().andGreaterThan("id", 100).andLessThan("id",151); example.or().andLessThan("id", 41); List countries = mapper.selectByExample(example); ``` -------------------------------- ### Generic Example for Dynamic SQL Conditions Source: https://github.com/abel533/mapper/wiki/6.example/6.example Shows how to build dynamic queries using the generic Example class where criteria are added conditionally based on input parameters. This is useful for flexible search functionalities. ```java Example example = new Example(Country.class); Example.Criteria criteria = example.createCriteria(); if(query.getCountryname() != null){ criteria.andLike("countryname", query.getCountryname() + "%"); } if(query.getId() != null){ criteria.andGreaterThan("id", query.getId()); } List countries = mapper.selectByExample(example); ``` -------------------------------- ### Example generatorConfig.xml for MyBatis Generator Source: https://github.com/abel533/mapper/wiki/4.generator/4.1.mappergenerator A sample `generatorConfig.xml` demonstrating configuration for MyBatis Generator, including the MapperPlugin. This example uses an HSQLDB in-memory database. ```xml
``` -------------------------------- ### MBG Generated Example for Deletion Source: https://github.com/abel533/mapper/wiki/6.example/6.example Demonstrates using an MBG-generated Example class to define criteria for deleting records. The example shows how to combine multiple conditions using 'or' and set distinctness. ```java CountryExample example = new CountryExample(); example.createCriteria().andCountrynameLike("A%"); example.or().andIdGreaterThan(100); example.setDistinct(true); int count = mapper.deleteByExample(example); ``` -------------------------------- ### Generic Example for Selecting Specific Properties Source: https://github.com/abel533/mapper/wiki/6.example/6.example Illustrates how to limit the query to return only specific columns (properties) of the entity using the generic Example class's selectProperties method. ```java Example example = new Example(Country.class); example.selectProperties("id", "countryname"); List countries = mapper.selectByExample(example); ``` -------------------------------- ### Basic MyBatis通用Mapper Usage Source: https://github.com/abel533/mapper/blob/master/core/README.md Demonstrates how to obtain a Mapper instance and perform basic CRUD operations like selecting all records and selecting by example using both generic `Example` and generated `CountryExample`. ```java CountryMapper mapper = sqlSession.getMapper(CountryMapper.class); //查询全部 List countryList = mapper.select(new Country()); //总数 Assert.assertEquals(183, countryList.size()); //通用Example查询 Example example = new Example(Country.class); example.createCriteria().andGreaterThan("id", 100); countryList = mapper.selectByExample(example); Assert.assertEquals(83, countryList.size()); //MyBatis-Generator生成的Example查询 CountryExample example2 = new CountryExample(); example2.createCriteria().andIdGreaterThan(100); countryList = mapper.selectByExample(example2); Assert.assertEquals(83, countryList.size()); ``` -------------------------------- ### TemplateFilePlugin Configuration Source: https://github.com/abel533/mapper/blob/master/generator/README.md Example configuration for the TemplateFilePlugin. ```xml <#if !templateFilePlugin??> ``` -------------------------------- ### Add Spring and MyBatis Dependencies Source: https://github.com/abel533/mapper/wiki/1.integration/1.2-spring Include these dependencies for a standard Spring and MyBatis setup. Ensure to use appropriate version numbers. ```xml org.mybatis mybatis 版本号 org.mybatis mybatis-spring 版本号 org.springframework spring-context 版本号 org.springframework spring-tx 版本号 org.springframework spring-jdbc 版本号 ``` -------------------------------- ### Specifying Target Project Directory Source: https://github.com/abel533/mapper/wiki/4.generator/4.2.codegenerator Example of setting the `targetProject` property to specify the output directory for generated code. The directory must exist prior to generation. ```xml ``` -------------------------------- ### Enable Entity Class Check for Example Queries Source: https://github.com/abel533/mapper/wiki/3.config/3.config Validates that the entity class used to construct an `Example` object matches the entity type of the `Mapper`. If `true`, it prevents potential errors where an `Example` for one entity is mistakenly used with a `Mapper` for another. ```properties checkExampleEntityClass=true ``` -------------------------------- ### Freemarker Template Output Example Source: https://github.com/abel533/mapper/wiki/4.generator/4.2.codegenerator Sample output from a Freemarker template used by the code generator, illustrating the detailed information extracted for entity and column mapping. ```text 目标package: 当前时间: 2017-11-6 22:00:45 2017-11-06 22:00:45 所有配置的属性信息: targetPackage - templateFormatter - tk.mybatis.mapper.generator.formatter.FreemarkerTemplateFormatter templatePath - generator/test-one.ftl targetProject - src/test/resources fileName - ${tableClass.shortClassName}Test.txt 实体和表的信息: 表名:user_info 变量名:userInfo 小写名:userinfo 类名:UserInfo 全名:test.model.UserInfo 包名:test.model 列的信息: ===================================== 主键: ------------------------------------- 列名:Id 列类型:INTEGER 字段名:id 注释: 类型包名:java.lang 类型短名:Integer 类型全名:java.lang.Integer 是否主键:true 是否可空:false 是否为BLOB列:false 是否为String列:false 是否为字符串列:false 是否为日期列:false 是否为时间列:false 是否为序列列:false 列长度:10 列精度:0 基础列: ------------------------------------- 列名:username 列类型:VARCHAR 字段名:username 注释:用户名 类型包名:java.lang 类型短名:String 类型全名:java.lang.String 是否主键:false 是否可空:false 是否为BLOB列:false 是否为String列:true 是否为字符串列:true 是否为日期列:false 是否为时间列:false 是否为序列列:false 列长度:32 列精度:0 ------------------------------------- 列名:password 列类型:VARCHAR 字段名:password 注释:密码 类型包名:java.lang 类型短名:String 类型全名:java.lang.String 是否主键:false 是否可空:true 是否为BLOB列:false 是否为String列:true 是否为字符串列:true 是否为日期列:false 是否为时间列:false 是否为序列列:false 列长度:32 列精度:0 ------------------------------------- 列名:usertype 列类型:VARCHAR 字段名:usertype 注释:用户类型 类型包名:java.lang 类型短名:String 类型全名:java.lang.String 是否主键:false 是否可空:true 是否为BLOB列:false 是否为String列:true 是否为字符串列:true 是否为日期列:false 是否为时间列:false 是否为序列列:false 列长度:2 列精度:0 ------------------------------------- 列名:enabled 列类型:INTEGER 字段名:enabled 注释:是否可用 类型包名:java.lang 类型短名:Integer 类型全名:java.lang.Integer 是否主键:false 是否可空:true 是否为BLOB列:false 是否为String列:false 是否为字符串列:false 是否为日期列:false 是否为时间列:false 是否为序列列:false 列长度:10 列精度:0 ------------------------------------- 列名:realname 列类型:VARCHAR 字段名:realname 注释:真实姓名 类型包名:java.lang 类型短名:String 类型全名:java.lang.String 是否主键:false 是否可空:true 是否为BLOB列:false 是否为String列:true 是否为字符串列:true 是否为日期列:false 是否为时间列:false 是否为序列列:false 列长度:32 列精度:0 ------------------------------------- 列名:qq 列类型:VARCHAR 字段名:qq 注释:QQ 类型包名:java.lang 类型短名:String 类型全名:java.lang.String 是否主键:false 是否可空:true 是否为BLOB列:false 是否为String列:true 是否为字符串列:true 是否为日期列:false 是否为时间列:false 是否为序列列:false 列长度:14 列精度:0 ------------------------------------- 列名:email 列类型:VARCHAR 字段名:email 注释: 类型包名:java.lang 类型短名:String 类型全名:java.lang.String 是否主键:false 是否可空:true 是否为BLOB列:false 是否为String列:true 是否为字符串列:true 是否为日期列:false 是否为时间列:false 是否为序列列:false 列长度:100 列精度:0 ------------------------------------- 列名:tel 列类型:VARCHAR 字段名:tel 注释:联系电话 类型包名:java.lang 类型短名:String 类型全名:java.lang.String 是否主键:false 是否可空:true 是否为BLOB列:false 是否为String列:true 是否为字符串列:true 是否为日期列:false 是否为时间列:false 是否为序列列:false 列长度:255 列精度:0 Blob列: ===================================== 全部列: 列名 - 字段名 Id - id username - username password - password usertype - usertype enabled - enabled realname - realname qq - qq email - email tel - tel ``` -------------------------------- ### Specifying Target Package Path Source: https://github.com/abel533/mapper/wiki/4.generator/4.2.codegenerator Example of setting the `targetPackage` property to define the package (directory) for generated files. This path will be automatically created if it does not exist. It supports template variables. ```xml ``` -------------------------------- ### FreeMarker Template for Date Formatting Source: https://github.com/abel533/mapper/wiki/4.generator/4.2.codegenerator Demonstrates how to format dates and times within a FreeMarker template used by the code generator. It shows how to get the current time and format it into different string representations. ```ftl <#assign dateTime = .now> 日期:${dateTime?date} 时间:${dateTime?time} 格式化:${dateTime?string["yyyy-MM-dd HH:mm:ss"]} ``` -------------------------------- ### Enable Method Annotation Usage Example Source: https://github.com/abel533/mapper/wiki/3.config/3.config Demonstrates how to use `@Column` annotation on a setter method to map a property to a different column name. ```java private String name; @Column(name = "user_name") public void setName(String name){ this.name = name; } ``` -------------------------------- ### Configure TemplateFilePlugin for Single Test File Output Source: https://github.com/abel533/mapper/wiki/4.generator/4.2.codegenerator Configure the TemplateFilePlugin to generate a single test file for each table. This example demonstrates outputting a custom text file for each entity, using a specified template and file name pattern. ```xml ``` -------------------------------- ### Java Generic Type Example for useJavaType Source: https://github.com/abel533/mapper/wiki/3.config/3.config Demonstrates a generic base class `Pk` and a derived class `User` that extends it. This structure requires `useJavaType=true` for correct type recognition in older MyBatis versions. ```java class Pk { private T id; public T getId() { return id; } public void setId(T id) { this.id = id; } } class User extends Pk { private String name; } ``` -------------------------------- ### Using Generic Mapper Methods Source: https://github.com/abel533/mapper/wiki/2.orm/2.1-simple Demonstrates how to use common methods like selectAll and selectByPrimaryKey after obtaining the mapper instance. ```java //从 MyBatis 或者 Spring 中获取 countryMapper,然后调用 selectAll 方法 List countries = countryMapper.selectAll(); //根据主键查询 Country country = countryMapper.selectByPrimaryKey(1); //或者使用对象传参,适用于1个字段或者多个字段联合主键使用 Country query = new Country(); query.setId(1); country = countryMapper.selectByPrimaryKey(query); ``` -------------------------------- ### Builder 模式结合 WeekendSqls Source: https://context7.com/abel533/mapper/llms.txt 将 `Example.builder()` 与 `WeekendSqls` 结合使用,实现链式构建查询,同时利用 Lambda 方法引用提高代码健壮性。 ```java Example weekendEx = Example.builder(Country.class) .select("id", "countryname") .where(WeekendSqls.custom() .andEqualTo(Country::getCountrycode, "CN")) .orderByDesc(Country::getId.toString()) .build(); countryMapper.selectByExample(weekendEx); ``` -------------------------------- ### Define Generic Mapper Interface with Type Parameters Source: https://github.com/abel533/mapper/wiki/4.x.changelog Example of defining a generic interface with type parameters for entity, primary key, and example types, which can be an alternative to `mapper-base`. ```java public interface Mapper extends xxx,xxx {} ``` -------------------------------- ### Custom Base Mapper Interface Example Source: https://github.com/abel533/mapper/wiki/4.generator/4.1.mappergenerator An example of a custom base Mapper interface (`MyMapper`) that extends generic Mapper interfaces. This custom interface can be specified in the `generatorConfig.xml` plugin configuration. ```java package xxx.base; import tk.mybatis.mapper.common.Mapper; import tk.mybatis.mapper.common.MySqlMapper; /** * 继承自己的MyMapper */ public interface MyMapper extends Mapper, MySqlMapper { //TODO //FIXME 特别注意,该接口不能被扫描到,否则会出错 } ``` -------------------------------- ### Spring Boot Starter Dependency for MyBatis通用Mapper3 Source: https://github.com/abel533/mapper/blob/master/core/README.md For Spring Boot projects, use the `mapper-spring-boot-starter` dependency. This starter simplifies integration with Spring Boot applications. Replace '最新版本' with the actual latest version. ```xml tk.mybatis mapper-spring-boot-starter 最新版本 ``` -------------------------------- ### Generated User DAO Interface Source: https://github.com/abel533/mapper/blob/master/generator/README.md Example of a generated Java DAO interface extending the common MyBatis Mapper. ```java package test.mapper; import test.model.UserInfo; /** * 通用 Mapper 代码生成器 * * @author mapper-generator */ public interface UserInfoDao extends tk.mybatis.mapper.common.Mapper { } ``` -------------------------------- ### Overriding SelectAll with RowBounds Source: https://github.com/abel533/mapper/wiki/2.orm/2.1-simple Example of overriding a generic method (selectAll) with custom parameters like RowBounds for pagination. ```java public interface CountryMapper extends Mapper { List selectAll(RowBounds rowBounds); } ``` -------------------------------- ### Introduce Core Mapper Dependencies Source: https://github.com/abel533/mapper/wiki/4.x.changelog For deeper customization, introduce core dependencies like mapper-core, mapper-base, and others as needed. ```xml tk.mybatis mapper-core ${mapper-core.version} tk.mybatis mapper-base ${mapper-base.version} tk.mybatis mapper-extra ${mapper-extra.version} tk.mybatis mapper-weekend ${mapper-weekend.version} tk.mybatis mapper-generator ${mapper-generator.version} tk.mybatis mapper-spring ${mapper-spring.version} tk.mybatis mapper-spring-boot-starter ${mapper-starter.version} ``` -------------------------------- ### 使用 @KeySql 通过序列获取主键 (Oracle) Source: https://github.com/abel533/mapper/wiki/2.orm/2.3-generatedvalue 配置 Oracle 数据库中通过序列获取主键的策略。需要指定 SQL 语句和 order 为 BEFORE。 ```java @Id @KeySql(sql = "select SEQ_ID.nextval from dual", order = ORDER.BEFORE) private Integer id; ``` -------------------------------- ### Generated User Entity Code Source: https://github.com/abel533/mapper/wiki/4.generator/4.2.codegenerator Example of a Java entity class generated by the code generator. It includes annotations for table and column mapping. ```java @Table(name = "`user_info`") public class UserInfo { @Id @Column(name = "`Id`") @GeneratedValue(generator = "JDBC") private Integer id; ``` -------------------------------- ### MyBatis通用Mapper Safe Delete Exception Example Source: https://github.com/abel533/mapper/wiki/3.config/3.config Illustrates the exception thrown when a delete operation is attempted without a query condition while safeDelete is enabled. ```java Caused by: tk.mybatis.mapper.MapperException: 通用 Mapper 安全检查: 当前操作的方法没有指定查询条件,不允许执行该操作! at tk.mybatis.mapper.util.OGNL.notAllNullParameterCheck(OGNL.java:91) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.apache.ibatis.ognl.OgnlRuntime.invokeMethod(OgnlRuntime.java:899) at org.apache.ibatis.ognl.OgnlRuntime.callAppropriateMethod(OgnlRuntime.java:1544) ... 53 more ``` -------------------------------- ### Implement SelectAll Provider Source: https://github.com/abel533/mapper/wiki/5.extend/5.extend Implement the `MySelectProvider` class, extending `MapperTemplate`, to provide the SQL logic for the `selectAll` method. Ensure the method name matches the interface and accepts `MappedStatement`. ```java import org.apache.ibatis.mapping.MappedStatement; import tk.mybatis.mapper.mapperhelper.MapperHelper; import tk.mybatis.mapper.mapperhelper.MapperTemplate; import tk.mybatis.mapper.mapperhelper.SqlHelper; public class MySelectProvider extends MapperTemplate { public BaseSelectProvider(Class mapperClass, MapperHelper mapperHelper) { super(mapperClass, mapperHelper); } /** * 查询全部结果 * * @param ms * @return */ public String selectAll(MappedStatement ms) { final Class entityClass = getEntityClass(ms); //修改返回值类型为实体类型 setResultType(ms, entityClass); StringBuilder sql = new StringBuilder(); sql.append(SqlHelper.selectAllColumns(entityClass)); sql.append(SqlHelper.fromTable(entityClass, tableName(entityClass))); sql.append(SqlHelper.orderByDefault(entityClass)); return sql.toString(); } } ``` -------------------------------- ### Spring Boot自动配置集成 Source: https://context7.com/abel533/mapper/llms.txt 通过`mapper-spring-boot-starter`实现Spring Boot的零XML配置集成。在`application.yml`中配置Mapper相关参数,并使用`@MapperScan`注解扫描Mapper接口。 ```yaml # application.yml mapper: mappers: - tk.mybatis.mapper.common.Mapper not-empty: true identity: MYSQL style: camelhump # 驼峰转下划线(默认值) safe-delete: true safe-update: true wrap-keyword: "`{0}`" enum-as-simple-type: true mybatis: mapper-locations: classpath:mapper/*.xml type-aliases-package: com.example.model ``` ```java // 启动类配置(推荐使用 tk 的 @MapperScan) @tk.mybatis.spring.annotation.MapperScan(basePackages = "com.example.mapper") @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } // 或仅用 @Mapper 注解(不使用 @MapperScan 时) @Mapper public interface UserMapper extends tk.mybatis.mapper.common.Mapper { } ``` -------------------------------- ### Generated MyBatis XML Mapper Source: https://github.com/abel533/mapper/wiki/4.generator/4.2.codegenerator Example of a MyBatis XML mapper file generated by the code generator. It defines the namespace for the corresponding DAO interface. ```xml ``` -------------------------------- ### Global TypeHandler Configuration Source: https://github.com/abel533/mapper/wiki/7.others/7.2.typehandler Configure type handlers globally in the XML configuration file. This example shows how to register `EnumOrdinalTypeHandler` for `StateEnum` and `AddressTypeHandler` for `Address`. ```xml ``` -------------------------------- ### Generated User DAO Interface Source: https://github.com/abel533/mapper/wiki/4.generator/4.2.codegenerator Example of a Java interface for a Data Access Object (DAO) generated by the code generator. It extends the common Mapper interface. ```java package test.mapper; import test.model.UserInfo; /** * 通用 Mapper 代码生成器 * * @author mapper-generator */ public interface UserInfoDao extends tk.mybatis.mapper.common.Mapper { } ``` -------------------------------- ### SQL Schema and Data for User Table Source: https://github.com/abel533/mapper/wiki/7.others/7.2.typehandler SQL statements to create the user table and insert sample data, including address and state fields. ```sql create table user ( id integer NOT NULL PRIMARY KEY, name varchar(32), address varchar(64), state integer ); INSERT INTO user (id, name, address, state) VALUES (1, 'abel533', 'Hebei/Shijiazhuang', 1); INSERT INTO user (id, name, address, state) VALUES (2, 'isea533', 'Hebei/Handan', 0); ``` -------------------------------- ### 添加Maven依赖 Source: https://context7.com/abel533/mapper/llms.txt 引入MyBatis通用Mapper及其Spring Boot Starter的Maven依赖。根据项目需求,可以选择引入统一jar包或细化依赖。 ```xml tk.mybatis mapper 6.0.0 tk.mybatis mapper-spring-boot-starter 6.0.0 tk.mybatis mapper-core ${mapper-core.version} tk.mybatis mapper-base ${mapper-base.version} tk.mybatis mapper-extra ${mapper-extra.version} tk.mybatis mapper-weekend ${mapper-weekend.version} tk.mybatis mapper-generator ${mapper-generator.version} ``` -------------------------------- ### Enable Safe Update in MyBatis通用Mapper Source: https://github.com/abel533/mapper/wiki/3.config/3.config When enabled, update operations using examples require a query condition to prevent accidental modification of all records. This setting is configured in properties. ```properties safeUpdate=true ``` -------------------------------- ### FreeMarker Template for Iterating Properties Source: https://github.com/abel533/mapper/wiki/4.generator/4.2.codegenerator Illustrates how to iterate over all configured properties within a FreeMarker template. This is useful for debugging or displaying configuration details during code generation. ```ftl <#list props?keys as key> ${key} - ${props[key]} ``` -------------------------------- ### Configure ORDER for Primary Key Generation (Properties - BEFORE) Source: https://github.com/abel533/mapper/wiki/3.config/3.config Sets the order for the `` tag to 'BEFORE' for primary key generation, typically used with sequences or UUIDs. This is the Properties file configuration. ```properties ORDER=BEFORE ``` ```properties order=BEFORE ``` ```properties before=true ``` -------------------------------- ### Generated Mapper Interface (CountryMapper) Source: https://github.com/abel533/mapper/wiki/4.generator/4.1.mappergenerator Example of an automatically generated Mapper interface. It extends the generic `Mapper` interface provided by tk.mybatis, including the entity class as a generic type. ```java package com.isea533.mybatis.mapper; import com.isea533.mybatis.model.Country; import tk.mybatis.mapper.common.Mapper; public interface CountryMapper extends Mapper { } ``` -------------------------------- ### Configure ORDER for Primary Key Generation (Properties) Source: https://github.com/abel533/mapper/wiki/3.config/3.config Sets the order for the `` tag in primary key generation. Use 'AFTER' for auto-incrementing keys and 'BEFORE' for sequences or UUIDs. This is the Properties file configuration. ```properties ORDER=AFTER ``` ```properties order=AFTER ``` ```properties before=false ``` -------------------------------- ### FreeMarker Template for All Column Information Source: https://github.com/abel533/mapper/wiki/4.generator/4.2.codegenerator Shows how to iterate over all columns (primary key, base, and BLOB) in a table within a FreeMarker template. It displays the column name and field name for each column. ```ftl <#if tableClass.allFields??> 列名 - 字段名 <#list tableClass.allFields as field> ${field.columnName} - ${field.fieldName} ``` -------------------------------- ### Generated Entity Class (Country) Source: https://github.com/abel533/mapper/wiki/4.generator/4.1.mappergenerator Example of an automatically generated entity class. It includes fields, getters, setters, and JPA annotations based on the database table structure and comments. ```java package com.isea533.mybatis.model; import javax.persistence.*; @Table(name = "country") public class Country { /** * 主键 */ @Id @Column(name = "Id") @GeneratedValue(generator = "JDBC") private Integer id; /** * 名称 */ private String countryname; /** * 代码 */ private String countrycode; /** * 获取主键 * * @return Id - 主键 */ public Integer getId() { return id; } /** * 设置主键 * * @param id 主键 */ public void setId(Integer id) { this.id = id; } /** * 获取名称 * * @return countryname - 名称 */ public String getCountryname() { return countryname; } /** * 设置名称 * * @param countryname 名称 */ public void setCountryname(String countryname) { this.countryname = countryname; } /** * 获取代码 * * @return countrycode - 代码 */ public String getCountrycode() { return countrycode; } /** * 设置代码 * * @param countrycode 代码 */ public void setCountrycode(String countrycode) { this.countrycode = countrycode; } } ``` -------------------------------- ### @KeySql 注解详解 Source: https://github.com/abel533/mapper/wiki/2.orm/2.3-generatedvalue 详细介绍了 @KeySql 注解的三个主要参数:useGeneratedKeys、dialect 和 sql,以及它们的优先级和 order 参数的用法。 ```java @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface KeySql { /** * 是否使用 JDBC 方式获取主键,优先级最高,设置为 true 后,不对其他配置校验 * * @return */ boolean useGeneratedKeys() default false; /** * 优先级第二,根据配置的数据库类型取回主键,忽略其他配置 * * @return */ IdentityDialect dialect() default IdentityDialect.DEFAULT; /** * 取主键的 SQL * * @return */ String sql() default ""; /** * 和 sql 可以配合使用,默认使用全局配置中的 ORDER * * @return */ ORDER order() default ORDER.DEFAULT; } ``` -------------------------------- ### MyBatis Mapper Weekend Dependency Source: https://github.com/abel533/mapper/wiki/1.integration/1.2-spring Include the MyBatis Mapper Weekend dependency for Java 8 method references, specifically for creating Example objects and using Weekend queries. ```xml tk.mybatis mapper-weekend ${mapper-weekend.version} ``` -------------------------------- ### Java编码方式集成(不使用Spring) Source: https://context7.com/abel533/mapper/llms.txt 在纯Java环境中使用MapperHelper初始化通用Mapper。需要先构建SqlSessionFactory,然后配置MapperHelper的各项参数,最后应用配置。 ```java // 1. 构建 SqlSessionFactory(示例使用 mybatis-config.xml) SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder() .build(Resources.getResourceAsStream("mybatis-config.xml")); SqlSession session = sqlSessionFactory.openSession(); // 2. 配置 MapperHelper MapperHelper mapperHelper = new MapperHelper(); Config config = new Config(); config.setIDENTITY("MYSQL"); // 主键回写方式(MySQL 自增) config.setNotEmpty(true); // 字符串判断 != '' config.setUseSimpleType(true); // 只映射简单类型字段 config.setEnumAsSimpleType(true); // 枚举当作简单类型 config.setWrapKeyword("`{0}`"); // 自动处理 MySQL 关键字 config.setCheckExampleEntityClass(true); // 校验 Example 类型一致性 config.setSafeDelete(true); // 安全删除(必须带条件) config.setSafeUpdate(true); // 安全更新(必须带条件) mapperHelper.setConfig(config); // 3. 应用配置(必须在任何 Mapper 调用前执行) mapperHelper.processConfiguration(session.getConfiguration()); // 4. 使用 Mapper CountryMapper mapper = session.getMapper(CountryMapper.class); List list = mapper.selectAll(); // 简化写法(使用默认配置) MapperHelper simple = new MapperHelper(); simple.processConfiguration(session.getConfiguration()); ``` -------------------------------- ### Weekend — Java 8 Method References Example Source: https://context7.com/abel533/mapper/llms.txt Weekend utilizes Lambda method references instead of string property names, allowing for compile-time checks and preventing spelling errors. ```APIDOC ## Weekend — Java 8 Method References Example `Weekend` uses Lambda method references instead of string property names, avoiding field name spelling errors and enabling compile-time checks. ```java import tk.mybatis.mapper.weekend.Weekend; import tk.mybatis.mapper.weekend.WeekendSqls; // Basic Usage: Build conditions via method references List list = countryMapper.selectByExample( new Example.Builder(Country.class) .where(WeekendSqls.custom() .andLike(Country::getCountryname, "%a%") .andGreaterThan(Country::getId, 100)) .build() ); // SQL: SELECT ... WHERE ( countryname LIKE '%a%' AND id > 100 ) // Weekend Object Usage Weekend weekend = Weekend.of(Country.class); weekend.weekendCriteria() .andIsNotNull(Country::getId) .andBetween(Country::getId, 10, 200) .andIn(Country::getCountrycode, Arrays.asList("CN", "US", "UK")); List result = countryMapper.selectByExample(weekend); // SQL: SELECT ... WHERE ( id IS NOT NULL AND id BETWEEN 10 AND 200 AND countrycode IN ('CN','US','UK') ) // Builder Pattern combined with WeekendSqls Example weekendEx = Example.builder(Country.class) .select("id", "countryname") .where(WeekendSqls.custom() .andEqualTo(Country::getCountrycode, "CN")) .orderByDesc(Country::getId.toString()) .build(); countryMapper.selectByExample(weekendEx); ``` ``` -------------------------------- ### FreeMarker Template for Primary Key Column Information Source: https://github.com/abel533/mapper/wiki/4.generator/4.2.codegenerator Demonstrates how to access and display detailed information for primary key columns within a FreeMarker template. It iterates through `pkFields` to show column name, type, field name, remarks, and various boolean flags. ```ftl <#if tableClass.pkFields??> 主键: <#list tableClass.pkFields as field> ------------------------------------- 列名:${field.columnName} 列类型:${field.jdbcType} 字段名:${field.fieldName} 注释:${field.remarks} 类型包名:${field.typePackage} 类型短名:${field.shortTypeName} 类型全名:${field.fullTypeName} 是否主键:${field.identity?c} 是否可空:${field.nullable?c} 是否为BLOB列:${field.blobColumn?c} 是否为String列:${field.stringColumn?c} 是否为字符串列:${field.jdbcCharacterColumn?c} 是否为日期列:${field.jdbcDateColumn?c} 是否为时间列:${field.jdbcTimeColumn?c} 是否为序列列:${field.sequenceColumn?c} 列长度:${field.length?c} 列精度:${field.scale} ```