SpringBoot入門——整合Mybatis

                                    

做APP,小程式就上開源眾包。世界盃期間免費領2600元啟動金。
>>>
  

SpringBoot入門——整合Mybatis

        springboot整合mybatis,只需要簡單的配置就能整合在一起,這裡寫了個查詢和插入小例子來演示如何呼叫mybatis。

1、配置pom.xml

先配置pom.xml,來引用spring和mybatis相關的jar包

<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.springboot</groupId>
	<artifactId>spring-boot2</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>springboot</name>
	<url>http://maven.apache.org</url>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.4.RELEASE</version>
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8</java.version>
		<!-- 管理jar包的版本號 -->
		<mybatis-spring.version>1.3.0</mybatis-spring.version>
		<mybatis-autoconfigure.version>1.3.0</mybatis-autoconfigure.version>
	</properties>

	<dependencies>
		<!-- web支援 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<!-- Springboot devtools熱部署 依賴包 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional>
			<scope>true</scope>
		</dependency>

		<!-- mybatis-spring依賴,包含mybatis和mybatis-spring等 -->
		<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>
				<configuration>
					<!-- 如果沒有該項配置,devtools不會起作用,即應用不會restart -->
					<fork>true</fork>
				</configuration>
			</plugin>
		</plugins>
	</build>


</project>

2、建立mapper檔案存放資料夾mapper

該資料夾用來放mybatis的mapper檔案

3、建立mapper類及配置

(1)、建立mapper的介面類

有兩種方式寫Sql語句,一種是基於xml檔案,另一種是基於註解,想詳細瞭解請自行百度

包名:com.springboot.dao

類名:AdminDAO 

package com.springboot.dao;

import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface AdminDAO {

	// 基於Mapper.xml寫sql語句
	public List<Map<String, Object>> selectAll();

	// 基於註解方式寫sql語句
	@Insert("insert into account(name,money) values(#{name},#{money})")
	int addAdmin(@Param("name") String name, @Param("money") String money);

}

(2)、建立mapper的配置類

建立此配置類的作用是在以後分散式搭建的時候,可以掃描每塊mapper的包的位置

並且在加上此配置類後mapper類不加@Mapper註解也可以,只需此配置類中設定好mapper的包的位置

包名:com.springboot.dao;

類名:MapperConfig

package com.springboot.dao;


import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;
/**
 * 
 * 掃描本包的mapper
 *
 */
@Configuration
@MapperScan("com.springboot.dao")
public class MapperConfig {

}

4、建立實體類

包名:com.springboot.entity;

類名:Admin

package com.springboot.entity;

public class Admin {
	private Integer id;
	private String name;
	private String money;
	
	public Admin() {}

	public Admin(Integer id, String name, String money) {
		super();
		this.id = id;
		this.name = name;
		this.money = money;
	}

	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 String getMoney() {
		return money;
	}

	public void setMoney(String money) {
		this.money = money;
	}
	
}

5、配置application.properties

只需要簡單的幾個配置就能行,如果需要配置其他引數,請自行查詢相關資料

# 資料庫連線
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mysql?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

# 連線池配置
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5

# mybatis配置
# mybatis對映檔案位置
mybatis.mapper-locations=classpath:/mapper/*Mapper.xml 
# 實體類entity包位置
mybatis.type-aliases-package=com.springboot.entity

6、編寫Mapper檔案

編寫mapper.xml,放入剛才建立的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">

<!-- namespace必須指向Dao介面 -->
<mapper namespace="com.springboot.dao.AdminDAO">

    <!-- 根據ID查詢資料 -->
    <select id="selectAll" resultType="map">
   		select
   		      *
   		from
   			account
    </select>

</mapper>

7、編寫service

寫對應的service業務處理層

(1)、service介面類:

包名:com.springboot.service

類名:AdminService

package com.springboot.service;

import java.util.List;
import java.util.Map;
//service介面類
public interface AdminService {
	
	public List<Map<String,Object>> findAll();
	
	public int addAdmin(String name,String money);
}

(2)、service實現類

包名:com.springboot.service.impl

類名:AdminServiceImpl

package com.springboot.service.impl;

import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.springboot.dao.AdminDAO;
import com.springboot.service.AdminService;

@Service
//service介面的實現類
public class AdminServiceImpl implements AdminService{
	
	@Autowired
	private AdminDAO adminDAO;
	
    // 查詢方法
	public List<Map<String, Object>> findAll() {
		return adminDAO.selectAll();
	}
    
    // 插入方法
	public int addAdmin(String name, String money) {
		return adminDAO.addAdmin(name, money);
	}

}

8、編寫controller類

包名:com.springboot.controller

類名:AdminController

package com.springboot.controller;

import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.springboot.service.AdminService;

@Controller
public class AdminController {
	@Autowired
	private AdminService adminService;

    // 查詢controller
	@RequestMapping("/admin")
	@ResponseBody
	public List<Map<String, Object>> test(){
		return adminService.findAll();
	}
	
    // 插入controller
	@RequestMapping("/addAdmin")
	@ResponseBody
	public int addAdmin(@RequestParam("name") String name,@RequestParam("money") String money){
		return adminService.addAdmin(name, money);
	}
	
}

9、編寫Main類

用來啟動springboot的main類

包名:com.springboot

類名:ApplicationMain

package com.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

@SpringBootApplication
@EnableConfigurationProperties
public class ApplicationMain {

	public static void main(String[] args) {
		SpringApplication.run(ApplicationMain.class, args);
		System.out.println("---------------OK----------------");
	}

}

10、測試

測試1:

輸入地址:http://localhost:8080/admin

如果顯示一序列json資訊則查詢成功

測試2:

輸入地址:http://localhost:8080/addAdmin?name=test&money=666

如果顯示1,則代表插入一條記錄成功

再輸入:http://localhost:8080/admin

來查詢剛才插入的內容


(adsbygoogle = window.adsbygoogle || []).push({});

function googleAdJSAtOnload() {
var element = document.createElement(“script”);
element.src = “//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js”;
element.async = true;
document.body.appendChild(element);
}
if (window.addEventListener) {
window.addEventListener(“load”, googleAdJSAtOnload, false);
} else if (window.attachEvent) {
window.attachEvent(“onload”, googleAdJSAtOnload);
} else {
window.onload = googleAdJSAtOnload;
}