YouTip LogoYouTip

Java Mybatis

[![Image 1: Java Common Libraries](#) Java Common Libraries](#)\n\n* * *\n\nMyBatis is an excellent persistence framework that simplifies the interaction between Java applications and relational databases. MyBatis maps SQL statements to Java objects through XML or annotations, avoiding a large amount of boilerplate code in traditional JDBC programming.\n\n* * *\n\n## Core Features of MyBatis\n\n### 1. Separation of SQL and Code\n\nMyBatis allows developers to separate SQL statements from Java code, storing them in XML files or annotations, making the code clearer and easier to maintain.\n\n### 2. Automatic Mapping\n\nMyBatis can automatically map database query results to Java objects, greatly reducing the workload of data conversion.\n\n### 3. Dynamic SQL\n\nMyBatis provides powerful dynamic SQL functionality, allowing different SQL statements to be generated based on different conditions.\n\n### 4. Caching Mechanism\n\nMyBatis has built-in first-level and second-level caches, which can effectively improve application performance.\n\n* * *\n\n## Basic Architecture of MyBatis\n\n### 1. Core Components\n\n* **SqlSessionFactory**: Factory class for creating SqlSession\n* **SqlSession**: Main interface for executing SQL commands\n* **Mapper Interface**: Defines methods for database operations\n* **Mapper XML**: Configuration file containing SQL statements\n\n### 2. Workflow\n\n1. Application creates SqlSessionFactory through SqlSessionFactoryBuilder\n2. SqlSessionFactory creates SqlSession\n3. SqlSession obtains instance of Mapper interface\n4. Calls Mapper methods to execute database operations\n5. Commits transaction and closes SqlSession\n\n* * *\n\n## MyBatis Configuration\n\n### 1. Main Configuration File (mybatis-config.xml)\n\n## Example\n\n### 2. Mapper File Example\n\n## Example\n\n SELECT * FROM users WHERE id = #{id}\n\n INSERT INTO users(name, email) VALUES(#{name}, #{email})\n\n* * *\n\n## Basic Usage of MyBatis\n\n### 1. Obtaining SqlSession\n\n## Example\n\nString resource = "mybatis-config.xml";\n\nInputStream inputStream = Resources.getResourceAsStream(resource);\n\n SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);\n\n SqlSession session = sqlSessionFactory.openSession();\n\n### 2. Executing Queries\n\n## Example\n\n// Method 1: Directly using SqlSession\n\n User user = session.selectOne("com.example.mapper.UserMapper.getUserById", 1);\n\n// Method 2: Through Mapper interface\n\n UserMapper mapper = session.getMapper(UserMapper.class);\n\n User user = mapper.getUserById(1);\n\n### 3. Executing Insertions\n\n## Example\n\nUser newUser = new User();\n\n newUser.setName("Zhang San");\n\n newUser.setEmail("zhangsan@example.com");\n\nint rows = mapper.insertUser(newUser);\n\n session.commit(); // Commit transaction\n\n* * *\n\n## Dynamic SQL in MyBatis\n\nMyBatis provides various dynamic SQL elements that can dynamically generate SQL statements based on different conditions:\n\n### 1. if Element\n\n## Example\n\n SELECT * FROM users\n\n WHERE 1=1\n\n AND name = #{name}\n\n AND email = #{email}\n\n### 2. choose/when/otherwise Elements\n\n## Example\n\n SELECT * FROM users\n\n WHERE status = 'ACTIVE'\n\n AND name like #{name}\n\n AND email = #{email}\n\n AND 1=1\n\n### 3. foreach Element\n\n## Example\n\n SELECT * FROM users\n\n WHERE id IN\n\n #{id}\n\n* * *\n\n## Association Queries in MyBatis\n\n### 1. One-to-One Association\n\n## Example\n\n SELECT \n\n u.id as user_id, u.name as user_name,\n\n a.id as address_id, a.street, a.city\n\n FROM users u\n\n LEFT JOIN addresses a ON u.address_id = a.id\n\n WHERE u.id = #{id}\n\n### 2. One-to-Many Association\n\n## Example\n\n SELECT \n\n u.id as user_id, u.name as user_name,\n\n o.id as order_id, o.order_date, o.amount\n\n FROM users u\n\n LEFT JOIN orders o ON u.id = o.user_id\n\n WHERE u.id = #{id}\n\n* * *\n\n## Caching Mechanism in MyBatis\n\n### 1. First-Level Cache\n\nFirst-level cache is SqlSession-level cache, enabled by default. In the same SqlSession, the same query will only execute SQL once.\n\n**Features:**\n\n* Scope: `SqlSession` level (enabled by default, cannot be disabled)\n\n* Lifecycle: Created with `SqlSession` creation, destroyed with `SqlSession` closure\n\n* Situations triggering cache clearing:\n\n * Executing `INSERT/UPDATE/DELETE` operations\n\n * Calling `sqlSession.clearCache()`\n\n * Executing transaction rollback\n\n * Configuring different `Statement ID` (even if SQL is the same)\n\n**Notes:**\n\n## Example\n\n// Example: Same query only executes once in the same SqlSession\n\n User user1 = sqlSession.selectOne("getUserById", 1); // Executes SQL\n\n User user2 = sqlSession.selectOne("getUserById", 1); // Retrieved from cache\n\n### 2. Second-Level Cache\n\nSecond-level cache is Mapper-level cache, multiple SqlSessions can share the cache. Needs to be enabled in configuration file:\n\n \nAnd configured in Mapper file:\n\n<cache eviction="LRU" flushInterval="60000" size="512" readOnly="true"/> \n**Cache Strategy Comparison:**\n\n| Strategy | Description | Applicable Scenario |\n| --- | --- | --- |\n| LRU | Least Recently Used | General use |\n| FIFO | First In First Out | Fixed order access |\n| SOFT | Soft reference | Memory-sensitive scenarios |\n| WEAK | Weak reference | Extremely memory-sensitive scenarios |\n\n* * *\n\n## MyBatis Integration with Spring\n\n### 1. Dependency Configuration (Modern Spring Boot Recommended)\n\n## Example\n\n\n\n\n\norg.mybatis.spring.boot\n\nmybatis-spring-boot-starter\n\n3.0.3\n\n\n\norg.mybatis\n\nmybatis-spring\n\n3.0.3\n\n\n\ncom.mysql\n\nmysql-connector-j\n\n8.0.33\n\n### 2. Configuration Options (Three Main Approaches)\n\n#### Approach 1: Spring Boot Auto-configuration (Simplest)\n\n## Example\n\n# application.yml\n\n mybatis:\n\n mapper-locations: classpath*:mapper/**/*.xml\n\n type-aliases-package: com.example.model\n\n configuration:\n\n map-underscore-to-camel-case: true # Automatic camelCase conversion\n\n#### Approach 2: Java Config Full Configuration (Fine-grained Control)\n\n## Example\n\n@Configuration\n\npublic class MyBatisConfig {\n\n@Bean\n\n @ConfigurationProperties(prefix = "spring.datasource")\n\npublic DataSource dataSource(){\n\nreturn DataSourceBuilder.create().build();\n\n}\n\n@Bean\n\npublic SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception{\n\n SqlSessionFactoryBean factory = new SqlSessionFactoryBean();\n\n factory.setDataSource(dataSource);\n\n factory.setTypeAliasesPackage("com.example.model");\n\n// Custom configuration (example)\n\n org.apache.ibatis.session.Configuration config = new Configuration();\n\n config.setMapUnderscoreToCamelCase(true);\n\n config.setDefaultFetchSize(100);\n\n factory.setConfiguration(config);\n\n// Plugin configuration (example)\n\n factory.setPlugins(\n\nnew MyBatisInterceptor(),\n\nnew PaginationInterceptor()\n\n);\n\nreturn factory.getObject();\n\n}\n\n@Bean\n\npublic MapperScannerConfigurer mapperScanner(){\n\n MapperScannerConfigurer scanner = new MapperScannerConfigurer();\n\n scanner.setBasePackage("com.example.mapper");\n\n scanner.setAnnotationClass(Repository.class); // Limit annotation scanning\n\nreturn scanner;\n\n}\n\n}\n\n#### Approach 3: XML Traditional Configuration (Compatible with Legacy Projects)\n\n## Example\n\n
← Pycharm DjangoJava Springboot Framework β†’