From e82b3dbbc618ae1698fb47b4341729e01f320262 Mon Sep 17 00:00:00 2001 From: jacky Date: Fri, 21 Feb 2025 23:49:03 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20MyBatis=20=E5=BF=AB?= =?UTF-8?q?=E9=80=9F=E5=85=A5=E9=97=A8=E7=AC=94=E8=AE=B0=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .obsidian/workspace.json | 34 +++++--- ...53\351\200\237\345\205\245\351\227\250.md" | 86 +++++++++++++++---- mkdocs.yml | 7 +- 3 files changed, 98 insertions(+), 29 deletions(-) diff --git a/.obsidian/workspace.json b/.obsidian/workspace.json index ba5c16ef..9ad33817 100644 --- a/.obsidian/workspace.json +++ b/.obsidian/workspace.json @@ -78,6 +78,18 @@ { "id": "54a6a2097fcd82ce", "type": "leaf", + "state": { + "type": "vscode-editor", + "state": { + "file": "docs/stylesheets/extra.css" + }, + "icon": "lucide-file", + "title": "extra" + } + }, + { + "id": "326541516c80c316", + "type": "leaf", "state": { "type": "markdown", "state": { @@ -90,7 +102,7 @@ } } ], - "currentTab": 5 + "currentTab": 6 } ], "direction": "vertical" @@ -143,8 +155,7 @@ "title": "书签" } } - ], - "currentTab": 1 + ] } ], "direction": "horizontal", @@ -237,10 +248,16 @@ "vscode-editor:新建代码文件": false } }, - "active": "54a6a2097fcd82ce", + "active": "326541516c80c316", "lastOpenFiles": [ - "mkdocs.yml", + "docs/stylesheets/extra.css", "docs/Java/MyBatis 快速入门.md", + "mkdocs.yml", + "docs/Java/Tips.md", + "docs/Java/NIO Tips.md", + "overrides/partials/footer.html", + "overrides/partials/comments.html", + "overrides/copy-code.js", "docs/Linux/Nginx Tips.md", "docs/OS/Nginx/Nginx 安装.md", "docs/Linux/正则表达式.md", @@ -275,13 +292,8 @@ "docs/LocalFile/Picture/Pasted image 20250117000101.png", "docs/Flink", "docs/MySQL/索引.md", - "docs/MySQL/事务.md", - "docs/Linux/OpenLDAP.md", "docs/Prometheus", - "overrides/partials/comments.html", - "overrides/partials/footer.html", "docs/LocalFile/Picture/ReentrantReadWriteLock类图.svg", - "docs/PG", - "docs/Doris" + "docs/PG" ] } \ No newline at end of file diff --git "a/docs/Java/MyBatis \345\277\253\351\200\237\345\205\245\351\227\250.md" "b/docs/Java/MyBatis \345\277\253\351\200\237\345\205\245\351\227\250.md" index 515341af..eb710b82 100644 --- "a/docs/Java/MyBatis \345\277\253\351\200\237\345\205\245\351\227\250.md" +++ "b/docs/Java/MyBatis \345\277\253\351\200\237\345\205\245\351\227\250.md" @@ -1,21 +1,25 @@ MyBatis 官网:https://mybatis.org/mybatis-3/zh_CN/index.html ## 准备数据 +DDL ```sql DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `username` varchar(100) NOT NULL COMMENT '姓名', `age` int NOT NULL COMMENT '年龄', `create_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '数据创建时间' -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='用户信息表'; +) ENGINE=InnoDB COMMENT='用户信息表'; -INSERT INTO `user` VALUES ('jacky',22,'2025-02-14 10:52:01'),('otto',18,'2025-02-14 10:52:01'),('zhangsan',25,'2025-02-14 10:52:01'); +INSERT INTO `user` +VALUES + ('jacky',22,'2025-02-14 10:52:01'), + ('otto',18,'2025-02-14 10:52:01'), + ('zhangsan',25,'2025-02-14 10:52:01'); ``` - 实体类 ```java -package com.jacky.mybatis.entity; +package com.otto.mybatis.entity; import java.time.LocalDateTime; @@ -32,8 +36,6 @@ public class User { ``` ## 直接使用 JDBC 查询数据 -直接使用 JDBC 查询数据。 - 添加依赖 ``` @@ -69,7 +71,6 @@ public class JDBCTest { ``` ## 使用 MyBatis - 添加依赖 ```xml @@ -103,8 +104,8 @@ public class JDBCTest { - - + + @@ -123,13 +124,12 @@ public class JDBCTest { PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd"> - select username, age, create_at as createAt from user where username = #{username} and age = #{age} ``` - 查询数据代码 ```java @@ -159,7 +159,6 @@ public class MyBatisTest { > > 示例代码中参数如果有多个占位符参数的话,可以使用 Map 传递参数,使用占位符名称作为键,实际的参数作为值。 - ### 使用 Mapper 代理开发 配置 Maven 打包代码包里面的 xml 文件。 ```xml @@ -184,25 +183,25 @@ public class MyBatisTest { ```xml - + ``` -新增 com.jacky.mybatis.mapper.UserMapper.java 文件 +新增 com.otto.mybatis.mapper.UserMapper.java 文件 ```java public interface UserMapper { List selectAll(@Param("username") String username, @Param("age") Integer age); } ``` -新增 com.jacky.mybatis.mapper.UserMapper.xml 文件 +新增 com.otto.mybatis.mapper.UserMapper.xml 文件 ```xml - - select username, age, create_at as createAt from user where username = #{username} and age = #{age} @@ -213,4 +212,57 @@ public interface UserMapper { UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List userList = userMapper.selectAll("jacky", 22); System.out.println("query result: ==> " + userList); +``` + +### 不使用 XML 构建 SqlSessionFactory +使用单例模式构建 SqlSessionFactory +```java +public class MyBatisConfig { + + private static SqlSessionFactory FACTORY_INSTANCE = null; + + public static SqlSessionFactory sqlSessionFactory() { + if (FACTORY_INSTANCE == null) { + synchronized (MyBatisConfig.class) { + if (FACTORY_INSTANCE == null) { + // 配置数据源 + PooledDataSource dataSource = new PooledDataSource(); + dataSource.setDriver("com.mysql.cj.jdbc.Driver"); + dataSource.setUrl("jdbc:mysql://192.168.199.129:3306/test_db"); + dataSource.setUsername("xxx"); + dataSource.setPassword("xxxxx"); + // 配置事务管理器 + JdbcTransactionFactory transactionFactory = new JdbcTransactionFactory(); + // 配置环境 + Environment environment = new Environment("development", transactionFactory, dataSource); + // 配置 MyBatis + Configuration configuration = new Configuration(environment); + // 设置日志实现为标准输出 + configuration.setLogImpl(org.apache.ibatis.logging.stdout.StdOutImpl.class); + // 如果 Mapper 接口都在同一个包下,可以使用包扫描 + configuration.addMappers("com.otto.mybatis.mapper"); + // 构建 SqlSessionFactory + FACTORY_INSTANCE = new SqlSessionFactoryBuilder().build(configuration); + } + } + } + return FACTORY_INSTANCE; + } +} +``` + +进一步简化调用代码 +```java +public class App { + public static void main(String[] args) throws IOException { + // 从 SqlSessionFactory 中获取 SqlSession + try(SqlSession sqlSession = MyBatisConfig.sqlSessionFactory().openSession()) { + + UserMapper userMapper = sqlSession.getMapper(UserMapper.class); + + List userList = userMapper.selectAll("jacky", 22); + System.out.println("query result: ==> " + userList); + } + } +} ``` \ No newline at end of file diff --git a/mkdocs.yml b/mkdocs.yml index 2aeda01a..1d803b25 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -12,9 +12,12 @@ theme: features: - navigation.tabs - navigation.top + - content.code.copy + - content.code.select + language: zh markdown_extensions: - pymdownx.highlight: - anchor_linenums: true + linenums: true - admonition - pymdownx.details - pymdownx.inlinehilite @@ -113,3 +116,5 @@ nav: extra_css: - stylesheets/extra.css +extra_javascript: + - copy-code.js