【JavaExample】Springboot&Mybatis&Mysql

序、说明

也没什么好说明的

一、项目创建

1.png
2.png

二、添加常用依赖

  • fastjson
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.62</version>
</dependency>
  • mybatis
<dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>2.1.1</version>
</dependency>
  • mysql驱动
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
 </dependency>

以上三个依赖基本每个项目都会用到,数据库根据情况选择不同的驱动即可。

三、创建项目文件夹结构

  • Config
  • Controller
  • Mapper
  • Model
  • Service
  • ServiceImpl
  • Utils
3.png

四、配置文件初始化

#设置springboot启动端口
server.port=9090

spring.datasource.url=jdbc:mysql://localhost:3306/java_example?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&autoReconnect=true
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.maximum-pool-size=15
spring.datasource.hikari.auto-commit=true
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.pool-name=DatebookHikariCP
spring.datasource.hikari.max-lifetime=1800000
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.connection-test-query=SELECT 1

五、基本必改代码

1、SpringbootApplication扫描Mapper文件夹

@MapperScan("com.javaexample.springboot.Mapper")

package com.javaexample.springboot;

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

@SpringBootApplication
@MapperScan("com.javaexample.springboot.Mapper")
public class SpringbootApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }
}

2、设置跨域

在Config文件夹内新建个CorsConfig类

package com.javaexample.springboot.Config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 1允许任何域名使用
        corsConfiguration.addAllowedHeader("*"); // 2允许任何头
        corsConfiguration.addAllowedMethod("*"); // 3允许任何方法(post、get等)
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}

3、常用Utils类

1)响应工具类:ResponseManager

先创建需要用到的Pojo:ResponsePojo

package com.javaexample.springboot.Model;

import java.util.List;

public class ResponsePojo<T> {
    private int code;
    private String msg;
    private T data;
    private List list;

    public ResponsePojo(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public ResponsePojo(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public ResponsePojo(int code, String msg, List list) {
        this.code = code;
        this.msg = msg;
        this.list = list;
    }

    public ResponsePojo(int code, String msg, T data, List list) {
        this.code = code;
        this.msg = msg;
        this.data = data;
        this.list = list;
    }

    // getter & setter & toString
}

然后创建ResponseManager

package com.javaexample.springboot.Utils;

import com.javaexample.springboot.Model.ResponsePojo;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ResponseManager {
    private static final int OK = 200;
    private static final int ERROR = 400;

    public static ResponsePojo buildSuccess() {
        return new ResponsePojo(OK,"请求成功");
    }

    public static ResponsePojo buildSuccess(String msg) {
        return new ResponsePojo(OK,msg);
    }

    public static <T> ResponsePojo buildSuccess(T data) {
        return new ResponsePojo(OK,"请求成功", data);
    }

    public static ResponsePojo buildSuccess(List list) {
        return new ResponsePojo(OK,"请求成功", list);
    }

    public static <T> ResponsePojo buildSuccess(T data, List list) {
        return new ResponsePojo(OK,"请求成功", data,list);
    }

    public static ResponsePojo buildError() {
        return new ResponsePojo(ERROR,"请求失败");
    }

    public static ResponsePojo buildError(String msg) {
        return new ResponsePojo(ERROR,msg);
    }

    public static ResponsePojo buildError(int code,String msg) {
        return new ResponsePojo(code,msg);
    }

    public static <T> ResponsePojo buildError(int code,String msg,T data) {
        return new ResponsePojo(code,msg,data);
    }
}

使用时就这样

@Autowired
private ResponseManager responseManager;
...
public ResponsePojo xxxx(){
  ...
  return responseManager.buildSuccess();
}

2)强制获取Spring中的组件:SpringManager

当无法通过@Autowired注入时就这样强制获取(个人是这样理解)

package com.javaexample.springboot.Utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringManager implements ApplicationContextAware {
    private static ApplicationContext applicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(SpringManager.applicationContext == null){
            SpringManager.applicationContext  = applicationContext;
        }
    }


    //获取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //通过name获取 Bean.
    public static Object getBean(String name){
        return getApplicationContext().getBean(name);
    }

    //通过class获取Bean.
    public static <T> T getBean(Class<T> clazz){
        return getApplicationContext().getBean(clazz);
    }

    //通过name,以及Clazz返回指定的Bean
    public static <T> T getBean(String name,Class<T> clazz){
        return getApplicationContext().getBean(name, clazz);
    }
}

使用时就这样

private ApplicationContext applicationContext = SpringManager.getApplicationContext();
private AsyncTaskService asyncTaskService = applicationContext.getBean(AsyncTaskService.class);

六、业务代码Example

1、准备工作

此示例基于Mysql数据库,先新建数据库java_example,再初始化表ex_user。

/*
Navicat MySQL Data Transfer

Source Server         : localhost_3306
Source Server Version : 50635
Source Host           : localhost:3306
Source Database       : java_example

Target Server Type    : MYSQL
Target Server Version : 50635
File Encoding         : 65001

Date: 2019-11-18 17:14:10
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for ex_user
-- ----------------------------
DROP TABLE IF EXISTS `ex_user`;
CREATE TABLE `ex_user` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `login_at` datetime DEFAULT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

反正比较简单,就随便建了几个字段,将实现get、post等基本操作。

2、创建实体类UserEntity

package com.javaexample.springboot.Model;

public class UserEntity {
    private int userId;
    private String userName;
    private String password;
    private String loginAt;

    //getter & setter & toString
}

3、创建控制器UserController

在Controller文件夹中创建UserController

package com.javaexample.springboot.Controller;

import com.javaexample.springboot.Model.ResponsePojo;
import com.javaexample.springboot.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@EnableAutoConfiguration
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    @ResponseBody
    public ResponsePojo userLogin(@RequestBody Map<String, String> data) {
        ResponsePojo responsePojo = userService.userLogin(data.get("userName"), data.get("password"));
        return responsePojo;
    }

    @GetMapping("/info")
    @ResponseBody
    public ResponsePojo getUserInfo(@RequestParam("userId") int userId) {
        ResponsePojo responsePojo = userService.getUserInfo(userId);
        return responsePojo;
    }
}

4、创建业务层接口:UserService

package com.javaexample.springboot.Service;

import com.javaexample.springboot.Model.ResponsePojo;

public interface UserService {
    ResponsePojo userLogin(String userName,String password);
    ResponsePojo getUserInfo(int userId);
}

5、创建业务层接口实现:UserServiceImpl

package com.javaexample.springboot.ServiceImpl;

import com.javaexample.springboot.Mapper.UserMapper;
import com.javaexample.springboot.Model.ResponsePojo;
import com.javaexample.springboot.Model.UserEntity;
import com.javaexample.springboot.Service.UserService;
import com.javaexample.springboot.Utils.ResponseManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ResponseManager responseManager;

    public ResponsePojo userLogin(String userName,String password){
        UserEntity user = userMapper.userLogin(userName, password);
        if (user == null) {
            return responseManager.buildError(11002, "密码错误");
        }
        userMapper.updateLoginInfo(user);
        return responseManager.buildSuccess();
    }

    public ResponsePojo getUserInfo(int userId) {
        UserEntity user = userMapper.getUserInfo(userId);
        return responseManager.buildSuccess(user);
    }
}

6、创建持久层:UserMapper

package com.javaexample.springboot.Mapper;

import com.javaexample.springboot.Model.UserEntity;
import org.apache.ibatis.annotations.*;

public interface UserMapper {

    @Select("SELECT user_id, user_name FROM ex_user where user_name = #{userName} and password = #{password}")
    @Results({
            @Result(property = "userId",  column = "user_id"),
            @Result(property = "userName",  column = "user_name")
    })
    UserEntity userLogin(@Param("userName") String userName, @Param("password") String password);

    @Update("UPDATE ex_user SET login_at = now() WHERE user_id =#{user_id}")
    void updateLoginInfo(UserEntity user);

    @Select("SELECT user_id,user_name,password,login_at FROM ex_user where user_id = #{userId}")
    @Results({
            @Result(property = "userId",  column = "user_id", javaType = Integer.class),
            @Result(property = "userName",  column = "user_name", javaType = String.class),
            @Result(property = "password", column = "password", javaType = String.class),
            @Result(property = "loginAt", column = "login_at", javaType = String.class)
    })
    UserEntity getUserInfo(@Param("userId") int userId);
}

7、说明

2、3、4、5、6这几步都是一气呵成,先一股脑创建完,然后挨个引用就行。其中实体类根据数据库结构来生成。
至此,项目demo初步完成,接下来试运行看看效果。

七、运行效果及项目结构图

在IDEA中运行,并通过浏览器或postman调用接口
(POST)http://localhost:9090/user/login
(GET)http://localhost:9090/user/info

注:端口默认是8080,或者根据application.properties中设置的server.port来

TIM图片20191119101523.png

TIM图片20191119101710.png

TIM图片20191119103119.png

八、打包发布

打包直接用IDEA自带的maven打包工具打包,或先切换到项目根目录,再执行下面语句。

mvn clean package -Dmaven.test.skip=true

打包后的jar文件,通过下面语句执行。(springboot.jar是我打包后的名字)

java -jar springboot.jar

九、完成

到这里第一个springboot&mybatis&mysql的示例项目已完成。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,406评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,732评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,711评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,380评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,432评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,301评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,145评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,008评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,443评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,649评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,795评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,501评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,119评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,731评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,865评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,899评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,724评论 2 354