Spring boot+mybatis整合

本項目使用的環境:

  • 開發工具:Intellij IDEA 2017.2.6
  • jdk:1.8.0_131
  • maven:3.3.9

額外功能

  • PageHelper 分頁插件
步驟: 

1.創建一個springboot項目: 


2.創建項目的文件結構以及jdk的版本 


3.選擇項目所需要的依賴 



    然後點擊finish,刪除一些不需要的文件。

    

5.看一下文件的結構: 


6.查看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.crest</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.10.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>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<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>1.3.1</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>
		</dependency>

		<!-- alibaba的druid數據庫連接池 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
			<version>1.1.0</version>
		</dependency>
		<!-- 分頁插件 -->
		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper-spring-boot-starter</artifactId>
			<version>1.1.2</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>
7.項目不使用application.properties文件 而使用更加簡潔的application.yml文件: 
將原有的resource文件夾下的application.properties直接改成application.yml配置文件, 

文件的內容如下:

server:
  port: 8080

spring:
    datasource:
        url: jdbc:mysql://127.0.0.1:3306/webchat
        username: root
        password: 151862
        # 使用druid數據源
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        filters: stat
        maxActive: 20
        initialSize: 1
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20
mybatis:
  #掃描mapping
  mapper-locations: classpath:mapping/*.xml
  #掃描實體類
  type-aliases-package: com.crest.xm.model

#pagehelper分頁插件
pagehelper:
    helperDialect: mysql
    reasonable: true
    supportMethodsArguments: true
    params: count=countSql

8.接下來創建我們的分層模式

Product.java

package com.crest.demo.model;

import java.io.Serializable;

/**
 * 商品實體類
 */
public class Product implements Serializable {

    private static final long serialVersionUID = 1435515995276255188L;

    private long id;

    private String name;

    private long price;

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public long getPrice() {
        return price;
    }

    public void setPrice(long price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}

ProductMapper.java

package com.crest.demo.mapper;

import com.crest.demo.model.Product;

import java.util.List;
import java.util.Map;

public interface ProductMapper {

    /**
     * 插入商品
     * @param product
     * @return Product
     */
    public abstract int insert(Product product);

    /**
     * 刪除商品信息
     * @param param
     * @return int
     */
    public  abstract int delete(Map<String,Object> param);

    /**
     * 更新商品信息
     * @param product
     * @return int
     */
    public abstract int update (Product product);

    /**
     * 獲取單個商品
     * @param param
     * @return Product
     */
    public abstract Product get(Map<String,Object> param);

    /**
     * 獲取商品列表
     * @param param
     * @return List<Product>
     */
    public abstract List<Product> list(Map<String,Object> param);
}

ProductMapper.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="com.crest.demo.mapper.ProductMapper">
    <resultMap id="BaseResultMap" type="com.crest.demo.model.Product">
        <result column="id" jdbcType="VARCHAR" property="id" />
        <result column="name" jdbcType="VARCHAR" property="name" />
        <result column="price" jdbcType="VARCHAR" property="price" />
    </resultMap>
    <sql id="Example_Where_Clause">
        <where>
            <foreach collection="oredCriteria" item="criteria" separator="or">
                <if test="criteria.valid">
                    <trim prefix="(" prefixOverrides="and" suffix=")">
                        <foreach collection="criteria.criteria" item="criterion">
                            <choose>
                                <when test="criterion.noValue">
                                    and ${criterion.condition}
                                </when>
                                <when test="criterion.singleValue">
                                    and ${criterion.condition} #{criterion.value}
                                </when>
                                <when test="criterion.betweenValue">
                                    and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                                </when>
                                <when test="criterion.listValue">
                                    and ${criterion.condition}
                                    <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                                        #{listItem}
                                    </foreach>
                                </when>
                            </choose>
                        </foreach>
                    </trim>
                </if>
            </foreach>
        </where>
    </sql>
    <sql id="Update_By_Example_Where_Clause">
        <where>
            <foreach collection="example.oredCriteria" item="criteria" separator="or">
                <if test="criteria.valid">
                    <trim prefix="(" prefixOverrides="and" suffix=")">
                        <foreach collection="criteria.criteria" item="criterion">
                            <choose>
                                <when test="criterion.noValue">
                                    and ${criterion.condition}
                                </when>
                                <when test="criterion.singleValue">
                                    and ${criterion.condition} #{criterion.value}
                                </when>
                                <when test="criterion.betweenValue">
                                    and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                                </when>
                                <when test="criterion.listValue">
                                    and ${criterion.condition}
                                    <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                                        #{listItem}
                                    </foreach>
                                </when>
                            </choose>
                        </foreach>
                    </trim>
                </if>
            </foreach>
        </where>
    </sql>
    <sql id="Base_Column_List">
        id,name,price
    </sql>

    <!-- 通過條件獲取單個對象 -->
    <select id="get" parameterType="java.util.Map" resultMap="BaseResultMap">
        select
        <if test="distinct">
            distinct
        </if>
        <include refid="Base_Column_List" />
        from
        product
        where
        id = #{id, jdbcType=VARCHAR}
    </select>

    <!-- 通過條件獲取對象集合 -->
    <select id="list" parameterType="java.util.Map" resultMap="BaseResultMap">
        select
        <if test="distinct">
            distinct
        </if>
        <include refid="Base_Column_List" />
        from
        product
        where
        price = #{price, jdbcType=VARCHAR}
    </select>

    <!-- 插入單個對象 -->
    <insert id="insert" parameterType="com.crest.demo.model.Product">
        insert into product
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">
                id,
            </if>
            <if test="name != null">
                name,
            </if>
            <if test="price != null">
                price,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="id != null">
                #{id,jdbcType=VARCHAR},
            </if>
            <if test="name != null">
                #{name,jdbcType=VARCHAR},
            </if>
            <if test="price != null">
                #{price,jdbcType=VARCHAR},
            </if>
        </trim>
    </insert>
    <!-- 更新單個對象 -->
    <update id="update" parameterType="com.crest.demo.model.Product">
        UPDATE product
        <set>
            <if test="id != null and id != ''">
                id = #{id, jdbcType=VARCHAR},
            </if>
            <if test="name != null and name != ''">
                name = #{name, jdbcType=VARCHAR},
            </if>
            <if test="price != null and price != ''">
                price = #{price, jdbcType=INTEGER},
            </if>
        </set>
        WHERE id = #{id, jdbcType=VARCHAR}
    </update>

    <!-- 刪除用戶 -->
    <delete id="delete" parameterType="java.util.Map">
        DELETE FROM product
        WHERE id = #{id, jdbcType=VARCHAR}
    </delete>
</mapper>

打開類DemoApplication.java,這個是springboot的啓動類。我們需要添加點東西,否則無法找到mapper類:

package com.crest.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.crest.demo.mapper")//將項目中對應的mapper類的路徑加進來就可以了
public class DemoApplication {

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

ProductService.java

package com.crest.demo.service;

import com.crest.demo.model.Product;
import com.github.pagehelper.PageInfo;

import java.util.Map;

public interface ProductService {

    /**
     * 插入商品
     * @param product
     * @return Product
     */
    public abstract int insert(Product product);

    /**
     * 刪除商品信息
     * @param param
     * @return int
     */
    public  abstract int delete(Map<String,Object> param);

    /**
     * 更新商品信息
     * @param product
     * @return int
     */
    public abstract int update (Product product);

    /**
     * 獲取單個商品
     * @param param
     * @return Product
     */
    public abstract Product get(Map<String,Object> param);

    /**
     * 分頁獲取商品列表
     * @param param
     * @return List<Product>
     */
    public abstract PageInfo<Product> list(Map<String,Object> param, int currentPage, int pageSize);
}

ProductServiceImpl.java

package com.crest.demo.service.impl;

import com.crest.demo.mapper.ProductMapper;
import com.crest.demo.model.Product;
import com.crest.demo.service.ProductService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service(value="productService")
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;//這裏會報錯,但是並不會影響

    @Override
    public int insert(Product product) {
        return productMapper.insert(product);
    }

    @Override
    public int delete(Map<String, Object> param) {
        return productMapper.delete(param);
    }

    @Override
    public int update(Product product) {
        return productMapper.update(product);
    }

    @Override
    public Product get(Map<String, Object> param) {
        return productMapper.get(param);
    }

    @Override
    public PageInfo<Product> list(Map<String, Object> param, int currentPage, int pageSize) {
        PageHelper.startPage(currentPage,pageSize);
        List<Product> list=productMapper.list(param);
        PageInfo<Product> pageInfo=new PageInfo<>(list);
        return pageInfo;
    }
}

ProductController.java

package com.crest.demo.controller;

import com.crest.demo.model.Product;
import com.crest.demo.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value="product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @RequestMapping(value = "/find")
    public String findById(String id){
        return "";
    }
}

9.到這裏所有的搭建工作都完成了,接下來就是測試的工作,我們測試service層,controller層等配置完jsp再測試: 

首先看一下完成之後的文件的結構: 


10.編寫測試類

package com.crest.demo;

import com.crest.demo.model.Product;
import com.crest.demo.service.ProductService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.HashMap;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
	@Autowired
	private ProductService productService;

	@Test
	public void find() {
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("id",1);
		Product product=productService.get(map);
		System.out.print(product);
	}

}

控制檯出現信息:



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章