SpringBoot整合mybatis

2019-03-15  本文已影响0人  树蜂

关于自动生成mapper文件,可通过笔者的另一篇文章《SpringBoot使用mybatis generator自动生成代码》查看

文章目录
1、项目结构
2、数据库结构
3、依赖
4、yml配置
5、源码
6、mapper文件
7、效果
8、druid的简单实用
9、参考


1、项目结构

目录结构

2、数据库结构

数据库结构

3、依赖

<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>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
         
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.9</version>
        </dependency>
        
    </dependencies>

4、yml配置

关于yml文件

application-dev.yml:开发环境
application-test.yml:测试环境
application-prod.yml:生产环境
至于哪个具体的配置文件会被加载,需要在application.yml文件中通过spring.profiles.active属性来设置,其值对应{profile}值。

application.yml

spring:
  profiles:
    active: dev

application-dev.yml

server:
  port: 8080
 
spring:
  datasource:
    #mysql驱动
    driver-class-name: com.mysql.jdbc.Driver
    #基本属性
    url: jdbc:mysql://localhost:3306/mybatis_test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC&allowMultiQueries=true
    username: root
    password: root
    #druid相关配置
    druid:
      #监控统计拦截的filters
#      filter: stat
      #配置初始化大小/最小/最大
      initial-size: 1
      min-idle: 1
      max-active: 20
      #获取连接等待超时时间
      max-wait: 60000
      #间隔多久进行一次检测,检测需要关闭的空闲连接
      time-between-eviction-runs-millis: 60000

mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml
#  type-aliases-package: com.shufeng.hellomybatis.entity
 
#showSql
logging:
  level:
    com:
      example:
        mapper : debug

要注意修改为自己数据库的名称、账户及密码

5、源码

User.java

public class User {
    private Integer id;

    private String userName;

    private String password;

    private Integer age;
    // 省略getter和setter
}

UserDao.java

import org.apache.ibatis.annotations.Mapper;

import com.shufeng.hellomybatis.entity.User;

@Mapper
public interface UserDao {
    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
}

可在UserDao 添加@Mapper或者在Application添加@MapperScan("com.shufeng.hellomybatis.dao"),从而使 UserDao 与后续的UserMapper.xml匹配。
但仅需使用一种。

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

@SpringBootApplication
//@MapperScan("com.shufeng.hellomybatis.dao")
public class Application {

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

UserService.java

import com.shufeng.hellomybatis.entity.User;
 
public interface UserService {
    public User getUserById(int userId);

    boolean addUser(User record);

}

UserServiceImpl.java

import org.springframework.stereotype.Service;

import com.shufeng.hellomybatis.dao.UserDao;
import com.shufeng.hellomybatis.entity.User;

import javax.annotation.Resource;

@Service("userService")
public class UserServiceImpl implements UserService
{

    @Resource
    private UserDao userDao;

    public User getUserById(int userId)
    {
        return userDao.selectByPrimaryKey(userId);
    }

    public boolean addUser(User record)
    {
        boolean result = false;
        try
        {
            userDao.insertSelective(record);
            result = true;
        } catch (Exception e)
        {
            e.printStackTrace();
        }

        return result;
    }

}

UserController.java

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.shufeng.hellomybatis.entity.User;
import com.shufeng.hellomybatis.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @RequestMapping("/showUser")
    @ResponseBody
    public User toIndex(HttpServletRequest request, Model model){
        int userId = Integer.parseInt(request.getParameter("id"));
        User user = this.userService.getUserById(userId);
        return user;
    }
}

6、mapper文件

image.png

注意:

1、UserMapper.xml 文件的位置要与yml配置文件的位置mapper-locations: classpath:mapper/*Mapper.xml一致
2、UserMapper.xml 文件中的namespacetype的值要改为与自己项目相同

<?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.shufeng.hellomybatis.dao.UserDao" >

    <resultMap id="BaseResultMap" type="com.shufeng.hellomybatis.entity.User" >
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="user_name" property="userName" jdbcType="VARCHAR" />
        <result column="password" property="password" jdbcType="VARCHAR" />
        <result column="age" property="age" jdbcType="INTEGER" />
    </resultMap>
    
    <sql id="Base_Column_List" >
        id, user_name, password, age
    </sql>
    
    <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
        select
        <include refid="Base_Column_List" />
        from user_t
        where id = #{id,jdbcType=INTEGER}
    </select>
    
    <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
        delete from user_t
        where id = #{id,jdbcType=INTEGER}
    </delete>
    
    <insert id="insert" parameterType="com.shufeng.hellomybatis.entity.User" >
        insert into user_t (id, user_name, password,
        age)
        values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
        #{age,jdbcType=INTEGER})
    </insert>
    
    <insert id="insertSelective" parameterType="com.shufeng.hellomybatis.entity.User" >
        insert into user_t
        <trim prefix="(" suffix=")" suffixOverrides="," >
            <if test="id != null" >
                id,
            </if>
            <if test="userName != null" >
                user_name,
            </if>
            <if test="password != null" >
                password,
            </if>
            <if test="age != null" >
                age,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides="," >
            <if test="id != null" >
                #{id,jdbcType=INTEGER},
            </if>
            <if test="userName != null" >
                #{userName,jdbcType=VARCHAR},
            </if>
            <if test="password != null" >
                #{password,jdbcType=VARCHAR},
            </if>
            <if test="age != null" >
                #{age,jdbcType=INTEGER},
            </if>
        </trim>
    </insert>
    
    <update id="updateByPrimaryKeySelective" parameterType="com.shufeng.hellomybatis.entity.User" >
        update user_t
        <set >
            <if test="userName != null" >
                user_name = #{userName,jdbcType=VARCHAR},
            </if>
            <if test="password != null" >
                password = #{password,jdbcType=VARCHAR},
            </if>
            <if test="age != null" >
                age = #{age,jdbcType=INTEGER},
            </if>
        </set>
        where id = #{id,jdbcType=INTEGER}
    </update>
    
    <update id="updateByPrimaryKey" parameterType="com.shufeng.hellomybatis.entity.User" >
        update user_t
        set user_name = #{userName,jdbcType=VARCHAR},
        password = #{password,jdbcType=VARCHAR},
        age = #{age,jdbcType=INTEGER}
        where id = #{id,jdbcType=INTEGER}
    </update>
</mapper>

7、效果

浏览器访问 http://localhost:8080/user/showUser?id=1

image.png

8、druid的简单实用

可通过druid方便的监控服务器性能,从而进行调优。
添加配置DruidConfig.java

import javax.sql.DataSource;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

@Configuration
public class DruidConfig {
    @Bean
    public ServletRegistrationBean druidServlet() { // 主要实现WEB监控的配置处理
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*"); // 进行druid监控的配置处理操作
        servletRegistrationBean.addInitParameter("allow",
                "127.0.0.1,192.168.1.159"); // 白名单
        servletRegistrationBean.addInitParameter("deny", "192.168.1.200"); // 黑名单
        servletRegistrationBean.addInitParameter("loginUsername", "stat"); // 用户名
        servletRegistrationBean.addInitParameter("loginPassword", "Wkt_sTat_1031"); // 密码
        servletRegistrationBean.addInitParameter("resetEnable", "false"); // 是否可以重置数据源
        return servletRegistrationBean ;
    }
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean() ;
        filterRegistrationBean.setFilter(new WebStatFilter());

        filterRegistrationBean.addUrlPatterns("/*"); // 所有请求进行监控处理
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.css,/druid/*");
        return filterRegistrationBean ;
    }
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }
}

访问 http://localhost:8080/druid
账号、密码在配置文件中

image.png
可方便的查看各种性能指标,这里不做展开。
image.png

9、参考

spring boot+mybatis整合
SpringBoot整合Mybatis完整详细版
单手撸了个springboot+mybatis+druid

上一篇下一篇

猜你喜欢

热点阅读