本文主要講ssm框架整合EhCache。或許有人會問什么是ehcache。
關於EhCache的介紹和優劣,我想下面的解答足以讓讀者明白:
EhCache 是一個純Java的進程內緩存框架,具有快速、精干等特點,是Hibernate中默認的CacheProvider。Ehcache是一種廣泛使用的開 源Java分布式緩存。主要面向通用緩存,Java EE和輕量級容器。它具有內存和磁盤存儲,緩存加載器,緩存擴展,緩存異常處理程序,一個gzip緩存servlet過濾器,支持REST和SOAP api等特點。
優點:
1. 快速
2. 簡單
3. 多種緩存策略
4. 緩存數據有兩級:內存和磁盤,因此無需擔心容量問題
5. 緩存數據會在虛擬機重啟的過程中寫入磁盤
6. 可以通過RMI、可插入API等方式進行分布式緩存
7. 具有緩存和緩存管理器的偵聽接口
8. 支持多緩存管理器實例,以及一個實例的多個緩存區域
9. 提供Hibernate的緩存實現
缺點:
1. 使用磁盤Cache的時候非常占用磁盤空間:這是因為DiskCache的算法簡單,該算法簡單也導致Cache的效率非常高。它只是對元素直接追加存儲。因此搜索元素的時候非常的快。如果使用DiskCache的,在很頻繁的應用中,很快磁盤會滿。
2. 不能保證數據的安全:當突然kill掉java的時候,可能會產生沖突,EhCache的解決方法是如果文件沖突了,則重建cache。這對於Cache 數據需要保存的時候可能不利。當然,Cache只是簡單的加速,而不能保證數據的安全。如果想保證數據的存儲安全,可以使用Bekeley DB Java Edition版本。這是個嵌入式數據庫。可以確保存儲安全和空間的利用率。
或許還有人很疑惑緩存,什么是緩存?為什么需要緩存?
引用百度百科的回答:
緩存就是數據交換的緩沖區(稱作Cache),當某一硬件要讀取數據時,會首先從緩存中查找需要的數據,如果找到了則直接執行,找不到的話則從內存中找。由於緩存的運行速度比內存快得多,故緩存的作用就是幫助硬件更快地運行。
因為緩存往往使用的是RAM(斷電即掉的非永久儲存),所以在用完后還是會把文件送到硬盤等存儲器里永久存儲。電腦里最大的緩存就是內存條了,最快的是CPU上鑲的L1和L2緩存,顯卡的顯存是給顯卡運算芯片用的緩存,硬盤上也有16M或者32M的緩存。
或許還有人會問內存是什么?
引用百度百科的回答:
內存是計算機中重要的部件之一,它是與CPU進行溝通的橋梁。計算機中所有程序的運行都是在內存中進行的,因此內存的性能對計算機的影響非常大。內存(Memory)也被稱為內存儲器,其作用是用於暫時存放CPU中的運算數據,以及與硬盤等外部存儲器交換的數據。只要計算機在運行中,CPU就會把需要運算的數據調到內存中進行運算,當運算完成后CPU再將結果傳送出來,內存的運行也決定了計算機的穩定運行。 內存是由內存芯片、電路板、金手指等部分組成的。
也許還人會罵我,說你怎么盡引用百度百科。
我的回答是,因為我對此也不知道怎么回答。
如果讓我回答在開發中為什么需要緩存及其緩存的作用,我的回答是,對於有些數據,我只需查詢一遍就可以,不需要再度查詢,因為有緩存。就好比數據庫優化,除了索引之外,還有就是將數據庫里面的數據緩存起來,這樣對於大規模數據,平常需要多次查詢,導致耗費時間很長,性能差,但是我通過緩存,只需查詢一次,當再次查詢時,就非常快,對整個系統的響應和性能也不會有什么影響。當然了,當涉及到緩存的數據與實際數據庫中的數據存在差異時,這里后續會講采取怎樣的方式解決這個問題。
另外建議軟件開發的朋友們,有空多多去熟悉熟悉計算機相關的理論知識。正所謂有句話叫做:萬變不離其宗。這個其宗在計算機中可以理解為算法與數據結構、操作系統、TCP/IP、計算機基礎知識、編譯原理等等。把握好這些,編程之路才能越走越長。
這也是一位朋友對我說的。
下面進入正題,關於SSM框架整合EhCache
sql腳本准備
CREATE TABLE `user` ( `user_id` int(8) NOT NULL AUTO_INCREMENT COMMENT '用戶主鍵', `login_code` varchar(20) NOT NULL COMMENT '用戶編碼(登錄賬戶) 手機號 郵箱號', `user_name` varchar(20) NOT NULL COMMENT '用戶名', `password` varchar(40) NOT NULL COMMENT '密碼', `sex` int(2) NOT NULL COMMENT '性別', `identity_card` varchar(20) DEFAULT NULL COMMENT '身份證', `create_time` datetime NOT NULL COMMENT '創建時間', `create_by` varchar(10) NOT NULL COMMENT '創建人', `update_time` datetime NOT NULL COMMENT '更新時間', `update_by` varchar(10) NOT NULL COMMENT '更新人', `status` int(2) NOT NULL DEFAULT '0' COMMENT '狀態:0注冊新用戶 1郵件認證用戶 2管理員 3黑名單', PRIMARY KEY (`user_id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
一、導入Maven依賴
<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.blog</groupId>
<artifactId>Blog</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<!-- 文件拷貝時的編碼 -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- 編譯時的編碼 -->
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<spring.version>4.3.13.RELEASE</spring.version>
<junit.version>4.12</junit.version>
<druid.version>1.1.0</druid.version>
<fastjson.version>1.2.8</fastjson.version>
<mybaitsplus.version>2.1.8</mybaitsplus.version>
<mysql.version>5.1.38</mysql.version>
<log4j.version>1.2.17</log4j.version>
<slf4j.version>1.7.19</slf4j.version>
<aspectjweaver.version>1.8.8</aspectjweaver.version>
<fileupload.version>1.3.1</fileupload.version>
<jstl.version>1.2</jstl.version>
<commons-io.version>2.5</commons-io.version>
<commons-fileupload.version>1.3.1</commons-fileupload.version>
<ruedigermoeller-fst.version>2.56</ruedigermoeller-fst.version>
<json.version>20170516</json.version>
<dozer.version>5.5.1</dozer.version>
<poi.version>3.14</poi.version>
</properties>
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.46</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
<!-- kisso end -->
<!-- JUnit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<!-- jsp -->
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>compile</scope>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>compile</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- AOP -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectjweaver.version}</version>
</dependency>
<!-- FileUpload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${fileupload.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!-- Mybatis-Plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>${mybaitsplus.version}</version>
</dependency>
<!-- Mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- Druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- FastJson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<!-- Log -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>de.ruedigermoeller</groupId>
<artifactId>fst</artifactId>
<version>${ruedigermoeller-fst.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
<!-- Json in java -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20170516</version>
</dependency>
<!-- Email -->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.2</version>
<scope>provided</scope>
</dependency>
<!-- <dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency> -->
<!-- 條形碼、二維碼生成 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
<!-- User Agent -->
<dependency>
<groupId>eu.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
<version>1.20</version>
</dependency>
<!-- Apache HTTP -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<!-- Jsoup HTTP -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.9.1</version>
</dependency>
<!-- 圖片Meta獲取 -->
<dependency>
<groupId>com.drewnoakes</groupId>
<artifactId>metadata-extractor</artifactId>
<version>2.9.1</version>
</dependency>
<!-- 縮略圖工具 -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
<!-- 圖片驗證碼生成 -->
<dependency>
<groupId>com.bladejava</groupId>
<artifactId>blade-patchca</artifactId>
<version>1.0.5</version>
</dependency>
<!-- jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-xml -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.5</version>
</dependency>
<!-- Java xml -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<!-- XPath xml -->
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.6</version>
</dependency>
<!-- Snake YAML -->
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.17</version>
</dependency>
<!-- Bean To Bean copy -->
<dependency>
<groupId>net.sf.dozer</groupId>
<artifactId>dozer</artifactId>
<version>${dozer.version}</version>
</dependency>
<!-- POI Office Tools -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-codec</artifactId>
<groupId>commons-codec</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>${poi.version}</version>
</dependency>
<!-- pinyin4j -->
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>
<!-- Apache Tools Ant Tar Zip -->
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.9.7</version>
</dependency>
<!-- File MimeType ContentType -->
<dependency>
<groupId>net.sf.jmimemagic</groupId>
<artifactId>jmimemagic</artifactId>
<version>0.1.3</version>
<exclusions>
<exclusion>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
</exclusion>
<exclusion>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-xc</artifactId>
</exclusion>
<exclusion>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
</exclusion>
<exclusion>
<artifactId>log4j</artifactId>
<groupId>log4j</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- swagger -->
<dependency>
<groupId>com.mangofactory</groupId>
<artifactId>swagger-springmvc</artifactId>
<version>1.0.2</version>
</dependency>
<!-- hutool -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- 指定編譯版本 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
<finalName>${project.artifactId}</finalName>
</build>
<repositories>
<repository>
<id>aliyun-repos</id>
<name>Aliyun Repository</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
<releases><enabled>true</enabled></releases>
<snapshots><enabled>false</enabled></snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>aliyun-repos</id>
<name>Aliyun Repository</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
<releases><enabled>true</enabled></releases>
<snapshots><enabled>false</enabled></snapshots>
</pluginRepository>
</pluginRepositories>
</project>
二、編寫實體
package com.blog.entity; import java.io.Serializable; import com.baomidou.mybatisplus.enums.IdType; import java.util.Date; import com.baomidou.mybatisplus.annotations.TableId; import com.baomidou.mybatisplus.annotations.TableName; import com.baomidou.mybatisplus.annotations.TableField; import com.baomidou.mybatisplus.activerecord.Model; import java.io.Serializable; /** * <p> * * </p> * * @author youcong123 * @since 2018-07-22 */ @TableName("user") public class User extends Model<User> { private static final long serialVersionUID = 1L; /** * 用戶主鍵 */ @TableId(value = "user_id", type = IdType.AUTO) private Integer userId; /** * 用戶編碼(登錄賬戶) 手機號 郵箱號 */ @TableField("login_code") private String loginCode; /** * 用戶名 */ @TableField("user_name") private String userName; /** * 密碼 */ private String password; /** * 性別 */ private Integer sex; /** * 身份證 */ @TableField("identity_card") private String identityCard; /** * 創建時間 */ @TableField("create_time") private Date createTime; /** * 創建人 */ @TableField("create_by") private String createBy; /** * 更新時間 */ @TableField("update_time") private Date updateTime; /** * 更新人 */ @TableField("update_by") private String updateBy; /** * 狀態:0注冊新用戶 1郵件認證用戶 2管理員 3黑名單 */ private Integer status; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getLoginCode() { return loginCode; } public void setLoginCode(String loginCode) { this.loginCode = loginCode; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getSex() { return sex; } public void setSex(Integer sex) { this.sex = sex; } public String getIdentityCard() { return identityCard; } public void setIdentityCard(String identityCard) { this.identityCard = identityCard; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getCreateBy() { return createBy; } public void setCreateBy(String createBy) { this.createBy = createBy; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getUpdateBy() { return updateBy; } public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } @Override protected Serializable pkVal() { return this.userId; } @Override public String toString() { return "User{" + "userId=" + userId + ", loginCode=" + loginCode + ", userName=" + userName + ", password=" + password + ", sex=" + sex + ", identityCard=" + identityCard + ", createTime=" + createTime + ", createBy=" + createBy + ", updateTime=" + updateTime + ", updateBy=" + updateBy + ", status=" + status + "}"; } }
三、編寫DAO
package com.blog.mapper;
import com.blog.entity.User;
import com.baomidou.mybatisplus.mapper.BaseMapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author youcong123
* @since 2018-07-22
*/
public interface UserDao extends BaseMapper<User> {
}
四、編寫業務接口類
package com.blog.service;
import com.blog.entity.User;
import com.baomidou.mybatisplus.service.IService;
/**
* <p>
* 服務類
* </p>
*
* @author youcong123
* @since 2018-07-22
*/
public interface UserService extends IService<User> {
User getUserById(String userId);
User login(String loginCode);
}
五、編寫業務接口實現類
package com.blog.service.impl;
import com.blog.entity.User;
import com.blog.mapper.UserDao;
import com.blog.service.UserService;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
/**
* <p>
* 服務實現類
* </p>
*
* @author youcong123
* @since 2018-07-22
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {
@Autowired
private UserDao userDao;
@Override
@Cacheable(value="cacheTest")
public User getUserById(String userId) {
return userDao.selectById(userId);
}
@Override
public User login(String loginCode) {
User user = new User();
user.setLoginCode(loginCode);
return userDao.selectOne(user);
}
}
六、編寫Controller
package com.blog.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.blog.entity.User;
import com.blog.service.UserService;
import cn.hutool.json.JSONObject;
/**
* <p>
* 前端控制器
* </p>
*
* @author youcong123
* @since 2018-07-22
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping(value="getById",produces="application/json;charset=utf-8")
public Object getById(String userId) {
JSONObject json = new JSONObject();
User user = userService.getUserById(userId);
json.put("user", user);
return user;
}
}
七、編寫DAO對應的XML
UserDao.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.blog.mapper.UserDao">
<!-- 通用查詢映射結果 -->
<resultMap id="BaseResultMap" type="com.blog.entity.User">
<id column="user_id" property="userId" />
<result column="login_code" property="loginCode" />
<result column="user_name" property="userName" />
<result column="password" property="password" />
<result column="sex" property="sex" />
<result column="identity_card" property="identityCard" />
<result column="create_time" property="createTime" />
<result column="create_by" property="createBy" />
<result column="update_time" property="updateTime" />
<result column="update_by" property="updateBy" />
<result column="status" property="status" />
</resultMap>
<!-- 通用查詢結果列 -->
<sql id="Base_Column_List">
user_id AS userId, login_code AS loginCode, user_name AS userName, password, sex, identity_card AS identityCard, create_time AS createTime, create_by AS createBy, update_time AS updateTime, update_by AS updateBy, status
</sql>
</mapper>
八、編寫配置文件
spring.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" xmlns:util="http://www.springframework.org/schema/util" 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 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> <!-- 引入屬性文件 --> <context:property-placeholder location="classpath:config.properties"/> <!-- Service包(自動注入) --> <context:component-scan base-package="com.blog.service"/> <import resource="classpath:spring/spring-mybatis.xml"/> </beans>
spring-mybatis.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<!-- 應用spring-cache注解功能 -->
<cache:annotation-driven cache-manager="cacheManager" />
<!-- 配置數據源 -->
<bean name="defaultDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc_url}"/>
<property name="username" value="${jdbc_username}"/>
<property name="password" value="${jdbc_password}"/>
<!-- 初始化連接大小 -->
<property name="initialSize" value="0"/>
<!-- 連接池最大使用連接數量 -->
<property name="maxActive" value="20"/>
<!-- 連接池最大空閑 -->
<property name="maxIdle" value="20"/>
<!-- 連接池最小空閑 -->
<property name="minIdle" value="0"/>
<!-- 獲取連接最大等待時間 -->
<property name="maxWait" value="60000"/>
<property name="validationQuery" value="${validationQuery}"/>
<property name="testOnBorrow" value="false"/>
<property name="testOnReturn" value="false"/>
<property name="testWhileIdle" value="true"/>
<!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000"/>
<!-- 配置一個連接在池中最小生存的時間,單位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="25200000"/>
<!-- 打開removeAbandoned功能 -->
<property name="removeAbandoned" value="true"/>
<!-- 1800秒,也就是30分鍾 -->
<property name="removeAbandonedTimeout" value="1800"/>
<!-- 關閉abanded連接時輸出錯誤日志 -->
<property name="logAbandoned" value="true"/>
<!-- 監控數據庫 -->
<property name="filters" value="mergeStat"/>
</bean>
<bean id="druidDynamicDataSource" class="com.blog.datasource.DruidDynamicDataSource">
<property name="defaultTargetDataSource" ref="defaultDataSource" />
<property name="targetDataSources">
<map>
<entry key="defaultDataSource" value-ref="defaultDataSource"/>
<!-- 這里還可以加多個dataSource -->
</map>
</property>
</bean>
<!-- Spring整合Mybatis,更多查看文檔:http://mp.baomidou.com -->
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
<property name="dataSource" ref="druidDynamicDataSource" />
<!-- 自動掃描Mapping.xml文件 -->
<property name="mapperLocations" value="classpath:mybatis/system/*.xml"/>
<property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/>
<property name="typeAliasesPackage" value="com.blog.entity"/>
<property name="plugins">
<array>
<!-- 分頁插件配置 -->
<bean id="paginationInterceptor" class="com.baomidou.mybatisplus.plugins.PaginationInterceptor">
</bean>
</array>
</property>
<!-- 全局配置注入 -->
<property name="globalConfig" ref="globalConfig" />
</bean>
<bean id="globalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
<!--
AUTO->`0`("數據庫ID自增")
INPUT->`1`(用戶輸入ID")
ID_WORKER->`2`("全局唯一ID")
UUID->`3`("全局唯一ID")
-->
<property name="idType" value="2" />
<!--
MYSQL->`mysql`
ORACLE->`oracle`
DB2->`db2`
H2->`h2`
HSQL->`hsql`
SQLITE->`sqlite`
POSTGRE->`postgresql`
SQLSERVER2005->`sqlserver2005`
SQLSERVER->`sqlserver`
-->
<!-- Oracle需要添加該項 -->
<!-- <property name="dbType" value="oracle" /> -->
<!-- 全局表為下划線命名設置 true -->
<!-- <property name="dbColumnUnderline" value="true" /> -->
<!-- <property name="metaObjectHandler">
<bean class="com.lms.common.MyMetaObjectHandler" />
</property> -->
</bean>
<!-- MyBatis 動態掃描 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.blog.mapper"/>
</bean>
<!-- 配置事務管理 -->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="druidDynamicDataSource"/>
</bean>
<!-- 事務管理 屬性 -->
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="append*" propagation="REQUIRED"/>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="modify*" propagation="REQUIRED"/>
<tx:method name="edit*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="remove*" propagation="REQUIRED"/>
<tx:method name="repair" propagation="REQUIRED"/>
<tx:method name="get*" propagation="REQUIRED" read-only="true"/>
<tx:method name="find*" propagation="REQUIRED" read-only="true"/>
<tx:method name="load*" propagation="REQUIRED" read-only="true"/>
<tx:method name="search*" propagation="REQUIRED" read-only="true"/>
<tx:method name="datagrid*" propagation="REQUIRED" read-only="true"/>
<tx:method name="*" propagation="REQUIRED" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 配置切面 -->
<aop:config>
<aop:pointcut id="transactionPointcut" expression="execution(* com.blog.service..*.*(..))"/>
<aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice"/>
</aop:config>
<!-- 配置ehcache管理器-->
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehcache"></property>
</bean>
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache-setting.xml"></property>
</bean>
</beans>
spring-mvc.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" xmlns:mvc="http://www.springframework.org/schema/mvc" 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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- Controller包(自動注入) --> <context:component-scan base-package="com.blog.controller"/> <mvc:default-servlet-handler/> <!-- FastJson注入 --> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 上傳限制 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 上傳文件大小限制為31M,31*1024*1024 --> <property name="maxUploadSize" value="32505856"/> </bean> </beans>
config.properties
validationQuery=SELECT 1 jdbc_url=jdbc:mysql://localhost:3306/blog_test?useUnicode=true&characterEncoding=UTF-8 jdbc_username=root jdbc_password=1234
ehcache-setting.xml
<?xml version="1.0" encoding="UTF-8"?> <ehcache> <!-- 指定一個文件目錄,當EhCache把數據寫到硬盤上時,將把數據寫到這個文件目錄下 --> <!-- <diskStore path="D://cache//java-cache"/> --> <diskStore path="java.io.tmpdir"/> <!-- 設定緩存的默認數據過期策略 --> <defaultCache maxElementsInMemory="10000" eternal="false" overflowToDisk="true" timeToIdleSeconds="10" timeToLiveSeconds="20" diskPersistent="false" diskExpiryThreadIntervalSeconds="120"/> <cache name="cacheTest" maxElementsInMemory="1000" eternal="false" overflowToDisk="true" timeToIdleSeconds="100" timeToLiveSeconds="200"/> </ehcache>
關於diskstore配置說明:
1、diskStore元素是可選的,非必須的。如果不使用磁盤存儲,只需要將diskStore注釋掉即可;如果使用,需要在ehcache.xml文件中的ehcahce元素下的定義一個diskStore元素並指定其path屬性。
2、由diskStore元素是定義在ehcache元素下我們看出diskStore在CacheManager范圍內是共享的,其是線程安全的
3、對於任何緩存,如果你已經激活了overflowToDisk或diskPersistent,就要配置磁盤存儲器。
(關於overflowToDisk或diskPersistent的配置,詳見配置文件ehcache.xml詳解(1) )
4、DiskStore中驅除元素跟MemoryStore中驅除元素的規則是不一樣的。當往DiskStore中添加元素且此時DiskStore中的容量已經超出限制時將采用LFU(最不常用)驅除規則將對應的元素進行刪除,而且該驅除規則是不可配置的(通過cache中的diskExpiryThreadIntervalSeconds屬性完成)
5、path屬性如果是下述Java系統屬性之一,他將會被運行中的VM中的值替換。為了向后兼容,這些應該被特別規定,而不會被${token}替換語法封閉。
6、path屬性可以配置的目錄有:
user.home(用戶的家目錄)
user.dir(用戶當前的工作目錄)
java.io.tmpdir(默認的臨時目錄)
ehcache.disk.store.dir(ehcache的配置目錄)
絕對路徑(如:d://javastore)
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL Map Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!-- | plugins在配置文件中的位置必須符合要求,否則會報錯,順序如下: | properties?, settings?, | typeAliases?, typeHandlers?, | objectFactory?,objectWrapperFactory?, | plugins?, | environments?, databaseIdProvider?, mappers? |--> <configuration> <!-- | 全局配置設置 | | 可配置選項 默認值, 描述 | | aggressiveLazyLoading true, 當設置為‘true’的時候,懶加載的對象可能被任何懶屬性全部加載。否則,每個屬性都按需加載。 | multipleResultSetsEnabled true, 允許和不允許單條語句返回多個數據集(取決於驅動需求) | useColumnLabel true, 使用列標簽代替列名稱。不同的驅動器有不同的作法。參考一下驅動器文檔,或者用這兩個不同的選項進行測試一下。 | useGeneratedKeys false, 允許JDBC 生成主鍵。需要驅動器支持。如果設為了true,這個設置將強制使用被生成的主鍵,有一些驅動器不兼容不過仍然可以執行。 | autoMappingBehavior PARTIAL, 指定MyBatis 是否並且如何來自動映射數據表字段與對象的屬性。PARTIAL將只自動映射簡單的,沒有嵌套的結果。FULL 將自動映射所有復雜的結果。 | defaultExecutorType SIMPLE, 配置和設定執行器,SIMPLE 執行器執行其它語句。REUSE 執行器可能重復使用prepared statements 語句,BATCH執行器可以重復執行語句和批量更新。 | defaultStatementTimeout null, 設置一個時限,以決定讓驅動器等待數據庫回應的多長時間為超時 | --> <settings> <!-- 這個配置使全局的映射器啟用或禁用緩存 --> <setting name="cacheEnabled" value="true"/> <!-- 全局啟用或禁用延遲加載。當禁用時,所有關聯對象都會即時加載 --> <setting name="lazyLoadingEnabled" value="true"/> <setting name="multipleResultSetsEnabled" value="true"/> <setting name="useColumnLabel" value="true"/> <setting name="defaultExecutorType" value="REUSE"/> <setting name="defaultStatementTimeout" value="25000"/> </settings> <plugins> <!-- SQL 執行分析攔截器 stopProceed 發現全表執行 delete update 是否停止運行 --> <plugin interceptor="com.baomidou.mybatisplus.plugins.SqlExplainInterceptor"> <property name="stopProceed" value="false" /> </plugin> <!-- SQL 執行性能分析,開發環境使用,線上不推薦。 maxTime 指的是 sql 最大執行時長 --> <plugin interceptor="com.baomidou.mybatisplus.plugins.PerformanceInterceptor"> <property name="maxTime" value="100" /> <!--SQL是否格式化 默認false--> <property name="format" value="true" /> </plugin> </plugins> </configuration>
log4j.properties
#config root logger
log4j.rootLogger = INFO,system.out
log4j.appender.system.out=org.apache.log4j.ConsoleAppender
log4j.appender.system.out.layout=org.apache.log4j.PatternLayout
log4j.appender.system.out.layout.ConversionPattern=[Log]%-d{yyyy-MM-dd HH:mm:ss} %5p[%F:%L]:%m%n
#log4j.appender.system.out.layout.ConversionPattern=[Log] %5p[%F:%L]:%m%n
#config this Project.file logger
log4j.logger.thisProject.file=INFO,thisProject.file.out
log4j.appender.thisProject.file.out=org.apache.log4j.DailyRollingFileAppender
log4j.appender.thisProject.file.out.File=pmslogout.log
log4j.appender.thisProject.file.out.layout=org.apache.log4j.PatternLayout
log4j.appender.thisProject.file.out.layout.ConversionPattern=[Log]%-d{yyyy-MM-dd HH:mm:ss} %5p[%F:%L]:%m%n
log4j.appender.thisProject.file.append=true
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>Blog</display-name> <!-- 歡迎頁 --> <welcome-file-list> <welcome-file>views/login.html</welcome-file> </welcome-file-list> <!-- 加載配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring.xml</param-value> </context-param> <!-- 字符過濾器 攔截所有 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 上下文監聽 --> <listener> <description>Spring監聽器</description> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 前端控制器 攔截 --> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <description>SpringMVC</description> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- session過期時間 --> <session-config> <session-timeout>30</session-timeout> </session-config> </web-app>
九、運行項目,如果控制台五報錯,就通過PostMan接口測試
PostMan可運行多次 發現控制台始終都只打印一次就表示緩存成功


