详解Spring boot + Mybatis整合及遇到的坑

刚开始接触Spring boot,就爱上它了,并且一发不可收拾,下面是我研究了一下午的成果,分享给大家的同时,也留份笔记

首先,在pom.xml中,导包

<!--包含了大量配置好的依赖管理,在自己项目添加这些依赖的时候不需要写<version>版本号-->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.4.7.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.7</java.version>
		<mybatis.version>3.3.0</mybatis.version>
		<mybatis-spring.version>1.3.0</mybatis-spring.version>
	</properties>
	<!--要实现web功能,所以添加的是这个依赖-->
	<dependencies>
		<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>

		<!--Spring-Loaded项目提供了强大的热部署功能,添加/删除/修改 方法/字段/接口/枚举 等代码的时候都可以热部署,速度很快,很方便。-->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>springloaded</artifactId>
			<version>1.2.5.RELEASE</version>
		</dependency>
		<!--配置druid数据源-->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.0.5</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.0</version>
		</dependency>
	</dependencies>
	<!--该插件支持多种功能,常用的有两种,第一种是打包项目为可执行的jar包。

	在项目根目录下执行mvn package将会生成一个可执行的jar包,jar包中包含了所有依赖的jar包,
	只需要这一个jar包就可以运行程序,使用起来很方便。该命令执行后还会保留一个XXX.jar.original的jar包,
	包含了项目中单独的部分。

	生成这个可执行的jar包后,在命令行执行java -jar xxxx.jar即可启动项目。

	另外一个命令就是mvn spring-boot:run,可以直接使用tomcat(默认)启动项目。
-->
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
其中包括了spring boot 所需要的web应用包及mysql的驱动包,mybatis的框架包等;

其次,在配置文件application.yml中,需要配置以下服务器信息及数据源信息和xml文件信息

server:
  port: 8080
  context-path: /a
spring:
    datasource:
        name: moshao
        url: jdbc:mysql://127.0.0.1:3306/moshao
        username: root
        password: 1314
        # 使用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:
  mapperLocations: classpath*:mapper/*.xml
  type-aliases-package: com.weiye.entity
后面的跟spring+mybatis都差不多了,直接贴代码

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="com.weiye.demo.LiuMapper">

    <sql id="selectId">
        id,
        name,
        age

    </sql>

    <!-- 查询条件分页查询 -->
    <select id="findByPage" resultType="com.weiye.entity.Liu">
        select
        <include refid="selectId" />
        from liu
        where 1 = 1
        <if test="id != null and id != ''">
            and id = ${id}
        </if>
        <if test="name != null and name != ''">
            and rule_name = '${name}'
        </if>
        <if test="age != null and age != ''">
            and age=${age}
        </if>
    </select>

    <select id="findById" parameterType="java.lang.Integer" resultType="com.weiye.entity.Liu" >
        SELECT
        <include refid="selectId" />
        from liu where id=${id};
    </select>

    <delete id="delById" parameterType="java.lang.Integer">
        delete from liu where id=${id};
    </delete>

    <update id="updateById" parameterType="java.lang.Integer">
        UPDATE from liu set
        <if test="name !=null and name !=''">
           name="${name}",
        </if>
        <if test="age !=null and age != ''">
          age = ${age}
        </if>
        where id = ${id}
    </update>

    <insert id="insertLiu" parameterType="com.weiye.entity.Liu">
        insert liu(name,age) values("${name}",${age});
    </insert>
</mapper>
class实体类

package com.weiye.entity;

import java.io.Serializable;

public class Liu implements Serializable {
    private static final long serialVersionUID = 8809101560720973267L;
    private int id;
    private  String name;
    private  int age;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Liu{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
下面是mapper接口文件,在这里,上面需要使用@Mapper注解

LiuMapper.java

package com.weiye.demo;

import com.weiye.entity.Liu;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;
@Mapper
public interface LiuMapper {
    //根据对象属性查找,动态查询
    List<Liu> findByPage(Liu liu);
    //根据id查询
    Liu findById(Integer id);

    //更新数据
    int updateById(Integer id);

    //插入数据
    int insertLiu(Liu liu);

    //删除数据
    int delById(Integer id);
}
最后是控制器类:

DemoController.java

 
 
package com.weiye.demo;

import com.weiye.entity.Liu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class DemoController {
    @Autowired
    private LiuMapper liuMapper;

    @ResponseBody
    @RequestMapping(value = "/findByPage",method = RequestMethod.POST)
    public List<Liu> findByPage() {
        System.out.print("hehe,执行了!!");
        Liu liu = new Liu();
        liu.setId(1);
        List<Liu> list = liuMapper.findByPage(liu);
        return list;
    }
}

到这里,一套完整的小demo就完成了,在做项目的时候遇到的一些坑,在这里分享以下:
LiuMapper.java接口,一定要跟项目的main方法入口在同一个文件夹,或者在其子文件夹,这样才可以找到并注入bean,否则,使用@Autowired注解也不注入bean,可以通过配置其他配置文件指定路径,不过笔者也是刚接触spring boot,所以再次就不赘述了,以上就是我的心得!!


猜你喜欢

转载自blog.csdn.net/qq_34545939/article/details/79047168