1. 程式人生 > >springboot 學習之整合mybatis

springboot 學習之整合mybatis

1、前言

spring data jpa針對單獨的表使用註解開發比較簡單,筆者一直以為mybatis才是持久層正確的開啟方式大笑。下面整理一下springboot整合mybatis。

2、開發準備

引入依賴:(也可以使用外掛直接選擇)

<!-- mybtais 整合依賴 -->
<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>1.3.2</version>
</dependency>
<!-- 資料庫驅動 -->
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<scope>runtime</scope>
</dependency>

3、yml配置

# server
server:
  port: 8081
  servlet:
    context-path: /boot
 
# database
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/test
    driver-class-name:  com.mysql.jdbc.Driver
    username: root
    password: root

# mybatis
mybatis:
  config-location: classpath:templates/mybatis/mybatis-config.xml  #mybatis配置,駝峰匹配、列印SQL等
  mapper-locations: classpath:templates/mybatis/mapper/*.xml       #SQL查詢檔案
  type-aliases-package: ws.simonking.springboot.mybatis.model      #別名掃描包

4、mapper.xml的配置

<?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="ws.simonking.springboot.mybatis.mapper.UserInfoMapper" >
  <!-- 這裡配置了resultMap,資料庫欄位和屬性一一對應就不用開啟駝峰匹配了 -->
  <resultMap id="BaseResultMap" type="ws.simonking.springboot.mybatis.model.UserInfo" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="age" property="age" jdbcType="INTEGER" />
    <result column="sex" property="sex" jdbcType="VARCHAR" />
    <result column="job" property="job" jdbcType="VARCHAR" />
    <result column="birthday" property="birthday" jdbcType="TIMESTAMP" />
    <result column="created_time" property="createdTime" jdbcType="TIMESTAMP" />
    <result column="update_time" property="updateTime" jdbcType="TIMESTAMP" />
  </resultMap>
  
  <sql id="Base_Column_List" >
    id, `name`, age, sex, job, birthday, created_time, update_time
  </sql>
  <select id="getUserInfoById" resultMap="BaseResultMap" parameterType="java.lang.Integer">
  	select
  	<include refid="Base_Column_List" />
  	from user_info
  	where id = #{id}
  </select>
</mapper>

5、mapper

public interface UserInfoMapper{
	UserInfo getUserInfoById(Integer id);
}

注意:有些技術文件使用單獨的註解@Mapper或者@Repository。直接將UserInfoMapper標註為mapper介面。但是筆者使用後項目報錯,無法啟動。筆者採用的而是使用介面掃描的方式初始化Mapper的(加在啟動方法上)。

6、啟動方法修改

@SpringBootApplication
@MapperScan("ws.simonking.springboot.mybatis.mapper") // 新增介面掃描,註冊mapper
public class SpringbootMybatisApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringbootMybatisApplication.class, args);
	}
}

7、啟動

訪問測試即可成功!