Spring Boot對於MyBatis的支持須要引入mybatis-spring-boot-starter的pom文件。html
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency>
在加添MySQL等相關依賴後,完整的pom.xml:前端
<?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> <groupId>com.louis</groupId> <artifactId>kitty-admin</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>kitty-admin</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <mybatis.spring.version>1.3.2</mybatis.spring.version> </properties> <dependencies> <!-- spring boot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis.spring.version}</version> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
1.添加MyBatis配置java
添加MyBatis配置類,配置相關掃描路徑,包括DAO,Model,XML映射文件的掃描。mysql
新建com.louis.kitty.admin.config包,並建立一個MyBatis配置類,MybatisConfig.java。git
package com.louis.kitty.admin.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.kitty.**.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.kitty.**.model"); // 掃描Model PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); sessionFactory.setMapperLocations(resolver.getResources("classpath*:**/sqlmap/*.xml")); // 掃描映射文件 return sessionFactory.getObject(); } }
2.添加數據源配置web
打開 application.yml ,添加MySQL數據源鏈接信息。spring
server: port: 8088 spring: datasource: driverClassName: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/mango?useUnicode=true&zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=utf-8 username: root password: 123456
因爲手動編寫MyBatis的Model、DAO、XML映射文件比較繁瑣,一般都會經過一些生成工具來生成。MyBatis官方也提供了生成工具(MyBaits Generator),另外還有一些基於官方基礎上改進的第三方工具,好比MyBatis Plus就是國內提供的一款很是優秀的開源工具,網上相關教程比較多,這裏就再也不贅述了。sql
這裏提供一些資料做爲參考。apache
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
代碼生成好以後,分別將Domain、DAO、XML映射文件拷貝到相應的包裏。
打開Mapper,咱們看到MyBatis Generator給咱們默認生成了一些增刪改查的方法。
package com.louis.kitty.admin.dao; import com.louis.kitty.admin.model.SysUser; public interface SysUserMapper { int deleteByPrimaryKey(Long userId); int insert(SysUser record); int insertSelective(SysUser record); SysUser selectByPrimaryKey(Long userId); int updateByPrimaryKeySelective(SysUser record); int updateByPrimaryKey(SysUser record); }
向 SysUserMapper 類中新一個 selectAll 方法,用於查詢全部的用戶信息。
package com.louis.kitty.admin.dao; import java.util.List; import com.louis.kitty.admin.model.SysUser; public interface SysUserMapper { int deleteByPrimaryKey(Long userId); int insert(SysUser record); int insertSelective(SysUser record); SysUser selectByPrimaryKey(Long userId); int updateByPrimaryKeySelective(SysUser record); int updateByPrimaryKey(SysUser record); /** * 查詢所有 * @return */ List<SysUser> selectAll(); }
向 SysUserMapper.xml 中加入 selectAll 的查詢語句。
<select id="selectAll" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from sys_user </select>
編寫 SysUserService 接口,包含 selectAll 和 findByUserId 兩個方法。
package com.louis.kitty.admin.sevice; import java.util.List; import com.louis.kitty.admin.model.SysUser; public interface SysUserService { /** * 根據用戶ID查找用戶 * @param userId * @return */ SysUser findByUserId(Long userId); /** * 查找全部用戶 * @return */ List<SysUser> findAll(); }
編寫 SysUserServiceImpl 實現類,調用 SysUserMapper 方法完成查詢操做。
package com.louis.kitty.admin.sevice.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.louis.kitty.admin.dao.SysUserMapper; import com.louis.kitty.admin.model.SysUser; import com.louis.kitty.admin.sevice.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(); } }
編寫 SysUserController restful 接口,返回JSON數據格式,提供外部調用。
package com.louis.kitty.admin.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.kitty.admin.sevice.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 標籤的打包配置,這樣代碼打包時就會把映射文件也拷貝過去了。
<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>
編譯啓動,分別訪問: http://localhost:8088/user/findAll, http://localhost:8088/user/findByUserId?userId=1,都能看到結果正常返回。
http://localhost:8088/user/findByUserId?userId=1
http://localhost:8088/user/findAll
後端:https://gitee.com/liuge1988/kitty
前端:https://gitee.com/liuge1988/kitty-ui.git
做者:朝雨憶輕塵
出處:https://www.cnblogs.com/xifengxiaoma/ 版權全部,歡迎轉載,轉載請註明原文做者及出處。