MyBatis 是一款優秀的持久層框架,它支持定製化 SQL、存儲過程以及高級映射。MyBatis 避免了幾乎全部的 JDBC 代碼和手動設置參數以及獲取結果集。MyBatis 可使用簡單的 XML 或註解來配置和映射原生類型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 對象)爲數據庫中的記錄。MyBatis是一款半ORM框架,相對於Hibernate這樣的徹底ORM框架,MyBatis顯得更加靈活,由於能夠直接控制SQL語句,因此使用MyBatis能夠很是方便的實現各類複雜的查詢需求。固然了,有利必有弊,也正由於太過自由,因此須要本身編寫SQL語句,而如何編寫更爲簡潔高效的SQL語句,也是一門學問。
html
接下來,咱們就經過實際案例來說解MyBatis的整合,而後提供相關的服務來學習瞭解數據庫的操做。java
爲方便咱們初始化項目,Spring Boot給咱們提供一個項目模板生成網站。mysql
1. 打開瀏覽器,訪問:https://start.spring.io/git
2. 根據頁面提示,選擇構建工具,開發語言,項目信息等。web
3. 點擊 Generate the project,生成項目模板,生成以後會將壓縮包下載到本地。spring
4. 使用IDE導入項目,我這裏使用Eclipse,經過導入Maven項目的方式導入。sql
這裏使用MySQL數據庫,版本是8.0.16,在項目根目錄下新建db目錄,而後在其中編寫一個數據庫腳本文件。數據庫
在MySQL數據庫新建一個springboot數據庫,而後在此數據庫中執行下面的腳本建立項目用戶表和用戶數據。apache
腳本文件api
SQL腳本內容
springboot.sql
-- ---------------------------- -- Table structure for sys_user -- ---------------------------- DROP TABLE IF EXISTS `sys_user`; CREATE TABLE `sys_user` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '編號', `name` varchar(50) NOT NULL COMMENT '用戶名', `nick_name` varchar(150) DEFAULT NULL COMMENT '暱稱', `avatar` varchar(150) DEFAULT NULL COMMENT '頭像', `password` varchar(100) DEFAULT NULL COMMENT '密碼', `salt` varchar(40) DEFAULT NULL COMMENT '加密鹽', `email` varchar(100) DEFAULT NULL COMMENT '郵箱', `mobile` varchar(100) DEFAULT NULL COMMENT '手機號', `status` tinyint(4) DEFAULT NULL COMMENT '狀態 0:禁用 1:正常', `dept_id` bigint(20) DEFAULT NULL COMMENT '機構ID', `create_by` varchar(50) DEFAULT NULL COMMENT '建立人', `create_time` datetime DEFAULT NULL COMMENT '建立時間', `last_update_by` varchar(50) DEFAULT NULL COMMENT '更新人', `last_update_time` datetime DEFAULT NULL COMMENT '更新時間', `del_flag` tinyint(4) DEFAULT '0' COMMENT '是否刪除 -1:已刪除 0:正常', PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`) ) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=utf8 COMMENT='用戶管理'; -- ---------------------------- -- Records of sys_user -- ---------------------------- INSERT INTO `sys_user` VALUES ('1', 'admin', '管理員', null, 'bd1718f058d8a02468134432b8656a86', 'YzcmCZNvbXocrsz9dm8e', 'admin@qq.com', '13612345678', '1', '4', 'admin', '2018-08-14 11:11:11', 'admin', '2018-08-14 11:11:11', '0'); INSERT INTO `sys_user` VALUES ('2', 'liubei', '劉備', null, 'fd80ebd493a655608dc893a9f897d845', 'YzcmCZNvbXocrsz9dm8e', 'test@qq.com', '13889700023', '1', '7', 'admin', '2018-09-23 19:43:00', 'admin', '2019-01-10 11:41:13', '0'); INSERT INTO `sys_user` VALUES ('3', 'zhaoyun', '趙雲', null, 'fd80ebd493a655608dc893a9f897d845', 'YzcmCZNvbXocrsz9dm8e', 'test@qq.com', '13889700023', '1', '7', 'admin', '2018-09-23 19:43:44', 'admin', '2018-09-23 19:43:52', '0'); INSERT INTO `sys_user` VALUES ('4', 'zhugeliang', '諸葛亮', null, 'fd80ebd493a655608dc893a9f897d845', 'YzcmCZNvbXocrsz9dm8e', 'test@qq.com', '13889700023', '7', '11', 'admin', '2018-09-23 19:44:23', 'admin', '2018-09-23 19:44:29', '0'); INSERT INTO `sys_user` VALUES ('5', 'caocao', '曹操', null, 'fd80ebd493a655608dc893a9f897d845', 'YzcmCZNvbXocrsz9dm8e', 'test@qq.com', '13889700023', '1', '8', 'admin', '2018-09-23 19:45:32', 'admin', '2019-01-10 17:59:14', '0'); INSERT INTO `sys_user` VALUES ('6', 'dianwei', '典韋', null, 'fd80ebd493a655608dc893a9f897d845', 'YzcmCZNvbXocrsz9dm8e', 'test@qq.com', '13889700023', '1', '10', 'admin', '2018-09-23 19:45:48', 'admin', '2018-09-23 19:45:57', '0'); INSERT INTO `sys_user` VALUES ('7', 'xiahoudun', '夏侯惇', null, 'fd80ebd493a655608dc893a9f897d845', 'YzcmCZNvbXocrsz9dm8e', 'test@qq.com', '13889700023', '1', '8', 'admin', '2018-09-23 19:46:09', 'admin', '2018-09-23 19:46:17', '0'); INSERT INTO `sys_user` VALUES ('8', 'xunyu', '荀彧', null, 'fd80ebd493a655608dc893a9f897d845', 'YzcmCZNvbXocrsz9dm8e', 'test@qq.com', '13889700023', '1', '10', 'admin', '2018-09-23 19:46:38', 'admin', '2018-11-04 15:33:17', '0'); INSERT INTO `sys_user` VALUES ('9', 'sunquan', '孫權', null, 'fd80ebd493a655608dc893a9f897d845', 'YzcmCZNvbXocrsz9dm8e', 'test@qq.com', '13889700023', '1', '10', 'admin', '2018-09-23 19:46:54', 'admin', '2018-09-23 19:47:03', '0'); INSERT INTO `sys_user` VALUES ('0', 'zhouyu', '周瑜', null, 'fd80ebd493a655608dc893a9f897d845', 'YzcmCZNvbXocrsz9dm8e', 'test@qq.com', '13889700023', '1', '11', 'admin', '2018-09-23 19:47:28', 'admin', '2018-09-23 19:48:04', '0'); INSERT INTO `sys_user` VALUES ('11', 'luxun', '陸遜', null, 'fd80ebd493a655608dc893a9f897d845', 'YzcmCZNvbXocrsz9dm8e', 'test@qq.com', '13889700023', '1', '11', 'admin', '2018-09-23 19:47:44', 'admin', '2018-09-23 19:47:58', '0'); INSERT INTO `sys_user` VALUES ('12', 'huanggai', '黃蓋', null, 'fd80ebd493a655608dc893a9f897d845', 'YzcmCZNvbXocrsz9dm8e', 'test@qq.com', '13889700023', '1', '11', 'admin', '2018-09-23 19:48:38', 'admin', '2018-09-23 19:49:02', '0');
添加 Maven 相關依賴,這裏須要添加上WEB和Swagger和MyBatis的依賴,Swagger的添加是爲了方便接口測試。
WEB依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
swagger依賴,這裏選擇 2.9.2 版本。
<!-- swagger --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
這裏使用MySQL數據庫,因此須要MySQL驅動。
<!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
MyBatis依賴
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.0</version> </dependency>
1. 添加swagger 配置
添加一個swagger 配置類,在工程下新建 config 包並添加一個 SwaggerConfig 配置類。
SwaggerConfig.java
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi(){ return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()).build(); } private ApiInfo apiInfo(){ return new ApiInfoBuilder() .title("SpringBoot API Doc") .description("This is a restful api document of Spring Boot.") .version("1.0") .build(); } }
2.添加MyBatis配置
添加MyBatis配置類,配置相關掃描路徑,包括DAO,Model,XML映射文件的掃描。
在config包下新建一個MyBatis配置類,MybatisConfig.java。
MybatisConfig.java
package com.louis.springboot.demo.config; import javax.sql.DataSource; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; @Configuration @MapperScan("com.louis.springboot.**.dao") // 掃描DAO public class MybatisConfig { @Autowired private DataSource dataSource; @Bean public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dataSource); sessionFactory.setTypeAliasesPackage("com.louis.springboot.**.model"); // 掃描Model PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); sessionFactory.setMapperLocations(resolver.getResources("classpath*:**/sqlmap/*.xml")); // 掃描映射文件 return sessionFactory.getObject(); } }
3.添加數據源配置
將application.properties文件更名爲application.yml ,並在其中添加MySQL數據源鏈接信息。
注意:
這裏須要首先建立一個MySQL數據庫,並輸入本身的用戶名和密碼。這裏的數據庫是springboot。
另外,若是你使用的是MySQL 5.x及之前版本,驅動配置driverClassName是com.mysql.jdbc.Driver。
application.yml
server: port: 8080 spring: datasource: driverClassName: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=utf-8 username: root password: 123456
因爲手動編寫MyBatis的Model、DAO、XML映射文件比較繁瑣,一般都會經過一些生成工具來生成。MyBatis官方也提供了生成工具(MyBaits Generator),另外還有一些基於官方基礎上改進的第三方工具,好比MyBatis Plus就是國內提供的一款很是優秀的開源工具,網上相關教程比較多,這裏就再也不贅述了。
這裏提供一些資料做爲參考。
Mybatis Generator 官網:http://www.mybatis.org/generator/index.html
Mybatis Generator 教程:https://blog.csdn.net/testcs_dn/article/details/77881776
MyBatis Plus 官網: http://mp.baomidou.com/#/
MyBatis Plus 官網: http://mp.baomidou.com/#/quick-start
代碼生成好以後,分別將MODEL、DAO、XML映射文件拷貝到相應的包裏。
打開Mapper,咱們看到MyBatis Generator給咱們默認生成了一些增刪改查的方法。
SysUserMapper.java
package com.louis.springboot.demo.dao; import com.louis.springboot.demo.model.SysUser; public interface SysUserMapper { int deleteByPrimaryKey(Long id); int insert(SysUser record); int insertSelective(SysUser record); SysUser selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(SysUser record); int updateByPrimaryKey(SysUser record); }
向 SysUserMapper 類中新一個 selectAll 方法,用於查詢全部的用戶信息。
SysUserMapper.java
package com.louis.springboot.demo.dao; import java.util.List; import com.louis.springboot.demo.model.SysUser; public interface SysUserMapper { int deleteByPrimaryKey(Long id); int insert(SysUser record); int insertSelective(SysUser record); SysUser selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(SysUser record); int updateByPrimaryKey(SysUser record); /** * 查詢所有用戶 * @return */ List<SysUser> selectAll(); }
向 SysUserMapper.xml 中加入 selectAll 的查詢語句。
SysUserMapper.xml
<select id="selectAll" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from sys_user </select>
新建service包,並在其中編寫 SysUserService 接口,包含 selectAll 和 findByUserId 兩個方法。
SysUserService.java
package com.louis.springboot.demo.service; import java.util.List; import com.louis.springboot.demo.model.SysUser; public interface SysUserService { /** * 根據用戶ID查找用戶 * @param userId * @return */ SysUser findByUserId(Long userId); /** * 查找全部用戶 * @return */ List<SysUser> findAll(); }
在service包下新建impl包,並在其中編寫 SysUserServiceImpl 實現類,調用 SysUserMapper 方法完成查詢操做。
SysUserServiceImpl.java
package com.louis.springboot.demo.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.louis.springboot.demo.dao.SysUserMapper; import com.louis.springboot.demo.model.SysUser; import com.louis.springboot.demo.service.SysUserService; @Service public class SysUserServiceImpl implements SysUserService { @Autowired private SysUserMapper sysUserMapper; @Override public SysUser findByUserId(Long userId) { return sysUserMapper.selectByPrimaryKey(userId); } @Override public List<SysUser> findAll() { return sysUserMapper.selectAll(); } }
新建一個controller包,並在其中編寫 SysUserController restful 接口,返回JSON數據格式,提供外部調用。
SysUserController.java
package com.louis.springboot.demo.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.louis.springboot.demo.service.SysUserService; @RestController @RequestMapping("user") public class SysUserController { @Autowired private SysUserService sysUserService; @GetMapping(value="/findByUserId") public Object findByUserId(@RequestParam Long userId) { return sysUserService.findByUserId(userId); } @GetMapping(value="/findAll") public Object findAll() { return sysUserService.findAll(); } }
雖然代碼編寫已經完成,但此時啓動運行仍是會有問題的,由於在編譯打包的時候,咱們的XML映射文件是不在默認打包範圍內的,因此須要修改一下配置。
修改 pom.xml ,在 build 標籤內加入形如如下的 resource 標籤的打包配置,這樣代碼打包時就會把映射文件也拷貝過去了。
pom.xml
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> <!-- 打包時拷貝MyBatis的映射文件 --> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/sqlmap/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.*</include> </includes> <filtering>true</filtering> </resource> </resources> </build>
1. 右鍵項目 -> Run as -> Maven install,開始執行Maven構建,第一次會下載Maven依賴,可能須要點時間,若是出現以下信息,就說明項目編譯打包成功了。
2. 右鍵文件 DemoApplication.java -> Run as -> Java Application,開始啓動應用,當出現以下信息的時候,就說明應用啓動成功了,默認啓動端口是8080。
3. 打開瀏覽器,訪問:http://localhost:8080/swagger-ui.html,進入swagger接口文檔界面。
4. 分別測試findAll和findUserById接口,若是能正常返回數據,就說明MyBatis已經能夠正常使用了。
findAll接口
findUserById接口
JDBC有點原始,ORM封裝度高。
Hibernate操做對象,MyBatis語句靈活。
二者各有利弊,根據條件選擇。
徹底對象選前者,靈活控制選後者。
MyBatis 官網:http://www.mybatis.org/mybatis-3/zh/index.html
MyBatis Generator 官網:http://www.mybatis.org/generator/index.html
MyBatis Plus 官網: http://mp.baomidou.com/#/quick-start
碼雲:https://gitee.com/liuge1988/spring-boot-demo.git
做者:朝雨憶輕塵
出處:https://www.cnblogs.com/xifengxiaoma/
版權全部,歡迎轉載,轉載請註明原文做者及出處。