新建项目spring boot + mybatis

一、安装IDEA

1、下载 java8,配置环境变量
2、下载 idea,安装

二、新建项目

1、File - New - ProjectSpring InitializrService URL使用Default
2、填写包名相关信息com.yzyfdf.shares,Java选8
3、勾选依赖

    - web
        - Spring Web
    - SQL
        - JDBC API
        - MyBatis Framework
        - MySQL Driver

4、选择项目位置
5、完成配置等待项目初始化

三、添加数据

1、安装 MySQL,idea连接数据库,可以参照 PyCharm连接MySQL
2、创建数据库,新建一个表,比如:

create table sharesdata
(
    myId       int primary key auto_increment comment '主键id',
    timestamp  varchar(13) comment '收盘时间',
    symbol     varchar(12) not null comment '股票代码',
    index (symbol),
    name       varchar(8)  not null comment '股票名称',
    current    float comment '当前股价',
    chg        float comment '股价变更',
    percent    float comment '股价变更百分比',
    high       float comment '最高',
    low        float comment '最低',
    open       float comment '今开',
    last_close float comment '昨收',
    limit_up   float comment '涨停',
    limit_down float comment '跌停',
    volume     bigint comment '成交量',
    amount     float comment '成交额'
);

3、插入一条数据

insert into sharesdata (symbol, name, current, chg, percent, high, low, open, last_close, limit_up, limit_down)
values ('SH600000', '浦发银行', 10.46, -0.04, -0.38, 10.57, 10.44, 10.57, 10.5, 11.55, 9.45, 38982822, 408921984);

四、配置mybatis-generator插件

1、pom.xml中plugins标签下加入

    <plugin>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.3.5</version>
        <configuration>
            <!-- 在控制台打印执行日志 -->
            <verbose>true</verbose>
            <!-- 重复生成时会覆盖之前的文件-->
            <overwrite>true</overwrite>
            <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
        </configuration>
        <!-- 数据库连接选择8.0以上的,因为用的mysql8.0,这里一定要加,虽然上面依赖里已经有了-->
        <dependencies>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.15</version>
            </dependency>
        </dependencies>
    </plugin>

2、跟启动类Application同级,创建4个目录:controllerservicemapperentity,在resources下新建mapper文件夹

3、添加配置
resources下新建generatorConfig.xml,最下方table标签注意改表名和实体类名,内容:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <!--导入配置文件-->
    <properties resource="mybatisGeneratorinit.properties"/>

    <!-- 一个数据库一个context -->
    <context id="default">

        <!-- 注释生成设置 -->
        <commentGenerator>
            <!-- 是否生成注释代时间戳-->
            <property name="suppressDate" value="true"/>
            <!-- 是否取消注释 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!--jdbc的数据库连接-->
        <jdbcConnection driverClass="${jdbc_driver}" connectionURL="${jdbc_url}"
                        userId="${jdbc_user}" password="${jdbc_password}">
            <property name="nullCatalogMeansCurrent" value="true"/>
        </jdbcConnection>

        <!-- 类型转换 -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- targetPackage:生成的实体类所在的包 -->
        <!-- targetProject:生成的实体类所在的硬盘位置 -->
        <javaModelGenerator targetPackage="${location_entity}" targetProject="src/main/java">
            <!-- 是否允许子包 -->
            <property name="enableSubPackages" value="false"/>
            <!-- 是否对modal添加构造函数 -->
            <property name="constructorBased" value="true"/>
            <!-- 是否清理从数据库中查询出的字符串左右两边的空白字符 -->
            <property name="trimStrings" value="true"/>
            <!-- 建立modal对象是否不可改变 即生成的modal对象不会有setter方法,只有构造方法 -->
            <property name="immutable" value="false"/>
        </javaModelGenerator>

        <!-- targetPackage 和 targetProject:生成的  mapper xml 文件的包和位置 -->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
            <!-- 是否在当前路径下新加一层schema,ex:false路径com.qikegu.demo.model, com.qikegu.demo.model.[schemaName] -->
            <property name="enableSubPackages" value="false"/>
            <!-- 是否针对string类型的字段在set的时候进行trim调用 -->
            <property name="trimStrings" value="true"/>
        </sqlMapGenerator>

        <!-- targetPackage 和  targetProject:生成的  java interface 文件的包和位置 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="${location_mapper}"
                             targetProject="src/main/java">
            <!-- 是否在当前路径下新加一层schema,ex:false路径com.qikegu.demo.model, com.qikegu.demo.model.[schemaName] -->
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>

        <!-- 配置表信息 -->
        <!-- schema即为数据库名 tableName为对应的数据库表 domainObjectName是要生成的实体类 enable*ByExample, 是否生成 example类   -->
        <!-- 不同的表,修改tableName和domainObjectName就可以 -->
        <table tableName="sharesdata" domainObjectName="Share"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
        </table>
    </context>
</generatorConfiguration>

resources下新建mybatisGeneratorinit.properties,内容:

#DataSource
#数据库驱动
jdbc_driver=com.mysql.jdbc.Driver
#数据库链接
jdbc_url=jdbc:mysql://localhost:3306/shares?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
#数据库用户名
jdbc_user=root
#数据库密码
jdbc_password=123456
#生成类位置
location_entity=com.yzyfdf.shares.entity
location_mapper=com.yzyfdf.shares.mapper

application.yml中添加:

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

mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml
  type-aliases-package: com.yzyfdf.shares.entity

4、运行插件
右侧Maven - 展开Plugins - mybatis-genertor,双击mybatis-generator:generate,等待编译,出现下面的就成功了

[INFO] Saving file ShareMapper.xml
[INFO] Saving file Share.java
[INFO] Saving file ShareMapper.java
[INFO] ---------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ---------------------------------------------
[INFO] Total time:  1.141 s

自动生成了三个文件

五、补全代码

1、给ShareMapper.java类加上@Repository注解
2、在service下新建ShareService

import com.yzyfdf.shares.entity.Share;
import com.yzyfdf.shares.mapper.ShareMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ShareService {

    @Autowired
    ShareMapper shareMapper;

    public Share getShareById(int id) {
        return shareMapper.selectByPrimaryKey(id);
    }
}

3、在controller下新建ShareController

import com.yzyfdf.shares.entity.Share;
import com.yzyfdf.shares.service.ShareService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/shares")
public class ShareController {
    
    @Autowired
    private ShareService shareService;

    @RequestMapping("/{id}")
    public Share getShare(@PathVariable int id) {
        return shareService.getShareById(id);
    }
}

4、给启动类加上注解@MapperScan("com.yzyfdf.shares.mapper")

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

@MapperScan("com.yzyfdf.shares.mapper")
@SpringBootApplication
public class SharesApplication {

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

}

5、在application.yml中加上端口

server:
  port: 8015

六、启动

1、在启动类右键,选择Run,等待启动完
2、在浏览器输入http://localhost:8015/shares/1,就能看到数据了

七、分环境配置

1、application.ymldatasource部分放入application-dev.yml
2、再创建一个application-prod.yml,内容同application-dev.yml,用户名密码自行修改
3、application.yml中加入

spring:
  profiles:
    active: prod

修改active改变环境

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