前言

该篇教程主要关注MyBatis实现底层的接口,把MyBatis交给Spring来托管。数据库连接池用的c3p0。数据库用的MySQL。主要有2个大类:秒杀商品的查询、秒杀明细的插入。

准备工作

1、数据库脚本。先初始化数据库,这里主要有2张表:seckill【秒杀商品表】、success_killed【秒杀记录明细表】。success_killed采用双主键seckill_id、user_phone。同一个商品同一个手机号只能秒杀一次,如果通过非法手段通过业务接口的话,则重复插入秒杀记录明细时会返回0。

-- 创建数据库
CREATE DATABASE seckill;
-- 使用数据库
use seckill;
CREATE TABLE seckill(
`seckill_id` BIGINT NOT NUll AUTO_INCREMENT COMMENT '商品库存ID',
`name` VARCHAR(120) NOT NULL COMMENT '商品名称',
`number` int NOT NULL COMMENT '库存数量',
`start_time` TIMESTAMP NOT NULL COMMENT '秒杀开始时间',
`end_time` TIMESTAMP NOT NULL COMMENT '秒杀结束时间',
`create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (seckill_id),
key idx_start_time(start_time),
key idx_end_time(end_time),
key idx_create_time(create_time)
)ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8 COMMENT='秒杀库存表'; -- 初始化数据
INSERT into seckill(name,number,start_time,end_time)
VALUES
('1000元秒杀iphone6',100,'2016-01-01 00:00:00','2016-01-02 00:00:00'),
('800元秒杀ipad',200,'2016-01-01 00:00:00','2016-01-02 00:00:00'),
('6600元秒杀mac book pro',300,'2016-01-01 00:00:00','2016-01-02 00:00:00'),
('7000元秒杀iMac',400,'2016-01-01 00:00:00','2016-01-02 00:00:00'); -- 秒杀成功明细表
-- 用户登录认证相关信息(简化为手机号)
CREATE TABLE success_killed(
`seckill_id` BIGINT NOT NULL COMMENT '秒杀商品ID',
`user_phone` BIGINT NOT NULL COMMENT '用户手机号',
`state` TINYINT NOT NULL DEFAULT -1 COMMENT '状态标识:-1:无效 0:成功 1:已付款 2:已发货',
`create_time` TIMESTAMP NOT NULL COMMENT '创建时间',
PRIMARY KEY(seckill_id,user_phone),/*联合主键*/
KEY idx_create_time(create_time)
)ENGINE=INNODB DEFAULT CHARSET=utf8 COMMENT='秒杀成功明细表';

   2、实现MyBatis配置文件并且交由Spring托管

mybatis-config.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>
<settings>
<!--使用jdbc的getGeneratedKeys获取自增主键值-->
<setting name="useGeneratedKeys" value="true"/>
<!--使用列别名替换列名,默认值true-->
<setting name="useColumnLabel" value="true"/>
<!--开启驼峰命名法 字段名seckill_Id 对应属性名seckillId -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>

spring-dao.xml

这里关键是sqlsessionfactory的配置,需要指定mybatis全局配置文件、mapper.xml文件位置。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <!--1、配置数据库相关参数-->
<context:property-placeholder location="classpath:jdbc.properties"/> <!--2、配置数据库连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/> <!--数据库连接池最大连接数-->
<property name="maxPoolSize" value="30" />
<!--数据库连接池最小连接数-->
<property name="minPoolSize" value="10"/>
<!--关闭连接后不自动commit-->
<property name="autoCommitOnClose" value="false"/>
<!--获取连接超时时间-->
<property name="checkoutTimeout" value="1000"/>
<!--当获取连接失败时重试次数-->
<property name="acquireRetryAttempts" value="3"/>
</bean> <!--3、配置SqlSessionFactory-->
<bean id="sessionfactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--mybatis全局配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!--扫描entity包-->
<property name="typeAliasesPackage" value="com.seckill.entity"/>
<!--扫描sql xml文件-->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean> <!--4、配置扫描Dao接口包,动态实现dao接口注入到spring容器-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--需要扫描的dao接口-->
<property name="basePackage" value="com.seckill.dao"/>
<!--注入sqlsessionfactory-->
<property name="sqlSessionFactoryBeanName" value="sessionfactory"/>
</bean>
</beans>

秒杀底层接口实现

1、实现接口。这里注意Param注解,当方法只有一个参数时不用指定,如果你需要给mapper里传多个参数则指定,也可以用HashMap传参。

public interface SeckillDao {

    /**减库存**/
int reduceNumber(@Param("seckillId") long seckillId,@Param("killTime") Date killTime); /**查询秒杀商品详情**/
Seckill queryById(long seckillId); /**查询所有秒杀商品**/
List<Seckill> queryAll(@Param("offset") int offset,@Param("limit") int limit); } public interface SuccessKillDao { /**
* 插入秒杀商品明细
* **/
int insertSuccessKilled(@Param("seckillId") long seckillId,@Param("userPhone") long userPhone); /**
* 根据商品id查询商品秒杀明细,并且同时返回商品明细
* **/
SuccessKilled queryByIdWithSeckill(@Param("seckillId") long seckillId,@Param("userPhone") long userPhone); }

2、秒杀实现。也就是mapper目录下的*.xml文件。

SeckillDao.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.seckill.dao.SeckillDao">
<update id="reduceNumber">
update seckill set number=number-1
where seckill_Id=#{seckillId}
and start_time <![CDATA[ <= ]]> #{killTime}
and end_time <![CDATA[ >= ]]> #{killTime}
and number>0
</update> <select id="queryById" resultType="Seckill">
select seckill_id,name,number,start_time,end_time,create_time
from seckill
where seckill_id=#{seckillId}
</select> <select id="queryAll" resultType="Seckill">
select seckill_id,name,number,start_time,end_time,create_time
from seckill
order by create_time
limit #{offset},#{limit}
</select>
</mapper>

SuccessKillDao.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.seckill.dao.SuccessKillDao"> <!--主键重复时不再插入数据-->
<insert id="insertSuccessKilled"> insert ignore into success_killed (seckill_id,user_Phone,state) values (#{seckillId},#{userPhone},0)
</insert> <select id="queryByIdWithSeckill" resultType="SuccessKilled">
select
sk.seckill_id,
sk.user_Phone,
sk.state,
sk.create_time,
s.seckill_id "seckill.seckill_id",
s.name "seckill.name",
s.number "seckill.number",
s.create_time "seckill.create_time",
s.start_time "seckill.start_time",
s.end_time "seckill.end_time"
from success_killed sk
inner join seckill s on sk.seckill_id = s.seckill_id
where sk.seckill_id=#{seckillId} and sk.user_Phone=#{userPhone}
</select>
</mapper>

3、OK,准备工作就绪,可以实现单元测试的方法了。

 

基于SpringMVC+Spring+MyBatis实现秒杀系统【数据库接口】的更多相关文章

  1. 基于SpringMVC+Spring+MyBatis实现秒杀系统【概况】

    前言 本教程使用SpringMVC+Spring+MyBatis+MySQL实现一个秒杀系统.教程素材来自慕课网视频教程[https://www.imooc.com/learn/631].有感兴趣的可 ...

  2. 基于SpringMVC+Spring+MyBatis实现秒杀系统【客户端交互】

    前言 该篇主要实现客户端和服务的交互.在第一篇概况里我已经贴出了业务场景的交互图片. 客户端交互主要放在seckill.js里来实现.页面展现基于jsp+jstl来实现. 准备工作 1.配置web.x ...

  3. 基于SpringMVC+Spring+MyBatis实现秒杀系统【业务逻辑】

    前言 该篇主要实现秒杀业务层,秒杀业务逻辑里主要包括暴露秒杀接口地址.实现秒杀业务逻辑.同时声明了三个业务类:Exposer.SeckillExecution.SeckillResult. Expos ...

  4. 手把手教你使用VUE+SpringMVC+Spring+Mybatis+Maven构建属于你自己的电商系统之vue后台前端框架搭建——猿实战01

            猿实战是一个原创系列文章,通过实战的方式,采用前后端分离的技术结合SpringMVC Spring Mybatis,手把手教你撸一个完整的电商系统,跟着教程走下来,变身猿人找到工作不是 ...

  5. 第04项目:淘淘商城(SpringMVC+Spring+Mybatis)【第十二天】(系统架构讲解、nginx)

    https://pan.baidu.com/s/1bptYGAb#list/path=%2F&parentPath=%2Fsharelink389619878-229862621083040 ...

  6. 第04项目:淘淘商城(SpringMVC+Spring+Mybatis)【第十天】(单点登录系统实现)

    https://pan.baidu.com/s/1bptYGAb#list/path=%2F&parentPath=%2Fsharelink389619878-229862621083040 ...

  7. Idea SpringMVC+Spring+MyBatis+Maven调整【转】

    Idea SpringMVC+Spring+MyBatis+Maven整合   创建项目 File-New Project 选中左侧的Maven,选中右侧上方的Create from archetyp ...

  8. SpringMVC+Spring+MyBatis+Maven调整【转】

    Idea SpringMVC+Spring+MyBatis+Maven整合   创建项目 File-New Project 选中左侧的Maven,选中右侧上方的Create from archetyp ...

  9. SpringMVC+Spring+MyBatis个人技术博客源码

    项目描述 Hi,大家好,又到了源码分享时间啦,今天我们分享的源码一个<个人技术博客>,该博客是基于SSM实现的一个个人博客系统,适合初学SSM和个人博客制作的同学学习.有了这个源码,直接买 ...

随机推荐

  1. nginx报错:./configure: error: C compiler cc is not found, gcc 是已经安装了的

    源码安装nginx报错,找不到gcc,但是实际上gcc是存在的,如下: # ./configure checking for OS + Linux -.el7.x86_64 x86_64 checki ...

  2. 因为曾经装过Mysql导致再次装时windows无法启动MySQL服务报错1067的解决方法

    找到这里 MySQL右击属性 检查这里的可执行文件的路径是否正确,因为我这里显示的是原先的文件夹所以会一直启动失败,修改一下 这里你去百度经验 windows服务修改可执行文件路径 网址https:/ ...

  3. day19_雷神_django第二天

    django_day02 Django的路由系统 URL配置(URLconf)就像Django所支撑网站的目录.它的本质是URL与要为该URL调用的视图函数之间的映射表. 1.URLconf配置 基本 ...

  4. chat.php

    <!DOCTYPE html><html> <meta charset="UTF-8"> <title>web chat</t ...

  5. cef3:禁止win10高dpi下cef对内部网页进行缩放

    1.使用命令行参数 //禁止cef进行dpi缩放 command_line->AppendSwitchWithValue("--force-device-scale-factor&qu ...

  6. Java集合排序(面试必考点之一)

    集合是Java面试必考知识点,而集合的排序也是非常重要的,工作中经常用到,那么这个知识点也是必须要掌握的,下面是我曾经面试时被面试官问的问题: 根据API可知,Java集合的工具类Collection ...

  7. FFmpeg开发实战(二):FFmpeg 文件操作

    FFmpeg 提供了丰富的API供我们使用,下面我们来讲述一下文件操作相关的API: FFmpeg 删除文件:avpriv_io_delete() FFmpeg 重命名文件:avpriv_io_mov ...

  8. Javascript高级编程学习笔记(42)—— DOM(8)Attr类型

    Attr类型 我们在之前的文章中提到了,元素有一个 attributes 属性 该属性保存了一个 NamedNodeMap 集合 该集合中的元素也就是今天我们所要记叙的 attr 类型 主要就是方便我 ...

  9. 《深入浅出nodejs》读书笔记(2)

    概述 本来是想着学学node.js试试的,后来发现node.js才是真正的js啊,它里面用到了很多我们平时没用过的js特性,而且还非常优雅,比如它里面的异步编程思想,总之,<深入浅出node.j ...

  10. SVM算法简单应用

    第一部分:线性可分 通俗解释:可以用一条直线将两类分隔开来 一个简单的例子,直角坐标系中有三个点,A,B点为0类,C点为1类: from sklearn import svm # 三个点 x = [[ ...