点击next!
3、输出项目名,包(表示web项目,以后可以spingMVC连起来用)
4、如下图 maven仓库可以选择你自己的
下一步!
点击完成!
(1)web.xml文件改变servlet版本,相关问题见
(2)pom.xml文件引入依赖
数据库构建主要是两个表的创建:秒杀表、明细表
CREATE TABLE seckill(
`seckill_id` BIGINT NOT NUll AUTO_INCREMENT COMMENT '商品库存ID',
`name` VARCHAR(120) NOT NULL COMMENT '商品名称',
`number` int NOT NULL COMMENT '库存数量',
`create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`start_time` TIMESTAMP NOT NULL COMMENT '秒杀开始时间',
`end_time` TIMESTAMP NOT NULL 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='秒杀成功明细表';
1、Entity
创建实体类Seckill.java
package entity;
import java.util.Date;
/**
* @Author:peishunwu
* @Description:
* @Date:Created 2018/6/1
*/
public class Seckill {
/**
* 商品库存ID
*/
private long seckillId;
/**
* 商品名称
*/
private String name;
/**
* 库存数量
*/
private int number;
/**
* 秒杀开始时间
*/
private Date startTime;
/**
* 秒杀结束时间
*/
private Date endTime;
/**
* 创建时间
*/
private Date createTime;
public long getSeckillId() {
return seckillId;
}
public void setSeckillId(long seckillId) {
this.seckillId = seckillId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
创建SuccessKilled.java
package entity;
import java.util.Date;
/**
* @Author:peishunwu
* @Description:
* @Date:Created 2018/6/1
*/
public class SuccessKilled {
/**
* 商品库存ID
*/
private long seckillId;
/**
* 用户手机号
*/
private long userPhone;
/**
* 状态标识:-1:无效 0:成功 1:已付款 2:已发货
*/
private short state;
/**
* 创建时间
*/
private Date createTime;
/**
* 秒杀库存表实体
*/
private Seckill seckill;
public long getSeckillId() {
return seckillId;
}
public void setSeckillId(long seckillId) {
this.seckillId = seckillId;
}
public long getUserPhone() {
return userPhone;
}
public void setUserPhone(long userPhone) {
this.userPhone = userPhone;
}
public short getState() {
return state;
}
public void setState(short state) {
this.state = state;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Seckill getSeckill() {
return seckill;
}
public void setSeckill(Seckill seckill) {
this.seckill = seckill;
}
}
2、DAO
SeckillDao.java
package dao;
import entity.Seckill;
import org.apache.ibatis.annotations.Param;
import java.util.Date;
import java.util.List;
/**
* @Author:peishunwu
* @Description:
* @Date:Created 2018/6/1
*/
public interface SeckillDao {
/**
* 减库存
* @param seckillId
* @param killTime
* @return 如果影响的行数>1,表示更新行数
*/
int reduceNumber(@Param("seckillId") long seckillId, @Param("killTime")Date killTime);
/**
* 根据id查询秒杀库存
* @param seckillId
* @return
*/
Seckill gueryById(long seckillId);
/**
* 根据偏移量查询秒杀列表
* @param offset
* @param limit
* @return
* 唯一形参自动赋值
* 当有多个参数的时候要指定实际的形参名称赋值,不然找不到对应值,因为Java并没有保存形参的记录
*java在运行的时候会把List queryAll(int offset,intlimit);中的参数变成这样:queryAll(int arg0,int arg1),这样我们就没有办法去传递多个参数
*/
List queryAll(@Param("offset")int offset, @Param("limit")int limit);
}
SuccessKilledDao
package dao;
import entity.SuccessKilled;
import org.apache.ibatis.annotations.Param;
/**
* @Author:peishunwu
* @Description:
* @Date:Created 2018/6/1
*/
public interface SuccessKilledDao {
/**
* 插入购买明细,过滤重复(联合唯一主键)
* @param seckillId
* @param userPhone
* @return
*/
int insertSuccessKilled(@Param("seckillId") long seckillId,@Param("userPhone") long userPhone);
/**
* 根据ID查询SuccessKilled并携带秒杀产品对象体
* @param seckillId
* @param userPhone
* @return
*/
SuccessKilled queryByIdWithSeckill(@Param("seckillId") long seckillId,@Param("userPhone") long userPhone);
}
设计好了Database和Dao层,剩下的就是需要一个映射关系来链接两者,将数据和对象对应起来,这时就需要Mybatis或者Hibernate来完成任务,“关系型对象映射— ORM(Object/RelationshipMapping)”的名称也是由此而来。
mybatis官方文档:http://www.mybatis.org/mybatis-3/zh/index.html
Mybatis特点:
参数需要提供+SQL需要自己写(比较灵活) = Entity/List
SQL文件可以写在xml文件或者注解当中,实际使用当中提倡使用xml配置文件来写SQL,避免修改重新编译类等。
如何实现DAO接口?
第一种:通过Mapper自动实现Dao层接口(推荐使用),将执行结果集封装成我们想要的方式;
第二种:通过API编程的方式实现Dao接口。
1、Mybatis总配置文件
配置文件mybatis-config.xml
<configuration>
<settings>
<setting name="useGeneratedKeys" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
settings>
configuration>
2、Dao配置文件
保证Dao配置文件和Dao层类名相同,形成一种规范。
SeckillDao.xml文件,为Dao层定义的接口提供sql语句,Dao层的接口中的参数可以自动被Mybatis绑定到配置文件对应的Sql语句里面的参数,文件内容如下:
<mapper namespace="org.seckill.dao.SeckillDao">
<update id="reduceNumber">
update seckill set number=number-1
where seckill_id=#{seckillId}
and start_time #{killTime}
and end_time=]]> #{killTime}
and number>0;
update>
<select id="queryById" resultType="Seckill" parameterType="long">
select seckill_id,name,number,create_time,start_time,end_time
from seckill
where seckill_id=#{seckillId}
select>
<select id="queryAll" resultType="Seckill">
select seckill_id,name,number,create_time,start_time,end_time
from seckill
order by create_time desc
limit #{offset},#{limit}
select>
mapper>
SuccessSeckilledDao.xml配置
<mapper namespace="org.seckill.dao.SuccessKilledDao">
<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.create_time,
sk.state,
s.seckill_id "seckill.seckill_id",
s.name "seckill.name",
s.number "seckill.number",
s.start_time "seckill.start_time",
s.end_time "seckill.end_time",
s.create_time "seckill.create_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>
将两者整合是为了更好的优化代码,整合目标是为了更少的编码、更少的配置、足够的灵活。
当有很多Dao的映射文件的时候,则需要配置很多的
,这样会比较麻烦,对于开发人员来说是一个很重的配置维护成本,这时候使用Mybatis可以自动扫描某一个目录下的所有以xml结尾的文件,这样就有了更少的配置。
另外,当有很多Dao的时候,需要配置对应的
,使用mybatis则不用配置这些东西,因为mybatis可以自动实现Dao接口,自动注入Spring容器。
这体现出了使用Mybatis可以更少的对文件进行配置。
整合代码
Spring和Mybatis整合的总体配置:(其中spring配置在Spring的官方文档里面有介绍)
1、pom文件增加Spring依赖和mybatis依赖mysql依赖
<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.0modelVersion>
<groupId>com.pswgroupId>
<artifactId>seckillartifactId>
<version>1.0-SNAPSHOTversion>
<packaging>warpackaging>
<name>seckill Maven Webappname>
<url>http://www.example.comurl>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>1.7maven.compiler.source>
<maven.compiler.target>1.7maven.compiler.target>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>1.7.12version>
dependency>
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-coreartifactId>
<version>1.1.1version>
dependency>
<dependency>
<groupId>ch.qos.logbackgroupId>
<artifactId>logback-classicartifactId>
<version>1.1.1version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.21version>
dependency>
<dependency>
<groupId>c3p0groupId>
<artifactId>c3p0artifactId>
<version>0.9.1.2version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.11version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.2.8version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.0version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>4.1.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>4.1.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>4.1.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>4.1.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>4.1.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>4.1.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>4.1.7.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>4.1.7.RELEASEversion>
dependency>
dependencies>
<build>
<finalName>seckillfinalName>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-clean-pluginartifactId>
<version>3.0.0version>
plugin>
<plugin>
<artifactId>maven-resources-pluginartifactId>
<version>3.0.2version>
plugin>
<plugin>
<artifactId>maven-compiler-pluginartifactId>
<version>3.7.0version>
plugin>
<plugin>
<artifactId>maven-surefire-pluginartifactId>
<version>2.20.1version>
plugin>
<plugin>
<artifactId>maven-war-pluginartifactId>
<version>3.2.0version>
plugin>
<plugin>
<artifactId>maven-install-pluginartifactId>
<version>2.5.2version>
plugin>
<plugin>
<artifactId>maven-deploy-pluginartifactId>
<version>2.8.2version>
plugin>
plugins>
pluginManagement>
build>
project>
2、数据库配置jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://locahost:3306/seckill?useUnicode=true&characterEncoding=utf8
username=root
password=psw105
2、Spring-dao.xml:
<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-3.0.xsd" >
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driver}"/>
<property name="jdbcUrl" value="${url}"/>
<property name="user" value="${username}"/>
<property name="password" value="${password}"/>
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<property name="autoCommitOnClose" value="false"/>
<property name="checkoutTimeout" value="6000"/>
<property name="acquireRetryAttempts" value="2"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="typeAliasesPackage" value="entity"/>
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="dao"/>
bean>
beans>
编写两个Dao类接口的测试类,这里使用Junit4来进行单元测试;
1、SeckillDaoTest
package dao;
import entity.Seckill;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import java.util.Date;
/**
* @Author:peishunwu
* @Description:
* @Date:Created 2018/6/1
* 配置Spring和Junit整合,Junit启动时加载SPringIOC容器
* spring-test,junit:spring测试的依赖
* 1:RunWith:Junit本身需要的依赖
*/
@RunWith(SpringJUnit4ClassRunner.class)
//2:告诉Junit Spring的配置文件
@ContextConfiguration({"classpath:spring/spring-dao.xml"})
public class SeckillDaoTest {
//3:注入Dao实现类依赖 --会自动去Spring容器中查找seckillDao的实现类注入到单元测试类
@Resource
private SeckillDao seckillDao;
@Test
public void testQueryById()throws Exception{
long id = 1000;
Seckill seckill = seckillDao.queryById(id);
System.out.println(seckill.getName());
System.out.println(seckill);
}
@Test
public void reduceNumber()throws Exception{
long seckillId = 1000;
Date killTime = new Date();
int updateCount = seckillDao.reduceNumber(seckillId,killTime);
System.out.println(updateCount);
}
}
运行:
2、SuccessKilledTest
package dao;
import entity.SuccessKilled;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.alibaba.fastjson.JSONObject;
import javax.annotation.Resource;
/**
* @Author:peishunwu
* @Description:
* @Date:Created 2018/6/4
*/
@RunWith(SpringJUnit4ClassRunner.class)
/*告诉Junit Spring的配置文件*/
@ContextConfiguration("classpath:spring/spring-dao.xml")
public class SuccessSeckillDaoTest {
@Resource
private SuccessKilledDao successKilledDao;
/*
*inserCount=0:已经插入相同记录
*inserCount=1:当前执行操作插入了一条记录
*/
@Test
public void insertSuccessKilledTest()throws Exception{
long seckillId = 1002;
long userPhone = 15718879112L;
int insertCount = successKilledDao.insertSuccessKilled(seckillId,userPhone);
System.out.println("insertCount:"+insertCount);
}
@Test
public void queryByIdWithSeckill()throws Exception{
long seckillId = 1002;
long userPhone = 15718879112L;
SuccessKilled successKilled = successKilledDao.queryByIdWithSeckill(seckillId,userPhone);
System.out.println(JSONObject.toJSONString(successKilled));
}
}
运行:
遇到问题与解决方法:
1、maven单元测试报java.lang.IllegalStateException: Failed to load ApplicationContext
从网上查了两个原因:
1.报这个异常java.lang.IllegalStateException: Failed to load ApplicationContext的时候,通常是因为applicationContent.xml里面的bean初始化失败的原因;
参考:http://breezylee.iteye.com/blog/1993003
2.mybatis-spring版本不支持当前mybatis版本和Spring版本,mybatis-spring当前版本支持对应的当前mybatis版本和Spring版本可以参考maven官网;
参考:http://www.cnblogs.com/molao-doing/p/6056380.html