# Mybatis.NET **Repository Path**: DXFB/Mybatis.NET ## Basic Information - **Project Name**: Mybatis.NET - **Description**: No description available - **Primary Language**: Unknown - **License**: MIT - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-05-07 - **Last Updated**: 2026-05-07 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # MyBatis.NET [![NuGet Version](https://img.shields.io/nuget/v/MyBatis.NET.SqlServer.svg)](https://www.nuget.org/packages/MyBatis.NET.SqlServer) [![NuGet Downloads](https://img.shields.io/nuget/dt/MyBatis.NET.SqlServer.svg)](https://www.nuget.org/packages/MyBatis.NET.SqlServer/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE) A lightweight MyBatis port for .NET, providing XML-based SQL mapping, runtime proxy generation, and transaction support. ## 📚 Documentation - **[QUICK_REFERENCE.md](QUICK_REFERENCE.md)** - Quick Start & Cheat Sheet - **[USAGE_GUIDE.md](USAGE_GUIDE.md)** - Comprehensive Usage Guide - **[SQL_LOGGING.md](SQL_LOGGING.md)** - SQL Logging Configuration - **[Tools/README.md](Tools/README.md)** - Code Generator Tool ## Features - **XML Mappers**: Define SQL statements in XML files with mandatory `returnSingle` attribute - **Dynamic SQL**: Support for ``, ``, ``, ``, ``, `` tags (like MyBatis Java) - **Runtime Proxy**: Automatically generate mapper implementations using dynamic proxies - **Optimized Performance**: Compiled Expression Trees with smart caching (2-3x faster for repeated queries) - **Code Generator**: Auto-generate C# interfaces from XML mappers (keeps them in sync!) - **SQL Logging**: Built-in SQL query and parameter logging for debugging - **Transaction Support**: Built-in transaction management - **Result Mapping**: Automatic mapping of query results to .NET objects with optimized caching - **ADO.NET Integration**: Uses Microsoft.Data.SqlClient for database connectivity - **Async Support**: Full asynchronous operations for all database interactions - **DDD Support**: Load mappers from multiple libraries and embedded resources ## Installation Install via NuGet: ```bash dotnet add package MyBatis.NET.SqlServer ``` Or using Package Manager: ```powershell Install-Package MyBatis.NET.SqlServer ``` ## 📖 Demo Project A complete working demo is included in this repository at **[Demo/MyBatis.TestApp](Demo/MyBatis.TestApp/)**! **Features demonstrated:** - ✅ **Dynamic SQL** - Full showcase of ``, ``, ``, ``, ``, and nested conditions - ✅ **Code Generator Tool** - How to use `mybatis-gen` to auto-generate interfaces - ✅ **returnSingle attribute** - Proper usage in v1.0.0 - ✅ **Basic CRUD** - Users table with simple operations - ✅ **Complex Queries** - Products table with multi-filter search, category filtering, and dynamic updates - ✅ **DDD Architecture** - Domain, Application, Infrastructure, and Presentation layers - ✅ **ASP.NET Core Web API** - RESTful endpoints with Swagger UI - ✅ **Async/Await** - Full async support - ✅ **Transaction Management** - Unit of Work pattern **Quick start:** ```bash cd Demo/MyBatis.TestApp dotnet restore dotnet run --project Presentation # Open https://localhost:5001/swagger ``` See **[Demo/MyBatis.TestApp/README.md](Demo/MyBatis.TestApp/README.md)** for detailed setup and API documentation. ## Quick Start ### 1. Define Your Entity ```csharp public class User { public int Id { get; set; } public string UserName { get; set; } = ""; public string Email { get; set; } = ""; } ``` ### 2. Create Mapper Interface ```csharp public interface IUserMapper { List GetAll(); User GetById(int id); int InsertUser(User user); int UpdateUser(int id, string userName, string email); int DeleteUser(int id); } ``` ### 3. Create XML Mapper Create a file `UserMapper.xml` in the `Mappers` directory: ```xml INSERT INTO Users (UserName, Email) VALUES (@UserName, @Email) UPDATE Users SET UserName = @userName, Email = @email WHERE Id = @id DELETE FROM Users WHERE Id = @Id ``` > **⚠️ Important (v1.0.0+)**: All ` SELECT * FROM Users AND UserName = @name AND Email = @email AND Age >= @age ``` Usage: ```csharp // Only search by name var users = mapper.FindUsers(name: "John", email: null, age: 0); // Search by name and age var users = mapper.FindUsers(name: "John", email: null, age: 18); ``` ### `` - Smart WHERE clause The `` tag automatically adds WHERE and removes leading AND/OR: ```xml ``` ### `` - Smart SET clause for UPDATE The `` tag automatically adds SET and removes trailing commas: ```xml UPDATE Users UserName = @userName, Email = @email, Age = @age, WHERE Id = @id ``` ### ``, ``, `` - Switch/Case ```xml ``` ### `` - Loop for IN clauses ```xml ``` Usage: ```csharp var ids = new[] { 1, 2, 3, 4, 5 }; var users = mapper.FindUsersByIds(ids); // Generates: WHERE Id IN (1, 2, 3, 4, 5) ``` ### `` - Custom prefix/suffix handling ```xml ``` ### Expression Syntax Dynamic SQL conditions support: - **Null checks**: `name != null`, `email == null` - **Comparisons**: `age > 18`, `score >= 90`, `level < 5`, `count <= 100` - **Equality**: `type == 'admin'`, `status != 'inactive'` - **Logical operators**: `name != null and age > 18`, `status == 'active' or role == 'admin'` - **Negation**: `!isDeleted` - **Simple existence**: `name` (true if parameter exists and is not null/empty) ### Complex Example ```xml ``` ## Supported SQL Operations - `SELECT` (returns List or single T, sync and async) - `INSERT`, `UPDATE`, `DELETE` (returns affected row count, sync and async) ## SQL Logging Enable SQL logging to see generated queries and parameters: ```csharp // Enable SQL logging SqlSessionConfiguration.EnableSqlLogging = true; // Enable SQL + Parameter logging SqlSessionConfiguration.EnableSqlLogging = true; SqlSessionConfiguration.EnableParameterLogging = true; ``` **Output Example:** ``` ═══════════════════════════════════════ [MyBatis.NET SQL] 14:52:07.910 ─────────────────────────────────────── SELECT * FROM Users WHERE Role IN (@role_0,@role_1) ─────────────────────────────────────── Parameters: @role_0 = 'Admin' @role_1 = 'Manager' ═══════════════════════════════════════ ``` 📖 See [SQL_LOGGING.md](./SQL_LOGGING.md) for complete documentation. ## Requirements - .NET 8.0 or later - Microsoft.Data.SqlClient (included as dependency) ## Contributing Contributions are welcome! Please feel free to submit issues and pull requests. ## License MIT License - see LICENSE file for details. ## Version History ### Version 1.0.0-preview.1 (Current Preview) - First public preview for the `MyBatis.NET.SqlServer` package line - Core runtime and documentation aligned for roadmap-driven releases - Release quality gate validated (build, unit tests, package generation) ### Version 1.0.0 (Planned Stable) Initial release line for the SQL Server package `MyBatis.NET.SqlServer`. - XML-based mappers with mandatory `returnSingle` on `