文章目录
1、搭建案例测试环境
1.1 创建数据库与数据表
在MySQL中创建数据表t_user,具体如下:
CREATE TABLE `t_user` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`user_name` varchar(60) NOT NULL DEFAULT '',
`sex` varchar(3) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '1',
`note` varchar(256) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
1.2 添加依赖
在pom文件中添加MySQL数据库连接驱动类依赖、DBCP相关依赖、MyBatis相关依赖、Redis相关依赖和Jedis相关依赖,并配置build标签使得xml文件有效。具体如下:
<dependencies>
<!--MySQL数据库连接驱动类-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--引入第三方数据源DBCP依赖-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
</dependency>
<!--MyBatis相关依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!--Redis相关依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<!--不依赖Redis的异步客户端lettuce -->
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--引入Redis的客户端驱动jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>${basedir}/src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
1.3 创建用户POJO
首先在enumration包下创建性别枚举类SexEnum,具体如下:
package com.ccff.springboot.demo.chapter7_2.enumration;
/**
* Created by wangzhefeng01 on 2019/8/12.
*/
public enum SexEnum {
MALE(1,"男"),
FEMALE(2,"女");
private Integer id;
private String value;
SexEnum(Integer id, String value) {
this.id = id;
this.value = value;
}
public static SexEnum getSexEnumById(Integer id){
for (SexEnum sex : SexEnum.values()) {
if (sex.getId() == id){
return sex;
}
}
return null;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
然后在pojo包下创建名为User的POJO类,具体如下:
package com.ccff.springboot.demo.chapter7_2.pojo;
import com.ccff.springboot.demo.chapter7_2.enumration.SexEnum;
import org.apache.ibatis.type.Alias;
import java.io.Serializable;
/**
* Created by wangzhefeng01 on 2019/8/12.
*/
@Alias(value = "user") //定义MyBatis的别名
public class User implements Serializable{
private static final long serialVersionUID = 7760614561073458247L;
private Long id = null;
private String userName = null;
private SexEnum sex = SexEnum.MALE;
private String note = null;
public User() {
}
public User(Long id, String userName, SexEnum sex, String note) {
this.id = id;
this.userName = userName;
this.sex = sex;
this.note = note;
}
public User(String userName, String note)