轉載請標明出處:
http://blog.csdn.net/forezp/article/details/53730333
本文出自方誌朋的博客
最近實在太忙,之前寫的《rxjava系列文章》告一段落,還有兩篇會在一月中旬補上,感謝大家。這篇文章講述mybatis搭建DAO層,另外這系列文章是我看完《Java高併發秒殺系列》的課程整理的,所以文章採用的例子也來源於這系列課程。
一.環境/工具
1.開發工具idea
3.javaweb容器 tomcat
4.構建項目工具maven
關於這幾個工具下載安裝,環境的搭建就不介紹,自行百度。
二.採用maven 構建項目
採用命令構架,當然也可以採用ide 直接構建。
構建命令:
mvn archetype:generate -DgroupId=org.forezp -DartifactId=minnkill -DarchetypeArtifactId=maven-archetype-webapp
低版本maven需要將generate 改爲create.
三.補全SSM框架相關依賴
下面是SSM框架所需的所有框架
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.seckill</groupId>
<artifactId>seckill</artifactId>
<packaging>war</packaging>
<version>1.0.0</version>
<name>seckill Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<!--使用junit4,4以上使用註解-->
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--補全項目依賴-->
<!--1:日誌,java日誌:slf4j,log4j,logback,common-logging
使用:slf4j+logBack
-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.5.6</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.1</version>
</dependency>
<!--2:數據庫相關依賴-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!--DAO框架:MyBatis依賴-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
<!--myBatis自身實現的spring整合依賴-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.3</version>
</dependency>
<!--3:Servlet web相關依賴-->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<!--4:spring依賴-->
<!--spring核心依賴-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!--spring dao層依賴-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!--spring web相關依賴-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!--spring test相關依賴-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<!--引入一些工具類-->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2</version>
</dependency>
</dependencies>
<build>
<finalName>seckill</finalName>
</build>
</project>
四.建數據庫
仿java高併發秒殺系列》的視頻,建了兩張表,一張上庫存表,一張上秒殺表,我直接貼sql語句了,比較簡單。
--創建數據庫
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 DEFAULT "2016-05-07 13:28:00",
`end_time` timestamp NOT NULL DEFAULT "2016-05-07 13:28:00",
`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,'2015-11-01 00:00:00','2015-11-02 00:00:00'),
('500元秒殺ipad2',200,'2015-11-01 00:00:00','2015-11-02 00:00:00'),
('300元秒殺小米4',300,'2015-11-01 00:00:00','2015-11-02 00:00:00'),
('200元秒殺紅米note',400,'2015-11-01 00:00:00','2015-11-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 0 COMMENT '狀態標示:-1:無效 0:成功 1:已付款',
`create_time` TIMESTAMP NOT NULL COMMENT '創建時間',
PRIMARY KEY (seckill_id,user_phone),/*聯合主鍵*/
KEY idx_create_time(create_time)
)EnGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='秒殺明細表';
五.DAO層實體編寫和接口編寫
1.創建org.forezp.entity包,根據數據庫字段,編寫實體。
下面是Seckill庫存實體:
public class Seckill {
private long seckillId;
private String name;
private int number;
private Date startTime;
private Date endTime;
private Date createTime;
//這裏省去了寫getter setter方法,在實際項目補上
}
- 創建org.forezp.dao包
編寫Seckill接口
public interface SeckillDao {
//減庫存
int reduceNumber(@Param("seckillId")long seckillId,@Param("killTime")Date killTime);
//根據Id查詢秒殺對象
Seckill queryById(long seckillId);
//根據偏移量查詢秒殺列表
List<Seckill> queryAll(@Param("offset")int offset,@Param("limit")int limit);
採用mapper實現接口
在resources目錄下創建maaper文件夾,所有的接口實現類放在這裏 ,另外項目採用xml的方式實現接口。採用這種方式的好處有很多,比如可以採用包掃描,更少的配置,所有的sql語句都放在這裏,有利於統一規範,代碼的可維護性和可讀性也大大提高。
<?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="org.forezp.dao.SeckillDao">
<update id="reduceNumber">
update
seckill
set
number = number-1
where seckill_id = #{seckillId}
and
start_time <![CDATA[ <= ]]>
#{killTime}
and end_time >= #{killTime}
and number > 0;
</update>
<select id="queryById" resultType="Seckill" parameterType="long">
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 desc
limit #{offset},#{limit}
</select>
</mapper>
六. mybatis的配置
創建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">
<!-- 配置全局屬性 -->
<settings>
<!--使用jdbc的getGeneratedKeys 獲取數據庫的自增主鍵值-->
<setting name="useGeneratedKeys" value="true"/>
<!--使用別名替換列名 默認true
select name as title from table
-->
<setting name="useColumnLabel" value="true"/>
<!--開啓駝峯命名轉換-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
創建jdbc.properties文件
數據庫配置文件和連接數據庫驅動。
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/seckill?useUnicode=true&characterEncoding=utf8
username=root
password=123
七.mybatis和spring 整合
直接貼配置文件,文件已經寫好了註釋。
<?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"
>
<!--配置整合mybatis過程-->
<!--1.配置數據庫相關參數-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--2.配置連接池屬性-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/seckill"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
</bean>
<!--3.配置SqlSessionFactory對象-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入數據庫連接池-->
<property name="dataSource" ref="dataSource"/>
<!--配置mybatis全局配置文件:mybatis-config.xml-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!--掃描entity包,使用別名,多個用;隔開-->
<property name="typeAliasesPackage" value="org.forezp.entity"/>
<!--掃描sql配置文件:mapper需要的xml文件-->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!--4:配置掃描Dao接口包,動態實現DAO接口,注入到spring容器-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入SqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 給出需要掃描的Dao接口-->
<property name="basePackage" value="org.forezp.dao"/>
</bean>
</beans>
就這樣mybatis和spring就整合好了,spring 提供了的ioc容器,爲我們管理bean,我們不需要管理bean的生命週期.
八.單元測試
採用junit單元測試,spring 對junit做了很好的支持。只需要配置註解久可以了,
/**
* 配置spring和junit整合,junit啓動時加載springIOC容器
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:spring/spring-dao.xml"})
public class SeckillDaoTest {
@Test
public void reduceNumber() throws Exception {
Date killTIme=new Date();
int updateCount =seckillDao.reduceNumber(1000L,killTIme);
System.out.println(updateCount);
//結果第一次執行爲1 後面爲0
}
//注入Dao實現類依賴
@Resource
private SeckillDao seckillDao;
@Test
public void queryById() throws Exception {
long id=1001;
Seckill seckill=seckillDao.queryById(id);
System.out.println(seckill.getName());
System.out.println(seckill);
//運行結果
/** 500元秒殺ipad2*/
/** Seckill{seckillId=1001, name='500元秒殺ipad2',number=200, startTime=Sun Nov 01 00:00:00 CST 2015, endTime=Mon Nov 02 00:00:00 CST 2015, createTime=Sun Nov 27 10:44:30 CST 2016}*/
}
@Test
public void queryAll() throws Exception {
//java沒有保存形參的記錄,queryAll(int offeset,int limit)->queryAll(arg0,arg1),通過@param註解來解決
List<Seckill> seckills=seckillDao.queryAll(0,100);
for(Seckill seckill:seckills){
System.out.println(seckill);
}
}
}
到此爲止,mybatis實現數據庫的連接,和dao層代碼的編寫以及mybatis 和spring的整合 。我覺得學習路上雖然很孤單,但如果有一個分享的心態和持續學習的動力,生活也算是充實的,自己成長了,技術也提高了,回報也高了,生活品質也隨之提高。所以無論做什麼,自己快樂,並且能提高自己的快樂,且以此爲目的就夠了,祝自己好運。