spring boot-2.0.x + mybatis

作者: hllcve_ | 来源:发表于2018-07-12 02:42 被阅读173次
搭建项目 选择java版本和项目类型 添加项目依赖 这三个貌似没有用,删掉

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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.littlebear</groupId>
    <artifactId>shop</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>shop</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </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>
        </dependency>
    </dependencies>

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

</project>

添加以下依赖

        <!-- 分页插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>

        <!-- alibaba的druid数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>

项目结构

image.png

项目启动类加上包扫描

image.png

配置文件,改成yml格式,把application.properties后缀改成yml即可

spring:
  datasource:
    name: shop
    type: com.alibaba.druid.pool.DruidDataSource
    #druid相关配置
    druid:
      #监控统计拦截的filters
      filters: stat
      driver-class-name: com.mysql.jdbc.Driver
      #基本属性
      url: jdbc:mysql://127.0.0.1:3306/shop?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&userSSL=false
      username: root
      password: root
      #配置初始化大小/最小/最大
      initial-size: 1
      min-idle: 1
      max-active: 20
      #获取连接等待超时时间
      max-wait: 60000
      #间隔多久进行一次检测,检测需要关闭的空闲连接
      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
      #打开PSCache,并指定每个连接上PSCache的大小。oracle设为true,mysql设为false。分库分表较多推荐设置为false
      pool-prepared-statements: false
      max-pool-prepared-statement-per-connection-size: 20

mybatis:
  mapper-locations: classpath:mybatis/mapper/*Mapper.xml
  type-aliases-package: com.littlebear.model

#pagehelper
pagehelper:
    helperDialect: mysql
    reasonable: true
    supportMethodsArguments: true
    params: count=countSql
    returnPageInfo: check

添加目录

image.png

创建数据库表

-- 类目
create table `product_category` (
    `category_id` int not null auto_increment,
    `category_name` varchar(64) not null comment '类目名字',
    `category_type` int not null comment '类目编号',
    `create_time` timestamp default current_timestamp comment '创建时间',
    `update_time` timestamp default current_timestamp on update current_timestamp comment '修改时间',
    primary key (`category_id`)
);

-- 商品
create table `product_info` (
    `product_id` varchar(32) not null,
    `product_name` varchar(64) not null comment '商品名称',
    `product_price` decimal(8,2) not null comment '单价',
    `product_stock` int not null comment '库存',
    `product_description` varchar(64) comment '描述',
    `product_icon` varchar(512) comment '小图',
    `product_status` int DEFAULT '0' COMMENT '商品状态,0正常1下架',
    `category_type` int not null comment '类目编号',
    `create_time` timestamp default current_timestamp comment '创建时间',
    `update_time` timestamp default current_timestamp on update current_timestamp comment '修改时间',
    primary key (`product_id`)
);

-- 订单
create table `order_master` (
    `order_id` varchar(32) not null,
    `buyer_name` varchar(32) not null comment '买家名字',
    `buyer_phone` varchar(32) not null comment '买家电话',
    `buyer_address` varchar(128) not null comment '买家地址',
    `buyer_openid` varchar(64) not null comment '买家微信openid',
    `order_amount` decimal(8,2) not null comment '订单总金额',
    `order_status` int not null default '0' comment '订单状态, 默认为新下单',
    `pay_status` int not null default '0' comment '支付状态, 默认未支付',
    `create_time` timestamp default current_timestamp comment '创建时间',
    `update_time` timestamp ndefault current_timestamp on update current_timestamp comment '修改时间',
    primary key (`order_id`),
    key `idx_buyer_openid` (`buyer_openid`)
);

-- 订单商品
create table `order_item` (
    `order_item_id` varchar(32) not null,
    `order_id` varchar(32) not null,
    `product_id` varchar(32) not null,
    `product_name` varchar(64) not null comment '商品名称',
    `product_price` decimal(8,2) not null comment '当前价格,单位分',
    `product_quantity` int not null comment '数量',
    `product_icon` varchar(512) comment '小图',
    `create_time` timestamp default current_timestamp comment '创建时间',
    `update_time` timestamp default current_timestamp on update current_timestamp comment '修改时间',
    primary key (`order_item_id`),
    key `idx_order_id` (`order_id`)
);

-- 用户
create table `user_info` (
    `id` varchar(32) not null,
    `username` varchar(32) not null,
    `password` varchar(32) not null,
    `openid` varchar(64) not null comment '微信openid',
    `role` int not null comment '1买家 2卖家',
    `create_time` timestamp default current_timestamp comment '创建时间',
    `update_time` timestamp default current_timestamp on update current_timestamp comment '修改时间',
    primary key (`id`)
) comment '用户信息表';

-- 卖家(登录后台使用, 卖家登录之后可能直接采用微信扫码登录,不使用账号密码)
create table `seller_info` (
    `id` varchar(32) not null,
    `username` varchar(32) not null,
    `password` varchar(32) not null,
    `openid` varchar(64) not null comment '微信openid',
    `create_time` timestamp not null default current_timestamp comment '创建时间',
    `update_time` timestamp not null default current_timestamp on update current_timestamp comment '修改时间',
    primary key (`id`)
) comment '卖家信息表';

利用Mybatis代码生成工具,生成model,mapper(interface),xml(映射文件),内含基本的crud

image.png

编写controller

package com.littlebear.controller;

import com.littlebear.constant.ServerResponse;
import com.littlebear.model.ProductCategory;
import com.littlebear.service.IProductCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: shenhelin
 * describe: 商品类目服务
 * creat_date: 2018/7/12
 * creat_time: 02:18
 **/
@RestController
@RequestMapping("/productCategory")
public class ProductCategoryController {

    @Autowired
    IProductCategoryService productCategoryService;

    @RequestMapping("/add.do")
    public ServerResponse getTicketsDetail(ProductCategory productCategory) {

        return productCategoryService.insert(productCategory);
    }

    @RequestMapping("list.do")
    public ServerResponse list(@RequestParam(value = "pageNum",defaultValue = "1") int pageNum,
                               @RequestParam(value = "pageSize",defaultValue = "10") int pageSize){

        return productCategoryService.selectList(pageNum,pageSize);
    }

}

base-service

package com.hllcve.springbootdemo.service;

import com.github.pagehelper.PageInfo;
import com.hllcve.springbootdemo.constant.ServerResponse;

import java.io.Serializable;
import java.util.List;

/**
 * @param <T>
 * @param <PK>
 * @author SHL
 */
public interface BaseService<T, PK extends Serializable> {

    ServerResponse<String> deleteByPrimaryKey(PK id);

    ServerResponse<String> insert(T obj);

    ServerResponse<String> insertSelective(T obj);

    ServerResponse<T> selectByPrimaryKey(PK id);

    ServerResponse<T> updateByPrimaryKeySelective(T obj);

    ServerResponse<T> updateByPrimaryKey(T obj);


    ServerResponse<String> insertBatch(List<T> list);

    ServerResponse<List<T>> selectListByCondition(T obj);

    ServerResponse<List<T>> selectList();

    ServerResponse<PageInfo<T>> selectList(int pageNum, int pageSize);

    ServerResponse<T> selectByCondition(T obj);

    ServerResponse<PageInfo<T>> selectListByCondition(T obj, int pageNum, int pageSize);

}

service

package com.hllcve.springbootdemo.service;

import com.hllcve.springbootdemo.constant.ServerResponse;
import com.hllcve.springbootdemo.model.ProductCategory;

import java.util.List;
import java.util.Map;

public interface IProductCategoryService extends BaseService<ProductCategory, Integer> {

    ServerResponse<List<ProductCategory>> selectListByColumnIn(Map<String, Object> map);
}

service-impl

package com.littlebear.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.littlebear.constant.ServerResponse;
import com.littlebear.mapper.ProductCategoryMapper;
import com.littlebear.model.ProductCategory;
import com.littlebear.service.IProductCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author: shenhelin
 * describe: ProductCategoryServiceImpl
 * creat_date: 2018/7/12
 * creat_time: 02:19
 **/
@Service
public class ProductCategoryServiceImpl implements IProductCategoryService {

    @Autowired
    private ProductCategoryMapper productCategoryMapper;

    @Override
    public ServerResponse<String> deleteByPrimaryKey(Integer id) {
        return null;
    }

    @Override
    @Transactional
    public ServerResponse<String> insert(ProductCategory obj) {
        int rowCount = productCategoryMapper.insert(obj);
        if(rowCount > 0){
            return ServerResponse.createBySuccess("添加品类成功");
        }
        return ServerResponse.createByErrorMessage("添加品类失败");
    }

    @Override
    public ServerResponse<String> insertSelective(ProductCategory obj) {
        return null;
    }

    @Override
    @Transactional(readOnly = true)
    public ServerResponse<ProductCategory> selectByPrimaryKey(Integer id) {
        ProductCategory productCategory = productCategoryMapper.selectByPrimaryKey(1);
        if(productCategory == null){
            return  ServerResponse.createByErrorMessage("未查询到相关数据");
        }
        return ServerResponse.createBySuccess(productCategory);
    }

    @Override
    public ServerResponse<ProductCategory> updateByPrimaryKeySelective(ProductCategory obj) {
        return null;
    }

    @Override
    public ServerResponse<ProductCategory> updateByPrimaryKey(ProductCategory obj) {
        return null;
    }

    @Override
    public ServerResponse<ProductCategory> selectByCondition(ProductCategory obj) {
        return null;
    }

    @Override
    public ServerResponse<PageInfo<ProductCategory>> selectListByCondition(ProductCategory obj, int pageNum, int pageSize) {
        return null;
    }

    @Override
    public ServerResponse<List<ProductCategory>> selectListByCondition(ProductCategory obj) {
        return null;
    }

    @Override
    public ServerResponse<List<ProductCategory>> selectList() {
        return null;
    }

    /**
     * 分页插件pagehelper的用法
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public ServerResponse<PageInfo<ProductCategory>> selectList(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<ProductCategory> productCategoryList = productCategoryMapper.selectList();
        PageInfo pageResult = new PageInfo(productCategoryList);
        return ServerResponse.createBySuccess(pageResult);
    }

    @Override
    public ServerResponse<String> insertBatch(List<ProductCategory> list) {
        return null;
    }
}

mapper.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.hllcve.springbootdemo.mapper.ProductCategoryMapper" >
  <resultMap id="BaseResultMap" type="com.hllcve.springbootdemo.model.ProductCategory" >
    <constructor >
      <idArg column="category_id" jdbcType="INTEGER" javaType="java.lang.Integer" />
      <arg column="category_name" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="category_type" jdbcType="INTEGER" javaType="java.lang.Integer" />
      <arg column="create_time" jdbcType="TIMESTAMP" javaType="java.util.Date" />
      <arg column="update_time" jdbcType="TIMESTAMP" javaType="java.util.Date" />
    </constructor>
  </resultMap>
  <sql id="Base_Column_List" >
    category_id, category_name, category_type, create_time, update_time
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from product_category
    where category_id = #{categoryId,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from product_category
    where category_id = #{categoryId,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.hllcve.springbootdemo.model.ProductCategory" >
    insert into product_category (category_id, category_name, category_type)
    values (#{categoryId,jdbcType=INTEGER}, #{categoryName,jdbcType=VARCHAR}, #{categoryType,jdbcType=INTEGER})
  </insert>
  <insert id="insertSelective" parameterType="com.hllcve.springbootdemo.model.ProductCategory" >
    insert into product_category
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="categoryId != null" >
        category_id,
      </if>
      <if test="categoryName != null" >
        category_name,
      </if>
      <if test="categoryType != null" >
        category_type,
      </if>
      <if test="createTime != null" >
        create_time,
      </if>
      <if test="updateTime != null" >
        update_time,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="categoryId != null" >
        #{categoryId,jdbcType=INTEGER},
      </if>
      <if test="categoryName != null" >
        #{categoryName,jdbcType=VARCHAR},
      </if>
      <if test="categoryType != null" >
        #{categoryType,jdbcType=INTEGER},
      </if>
      <if test="createTime != null" >
        #{createTime,jdbcType=TIMESTAMP},
      </if>
      <if test="updateTime != null" >
        #{updateTime,jdbcType=TIMESTAMP},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.hllcve.springbootdemo.model.ProductCategory" >
    update product_category
    <set >
      <if test="categoryName != null" >
        category_name = #{categoryName,jdbcType=VARCHAR},
      </if>
      <if test="categoryType != null" >
        category_type = #{categoryType,jdbcType=INTEGER},
      </if>
      <if test="createTime != null" >
        create_time = #{createTime,jdbcType=TIMESTAMP},
      </if>
      <if test="updateTime != null" >
        update_time = #{updateTime,jdbcType=TIMESTAMP},
      </if>
    </set>
    where category_id = #{categoryId,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.hllcve.springbootdemo.model.ProductCategory" >
    update product_category
    set category_name = #{categoryName,jdbcType=VARCHAR},
      category_type = #{categoryType,jdbcType=INTEGER},
      create_time = #{createTime,jdbcType=TIMESTAMP},
      update_time = #{updateTime,jdbcType=TIMESTAMP}
    where category_id = #{categoryId,jdbcType=INTEGER}
  </update>

  <select id="selectList" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List"/>
    from product_category
  </select>
</mapper>
编写完controller和service后的结构

启动成功

image.png

接口调用成功

add.do list.do 分页查询

相关文章

网友评论

    本文标题:spring boot-2.0.x + mybatis

    本文链接:https://www.haomeiwen.com/subject/oogkpftx.html