springboot整合mybatis、Druid、mysql

2019-11-17  本文已影响0人  守望者_0173

最近三个多月,利用空闲时间自学java,利用周日休息,心血来潮,做了一个简单项目案例。项目主要用到了springboot、mybatis、druid、mysql技术。废话不多说了,先把建项目过程,贴出来。

新建工程

create_project_1.png
create_project_2.png
create_project_3.png
create_project_4.png
create_project_5.png
create_project_6.png

点击完成按钮,会生成examedemo项目,目录结构如下图所示:


image.png
image.png

新建application.yml文件

application.yml文件配置项


server:
  port: 8082
  undertow:
    io-threads: 15

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/zhixiaole_test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false
    username: root
    password: root
  druid:
    #监控统计拦截的过滤器 不加监控界面sql无法统计 wall用于防火墙
    filters: stat,wall,log4j,config
    #最大连接数
    max-active: 100
    #初始化大小
    initial-size: 1
    #获取连接最大等待时间
    max-wait: 60000
    min-idle: 1
    #间隔多久检测一次需要关闭的空闲连接 毫秒
    time-between-eviction-runs-millis: 60000
    #连接在连接池中最小生存的时间,毫秒
    min-evictable-idle-time-millis: 300000
    validation-query: select 'x'
    test-while-idle: true
    test-on-borrow: false
    test-on-return: false
    pool-prepared-statements: true
    max-open-prepared-statements: 50
    max-pool-prepared-statement-per-connection-size: 20
    web-stat-filter:
      exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
      url-pattern: /*
    stat-view-servlet:
      #白名单IP
      allow: 127.0.0.1
      #黑名单IP
      deny: 120.77.85.84
      #登录账号和密码
      login-username: admin
      login-password: admin
      #启用重置数据功能
      reset-enable: true

  thymeleaf:
    prefix: classpath:/templates/
    mode: HTML
    encoding: utf-8
    content-type: text/html
    cache: false


mybatis:
  config-location: classpath:/mybatis/mybatis.cfg.xml
  type-aliases-package: com.examedemo.exame.model
  mapper-locations: classpath*:/mybatis/mapper/*Mapper.xml
#  configuration:
#    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
logging:
  level:
    com.examedemo.exame.mapper : debug

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.examedemo</groupId>
    <artifactId>exame</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>exame</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </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>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
<!--        &lt;!&ndash;自启动Druid管理后台&ndash;&gt;-->
<!--        <dependency>-->
<!--            <groupId>com.alibaba</groupId>-->
<!--            <artifactId>druid-spring-boot-starter</artifactId>-->
<!--            <version>1.1.10</version>-->
<!--        </dependency>-->

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>

    </dependencies>

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

</project>

mybatis.cfg.xml配置文件代码

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 进行Mybatis的相应的环境的属性定义 -->
    <settings>    <!-- 在本项目之中开启二级缓存 -->
        <setting name="cacheEnabled" value="true"/>
    </settings>
</configuration>

user_weixin

表结构如下

-- ----------------------------
-- Table structure for user_weixin
-- ----------------------------
DROP TABLE IF EXISTS `user_weixin`;
CREATE TABLE `user_weixin` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `userid` int(11) DEFAULT NULL COMMENT '用户id(只有填写基本资料后才会创建)',
  `nickname` varchar(100) DEFAULT NULL COMMENT '昵称',
  `openid` varchar(100) DEFAULT NULL COMMENT '微信OpenID',
  `unionid` varchar(50) DEFAULT NULL COMMENT 'unionId',
  `sex` int(11) DEFAULT NULL COMMENT '性别',
  `city` varchar(20) DEFAULT NULL COMMENT '所在城市',
  `province` varchar(20) DEFAULT NULL COMMENT '所在省份',
  `country` varchar(20) DEFAULT NULL COMMENT '所在国家',
  `avatar_url` varchar(200) DEFAULT NULL COMMENT '用户头像',
  `reg_time` datetime DEFAULT NULL COMMENT '注册时间',
  `mobile` varchar(12) DEFAULT NULL,
  `snsid` int(11) DEFAULT '0' COMMENT 'bbs系统用户编号',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=244 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='微信用户表';

IUserWeixinMapper.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.examedemo.exame.mapper.IUserWeixinMapper">

    <resultMap id="BaseResultMap" type="com.examedemo.exame.model.UserWeixinModel">
        <result column="id" jdbcType="INTEGER" property="id" />
        <result column="userid" jdbcType="INTEGER" property="userid" />
<!--        <result column="passWord" jdbcType="VARCHAR" property="passWord" />-->
<!--        <result column="realName" jdbcType="VARCHAR" property="realName" />-->
    </resultMap>

    <select id="findAll" resultType="com.examedemo.exame.model.UserWeixinModel">
        SELECT * FROM user_weixin order  by id desc limit 10;
    </select>
</mapper>

ExameApplication.java

package com.examedemo.exame;

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

@SpringBootApplication
@MapperScan(basePackages = "com.examedemo.exame.mapper")
public class ExameApplication {

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

}

DruidConfig.java

package com.examedemo.exame.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.beans.factory.annotation.Value;
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 javax.sql.DataSource;
import java.sql.SQLException;


@Configuration
public class DruidConfig {

    @Bean
    public ServletRegistrationBean druidServlet(){
        ServletRegistrationBean reg = new ServletRegistrationBean();
        reg.setServlet(new StatViewServlet());
        reg.addUrlMappings("/druid/*");
        reg.addInitParameter("allow", "127.0.0.1");
        reg.addInitParameter("deny","");
        reg.addInitParameter("loginUsername", "admin");
        reg.addInitParameter("loginPassword", "admin");
        return reg;
    }



    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }

    @Bean(name="dataSource")
    public DataSource druidDataSource(
            @Value("${spring.datasource.driver-class-name}") String driver,
            @Value("${spring.datasource.url}") String url,
            @Value("${spring.datasource.username}") String username,
            @Value("${spring.datasource.password}") String password) {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driver);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        try {
            druidDataSource.setFilters("stat, wall");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return druidDataSource;
    }
}

IndexController.java

package com.examedemo.exame.controllers.admin;

import com.examedemo.exame.model.UserWeixinModel;
import com.examedemo.exame.service.impl.UserWeixinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class IndexController {

    @Autowired
    private UserWeixinService userWeixinService;

    @RequestMapping(value = "/index",method = RequestMethod.GET)
    @ResponseBody
    public String index(){
        return "hello world";
    }


    @ResponseBody
    @RequestMapping(value = "/users",method = RequestMethod.GET)
    public List<UserWeixinModel> users(){
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("content-type","application/json");
        return userWeixinService.getList();
    }
}

IUserWeixinMapper.java

package com.examedemo.exame.mapper;


import com.examedemo.exame.model.UserWeixinModel;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;


public interface IUserWeixinMapper {

    public List<UserWeixinModel> findAll();
}

UserWeixinModel.java

package com.examedemo.exame.model;

import java.io.Serializable;

public class UserWeixinModel implements Serializable {
    private Integer id;
    private Integer userid;
    private String nickname;
    private String openid;
    private Integer sex;
    private String city;
    private String province;
    private String country;
    private String avatarUrl;
    private String regTime;
    private String mobile;
    private Integer snsid;

    public Integer getId() {
        return id;
    }

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

    public Integer getUserid() {
        return userid;
    }

    public void setUserid(Integer userid) {
        this.userid = userid;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getOpenid() {
        return openid;
    }

    public void setOpenid(String openid) {
        this.openid = openid;
    }

    public long getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getAvatarUrl() {
        return avatarUrl;
    }

    public void setAvatarUrl(String avatarUrl) {
        this.avatarUrl = avatarUrl;
    }

    public String getRegTime() {
        return regTime;
    }

    public void setRegTime(String regTime) {
        this.regTime = regTime;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public Integer getSnsid() {
        return snsid;
    }

    public void setSnsid(Integer snsid) {
        this.snsid = snsid;
    }
}

IUserWeixinService.java

package com.examedemo.exame.service;

import com.examedemo.exame.model.UserWeixinModel;

import java.util.List;

public interface IUserWeixinService {

    public List<UserWeixinModel> getList();
}

UserWeixinService.java

package com.examedemo.exame.service.impl;

import com.examedemo.exame.mapper.IUserWeixinMapper;
import com.examedemo.exame.model.UserWeixinModel;
import com.examedemo.exame.service.IUserWeixinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserWeixinService implements IUserWeixinService {

    @Autowired
    private  IUserWeixinMapper userWeixinMapper;

    public List<UserWeixinModel> getList(){
        return userWeixinMapper.findAll();
    }
}

上一篇下一篇

猜你喜欢

热点阅读