Xbatis
一款基于mybatis的ORM框架,非常强大,非常好用,不信的来试试,2024年超级优秀的ORM!!!
Install / Use
/learn @xbatis/XbatisREADME
Xbatis AI Agent Knowledge Base
Official site: https://xbatis.cn
DeepWiki documentation: https://deepwiki.com/xbatis/xbatis
Knowledge pack for AI agents working with the Xbatis framework. It distills the official Chinese materials into a self-contained explanation so that automated assistants can understand the framework capabilities, common patterns, and key APIs.
English | 简体中文
1. Framework Overview
- Positioning: Xbatis is built on MyBatis and delivers a highly ORM-like database experience, emphasizing "less SQL, fluent DSL, cross-database compatibility".
- Primary advantages:
- Multi-table joins, subqueries, fluent pagination, automatic SQL optimization (auto-removal of redundant
LEFT JOIN/ORDER BY, smarterCOUNT). - Built-in
RETURNINGsupport, batch insert/update chains, native function wrappers, SQL templates. - Single mapper mode that allows one
BasicMapperto cover every entity. - Database function library, database-specific
dbAdapt, dynamic datasource routing. - Full annotation ecosystem: logical delete, multi-tenancy, optimistic locking, result mapping, condition mapping, dynamic default value injection, etc.
- Multi-table joins, subqueries, fluent pagination, automatic SQL optimization (auto-removal of redundant
- Core characteristics (from the official highlights):
- Extremely lightweight: only wraps MyBatis without invasive modification.
- High performance: keeps execution efficiency close to handwritten SQL.
- Flexible and easy to use: fluent APIs read like natural language.
- Highly available: covers more than 90% of common SQL scenarios.
- Reliable and safe: concise design yet feature-rich, hardened by extensive testing.
- Pagination optimization: automatically tunes
JOIN,COUNT,ORDER BY, and ships with a built-in pager.
2. Core Modules & Package Paths
| Module | Typical package | Core types | Purpose |
|--------------------|---------------------------------|-------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------|
| Core Mapper | cn.xbatis.core.mybatis.mapper | MybatisMapper<T>, BasicMapper | Provides base CRUD plus single-mapper capabilities |
| Fluent DSL | cn.xbatis.core.chain | QueryChain, InsertChain, UpdateChain, DeleteChain | Build complex SQL, batch ops, returning clauses |
| Global config | cn.xbatis.core.config | XbatisGlobalConfig | Unified naming rules, interceptors, dynamic values, paging |
| Annotation suite | cn.xbatis.db.annotations | @Table, @TableId, @TableField, @LogicDelete,@LogicDeleteTime, @TenantId, @Version, @Condition, @Fetch, etc. | Entity mapping, injection rules, condition objects, result shaping |
| Database functions | db.sql.api.impl.cmd | Methods | Cross-database functions, SQL templates, fluent wrappers |
| Multi-tenant | cn.xbatis.core.tenant | TenantContext, TenantId | Register and propagate tenant IDs globally |
| Dynamic datasource | cn.xbatis.datasource.routing | @DS, JdbcConfigDecryptor | Runtime datasource switching, encrypted configs, grouped routing |
| Logical delete | cn.xbatis.core.logic | LogicDeleteSwitch, LogicDeleteUtil | Toggle logical delete, easy overrides |
| Dynamic values | cn.xbatis.core.dynamic | XbatisGlobalConfig#setDynamicValue | Define tokens like {NOW}, {TODAY} |
| Code generation | cn.xbatis.codegen | GeneratorConfig and sub modules | One-stop generation for entities, mapper, service skeletons, etc. |
3. Quick Start & Dependencies
3.1 Maven coordinates example
<dependencyManagement>
<dependencies>
<dependency>
<groupId>cn.xbatis</groupId>
<artifactId>xbatis-spring-boot-parent</artifactId>
<version>1.9.9-M7</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>cn.xbatis</groupId>
<artifactId>xbatis-spring-boot3-starter</artifactId>
</dependency>
</dependencies>
3.2 Datasource configuration example
spring:
datasource:
url: jdbc:mysql://localhost:3306/dbName
username: dbusername
password: dbpassword
3.3 Bootstrapping skeleton example
@SpringBootApplication
@MapperScan("com.xx.xxx.mapper")
public class XbatisApplication {
public static void main(String[] args) {
SpringApplication.run(XbatisApplication.class, args);
}
}
3.4 Spring Boot 2 integration
- Maven dependencies (using
xbatis-spring-boot-starter):<dependencyManagement> <dependencies> <dependency> <groupId>cn.xbatis</groupId> <artifactId>xbatis-spring-boot-parent</artifactId> <version>1.9.9-M7</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>cn.xbatis</groupId> <artifactId>xbatis-spring-boot-starter</artifactId> </dependency> </dependencies> - Datasource & mapper scanning: same as 3.2/3.3; Spring Boot 2 continues to use
application.ymland@MapperScan. - Bootstrap class: identical to 3.3, ensure the starter version matches Spring Boot 2.
3.5 Solon integration
- Maven dependencies:
<!-- Order matters: register Xbatis plugin before mybatis-solon-plugin --> <dependency> <groupId>cn.xbatis</groupId> <artifactId>xbatis-solon-plugin</artifactId> <version>1.9.9-M7</version> </dependency> <dependency> <groupId>org.noear</groupId> <artifactId>mybatis-solon-plugin</artifactId> <version>${mybatis.solon.version}</version> </dependency> - Configuration example:
# solon.yml ds: schema: demo # recommend matching the database name jdbcUrl: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8 driverClassName: com.mysql.cj.jdbc.Driver username: root password: 123456 # Rule: mybatis.<datasource bean name> mybatis.master: mappers: - "com.demo.mapper" # package scan - "classpath:mapper/**/*.xml" # XML scan - Datasource bean:
@Configuration public class MybatisConfig { @Bean(name = "master", typed = true) public DataSource dataSource(@Inject("${ds}") HikariDataSource ds) { return ds; } } - Business usage:
@Controller public class DemoController { @Db // omit name for single datasource; specify @Db("master") for multi-datasource UserMapper mapper; @Get @Mapping("/test") public List<User> test() { return QueryChain.of(mapper) .like(User::getName, "abc") .list(); } } - Further configuration aligns with
mybatis-solon-plugin; chaining DSL, sharding, and multi-tenancy remain available. Entity, mapper, and service examples:
@Data
@Table
public class SysUser {
@TableId
private Integer id;
private String userName;
private String password;
private Integer roleId;
private LocalDateTime createTime;
}
public interface SysUserMapper extends MybatisMapper<SysUser> {}
@Service
public class TestService {
@Autowired
private SysUserMapper sysUserMapper;
public Pager<SysUser> demo() {
return QueryChain.of(sysUserMapper)
.eq(SysUser::getId, 1)
.like(SysUser::getUserName, "xxx")
.paging(Pager.of(1, 10));
}
}
> Pager resides in `cn.xbatis.core.mybatis.mapper.context.Pager` and implements `cn.xbatis.page.IPager`. Common usage:
> - Static factories: `Pager.of(size)`, `Pager.of(number, size)`.
> - `setExecuteCount(boolean)`: control whether to run the count query.
> - `paging(Pager)`: pass into chain APIs and read `getResults()`, `getTotal()`, `getNumber()`, `getSize()`, `getTotalPage()`, etc.
> - `PagerGetSetUtil` enables dynamic read/write of extension fields by `PagerField`.
4. Global Configuration XbatisGlobalConfig (cn.xbatis.core.config.XbatisGlobalConfig)
- Configure ahead of time via Spring
ConfigurationCustomizeror@PostConstruct. - Common methods:
setSingleMapperClass(MybatisBasicMapper.class): enable single-mapper mode withBasicMapper.setTableUnderline(boolean)/setColumnUnderline(boolean): control table/column naming.setDatabaseCaseRule(DatabaseCaseRule rule)orsetDatabaseCaseRule(DbType, rule): adjust casing strategy.- `setDynamicValue("{KEY}", (c
