https://github.com/zq2599/blog_demosjava
內容:全部原創文章分類彙總及配套源碼,涉及Java、Docker、Kubernetes、DevOPS等;mysql
《MyBatis初級實戰》系列旨在經過一系列編碼實戰,和讀者一塊兒掌握MyBatis的基本用法,幫助初學者快速運用MyBatis參與實際開發;git
《MyBatis初級實戰》面向的是對MyBatis有興趣的讀者,向讀者們提供可用的方案和代碼,這裏不是比較Hibernate、sqltoy-orm的地方,做者也十分承認這些ORM框架,但《MyBatis初級實戰》不參與比較;程序員
引自官方:MyBatis 是一款優秀的持久層框架,它支持自定義 SQL、存儲過程以及高級映射。MyBatis 免除了幾乎全部的 JDBC 代碼以及設置參數和獲取結果集的工做。MyBatis 能夠經過簡單的 XML 或註解來配置和映射原始類型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 對象)爲數據庫中的記錄。github
《MyBatis初級實戰》系列的環境信息以下:web
Spring Boot集成MyBatis的常規步驟以下:spring
USE mybatis; DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(32) NOT NULL AUTO_INCREMENT, `name` varchar(32) NOT NULL, `age` int(32) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; DROP TABLE IF EXISTS `log`; CREATE TABLE `log` ( `id` int(32) NOT NULL AUTO_INCREMENT, `user_id` int(32), `action` varchar(255) NOT NULL, `create_time` datetime not null, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; INSERT INTO mybatis.user (id, name, age) VALUES (3, 'tom', 11); INSERT INTO mybatis.log (id, user_id, action, create_time) VALUES (3, 3, 'read book', '2020-08-07 08:18:16');
名稱 | 連接 | 備註 |
---|---|---|
項目主頁 | https://github.com/zq2599/blog_demos | 該項目在GitHub上的主頁 |
git倉庫地址(https) | https://github.com/zq2599/blog_demos.git | 該項目源碼的倉庫地址,https協議 |
git倉庫地址(ssh) | git@github.com:zq2599/blog_demos.git | 該項目源碼的倉庫地址,ssh協議 |
爲了整個系列的代碼好管理,我這邊用maven建立的是父子工程,若是您只要子工程,不須要父子結構,要對子工程的pom.xml作如下調整:sql
<parent> <groupId>com.bolingcavalry</groupId> <artifactId>mybatis</artifactId> <version>1.0-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent>
請替換成如下內容(也就是直接用>spring-boot-starter-parent做爲父工程):docker
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.2.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent>
建立名爲mybatis的maven工程,pom.xml內容以下:shell
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.2.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.bolingcavalry</groupId> <artifactId>mybatis</artifactId> <version>1.0-SNAPSHOT</version> <packaging>pom</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <modules> <module>simple</module> </modules> <dependencyManagement> <dependencies> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency> </dependencies> </dependencyManagement> </project>
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.bolingcavalry</groupId> <artifactId>mybatis</artifactId> <version>1.0-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> <groupId>com.bolingcavalry</groupId> <artifactId>simple</artifactId> <version>0.0.1-SNAPSHOT</version> <name>simple</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
server: port: 8080 spring: # 數據源 datasource: username: root password: 123456 url: jdbc:mysql://192.168.50.43:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC driver-class-name: com.mysql.cj.jdbc.Driver # mybatis配置 mybatis: # 配置文件所在位置 config-location: classpath:mybatis-config.xml # 映射文件所在位置 mapper-locations: classpath:mappers/*Mapper.xml # 日誌配置 logging: level: root: INFO com: bolingcavalry: simple: mapper: debug
package com.bolingcavalry.simple.entity; /** * @Description: 實體類 * @author: willzhao E-mail: zq2599@gmail.com * @date: 2020/8/4 8:24 */ public class User { private Integer id; private String name; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }
package com.bolingcavalry.simple.entity; import java.sql.Date; /** * @Description: 實體類 * @author: willzhao E-mail: zq2599@gmail.com * @date: 2020/8/4 8:24 */ public class Log { private Integer id; private Integer userId; private String action; private Date createTime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String toString() { return "Log{" + "id=" + id + ", userId=" + userId + ", action='" + action + '\'' + ", createTime=" + createTime + '}'; } }
6. application.yml所在目錄下,新增名爲mybatis-config.xml的文件,這是mybatis的配置文件,本例很簡單隻有一個配置,內容以下:
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <!-- 映射文件中的類不用寫全路徑了--> <package name="com.bolingcavalry.simple.entity"/> </typeAliases> </configuration>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.bolingcavalry.simple.mapper.UserMapper"> <select id="sel" parameterType="int" resultType="User"> select * from user where id = #{id} </select> </mapper>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.bolingcavalry.simple.mapper.LogMapper"> <resultMap id="logResultMap" type="Log"> <id property="id" column="id" /> <result column="user_id" jdbcType="INTEGER" property="userId" /> <result column="action" jdbcType="VARCHAR" property="action" /> <result column="create_time" jdbcType="TIMESTAMP" property="createTime" /> </resultMap> <select id="sel" parameterType="int" resultMap="logResultMap"> select * from log where id = #{id} </select> </mapper>
package com.bolingcavalry.simple.mapper; import com.bolingcavalry.simple.entity.User; import org.springframework.stereotype.Repository; @Repository public interface UserMapper { User sel(int id); }
package com.bolingcavalry.simple.mapper; import com.bolingcavalry.simple.entity.Log; import org.springframework.stereotype.Repository; @Repository public interface LogMapper { Log sel(int id); }
12. 映射配置完畢,接下來就能夠在應用中使用了,先爲user作一個service類UserService.java,裏面經過Autowired註解注入UserMapper的實現:
package com.bolingcavalry.simple.service; import com.bolingcavalry.simple.entity.User; import com.bolingcavalry.simple.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired UserMapper userMapper; public User sel(int id){ return userMapper.sel(id); } }
package com.bolingcavalry.simple.service; import com.bolingcavalry.simple.entity.Log; import com.bolingcavalry.simple.mapper.LogMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class LogService { @Autowired LogMapper logMapper; public Log sel(int id){ return logMapper.sel(id); } }
package com.bolingcavalry.simple.controller; import com.bolingcavalry.simple.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @Autowired private UserService userService; @RequestMapping("user/{id}") public String GetUser(@PathVariable int id){ return userService.sel(id).toString(); } }
package com.bolingcavalry.simple.controller; import com.bolingcavalry.simple.service.LogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class LogController { @Autowired private LogService logService; @RequestMapping("log/{id}") public String log(@PathVariable int id){ return logService.sel(id).toString(); } }
package com.bolingcavalry.simple; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("com.bolingcavalry.simple.mapper") public class SimpleApplication { public static void main(String[] args) { SpringApplication.run(SimpleApplication.class, args); } }
4. 訪問http://localhost:8080/log/3,能夠獲得log表的查詢結果:
5. 在控制檯能夠看到日誌以下所示,這是咱們開發期間調試問題的重要線索:
至此,入門級SpringBoot集成MyBatis的實戰就完成了,接下來的系列內容會有更多實戰,我們一塊兒來學習和掌握MyBatis的基本用法;
微信搜索「程序員欣宸」,我是欣宸,期待與您一同暢遊Java世界...