zoukankan      html  css  js  c++  java
  • springboot集成mybatis环境搭建以及实现快速开发微服务商品模块基本的增删改查!

    之前学习了springboot和mybatis3的一些新特性,初步体会了springboot的强大(真的好快,,,,,),最近趁着复习,参考着以前学习的教程,动手写了一个springboot实战的小例子!

    一 创建表以及实体

    使用简单的五个字段商品表,主键采用UUID字符串,价格使用BigDecimal,本来是想在linux数据库中建立表的,实在是懒不想启动虚拟机(这么简单也觉得没必要),,sql语句如下:

    create table products(
    pid varchar(32) not null primary key,
    pname varchar(200),
    ptype varchar(50),
    pprice decimal,
    createtime timestamp
    );

    二 添加依赖

    springboot的强大不必说,只需要添加很少的依赖,此案例使用mybatis集成,mybatis官方提供的集成springboot依赖,父级依赖这里就不写了:

    <!-- springbootweb依赖 -->
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    </dependency>


    <!--jdbc依赖 -->
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>


    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    </dependency>


    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.1</version>
    </dependency>


    <!--springboot与mybatis整合依赖,mybatis官方出的 -->
    <dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.1.1</version>
    </dependency>

    三 新建mapper接口

    使用mybatis3的@Mapper注解,省去xml文件的麻烦,而且springboot可以自动提供实现类,不需要我们手动去写,mapper接口如下:

    ,

    四 运行程序测试环境

    到这里只需要在resources目录下新建配置文件,加上数据源配置就好,这里顺便提一下,springboot还可以省去driveClass的配置,它会根据URL自动判断所使用的数据库:

    spring.datasource.url=jdbc:mysql:///db_products?useUnicode=true&characterEncoding=UTF-8
    spring.datasource.username=root
    spring.datasource.password=xxxxxx
    #driverClassName可省略不写,springboot会根据url自动推断所使用的数据库
    #spring.datasource.driverClassName=com.mysql.jdbc.Driver

    ,最后只需要再启动程序进行简单测试就可以,发现竟然一遍过,前前后后用了不到5分钟,真是个神奇的框架,哈哈!

    主程序入口如下:

    @SpringBootApplication
    public class App
    {
      public static void main( String[] args )
    {
      //启动程序
      ConfigurableApplicationContext content = SpringApplication.run(App.class, args);
      //测试mapper添加方法
      ProductMapper mapper = content.getBean(ProductMapper.class);
      Product product = new Product(UUID.randomUUID().toString().replace("-", "")
      ,"小米7","手机",new BigDecimal(99.99));
      mapper.add(product);
      content.close();
      }
    }

  • 相关阅读:
    shell特殊符号cut命令 sort_wc_uniq命令 tee_tr_split命令 shell特殊符号
    管道符和作业控制 shell变量 环境变量配置文件
    8.1 shell介绍 8.2 命令历史 8.3 命令补全和别名 8.4 通配符 8.5 输入输出重定向 
    yum更换国内源 yum下载rpm包 源码包安装
    mysql Communication link failure, message from server: "Can't get hostname for your address"
    7.1 安装软件包的三种方法 7.2 rpm包介绍 7.3 rpm工具用法 7.4 yum工具用法 7.5 yum搭建本地仓库
    java 对象数组
    zip压缩工具 tar打包 打包并压缩
    java链接mysql 中文乱码
    压缩打包介绍/gzip压缩工具/bzip2压缩工具/xz压缩工具
  • 原文地址:https://www.cnblogs.com/houzheng/p/8747904.html
Copyright © 2011-2022 走看看