一寓涨、Mybatis介紹
MyBatis是一個支持普通SQL查詢吼句,存儲過程和高級映射的優(yōu)秀持久層框架先煎。MyBatis消除了幾乎所有的JDBC代碼和參數(shù)的手工設(shè)置以及對結(jié)果集的檢索封裝肩狂。MyBatis可以使用簡單的XML或注解用于配置和原始映射套么,將接口和Java的POJO(Plain Old Java Objects饼酿,普通的Java對象)映射成數(shù)據(jù)庫中的記錄帮毁。
二铭乾、準(zhǔn)備環(huán)境
1 創(chuàng)建用戶表
-- 創(chuàng)建用戶表
CREATE TABLE `user_info` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '用戶id',
`user_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '用戶名',
`password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '密碼',
`phone` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '手機(jī)',
`icon` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '頭像鏈接地址',
`sex` int(5) NOT NULL DEFAULT '3' COMMENT '性別: 1 男汛蝙,2 女烈涮, 3 保密',
`age` int(5) NOT NULL DEFAULT '0' COMMENT '年齡',
`birthday` bigint(15) DEFAULT '0' COMMENT '出生年月',
`create_time` bigint(15) NOT NULL DEFAULT '0' COMMENT '創(chuàng)建時間',
`update_time` bigint(15) NOT NULL DEFAULT '0' COMMENT '更新時間',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE KEY `index_name` (`user_name`) USING BTREE COMMENT '用戶名唯一索引',
KEY `index_phone` (`phone`) USING BTREE COMMENT '手機(jī)號索引'
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci ROW_FORMAT=DYNAMIC COMMENT='用戶表';
-- 插入數(shù)據(jù)
INSERT INTO `demo`.`user_info`(`user_name`, `password`, `phone`, `icon`, `sex`, `age`, `birthday`, `create_time`, `update_time`) VALUES ('test01', 'test01', '15810101010', '', 3, 0, 1577460560869, 1577460560869, 1577460560869);
2 添加jar包
<!--組件引用-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
</dependency>
<!--添加spring boot mybatis依賴-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<!--添加數(shù)據(jù)庫連接池依賴-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.21</version>
</dependency>
<!--添加數(shù)據(jù)庫依賴-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
三、使用Mybatis查詢數(shù)據(jù)
1.在yml配置文件中添加mybatis配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/demo?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
username: demo
password: demo
driver-class-name: com.mysql.cj.jdbc.Driver
druid:
initial-size: 5 # 初始化大小
min-idle: 5 # 最小
max-active: 100 # 最大
max-wait: 60000 # 連接超時時間
time-between-eviction-runs-millis: 60000 # 配置間隔多久才進(jìn)行一次檢測窖剑,檢測需要關(guān)閉的空閑連接坚洽,單位是毫秒
min-evictable-idle-time-millis: 300000 # 指定一個空閑連接最少空閑多久后可被清除,單位是毫秒
validationQuery: select 'x'
test-while-idle: true # 當(dāng)連接空閑時西土,是否執(zhí)行連接測試
test-on-borrow: false # 當(dāng)從連接池借用連接時讶舰,是否測試該連接
test-on-return: false # 在連接歸還到連接池時是否測試該連接
filters: config,wall,stat # 配置監(jiān)控統(tǒng)計攔截的filters,去掉后監(jiān)控界面sql無法統(tǒng)計需了,'wall'用于防火墻
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
maxOpenPreparedStatements: 20
connectionProperties: druid.stat.slowSqlMillis=200;druid.stat.logSlowSql=true
web-stat-filter:
enabled: true
url-pattern: /*
exclusions: /druid/*,*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico
session-stat-enable: true
session-stat-max-count: 10
stat-view-servlet:
enabled: true
url-pattern: /druid/*
reset-enable: true
login-username: admin
login-password: admin
filter:
slf4j:
statement-log-enabled: true
#配置mapper xml 文件路徑跳昼,即在resources目錄下創(chuàng)建mapper文件夾
mybatis:
mapper-locations: /mapper/*.xml
#開啟打印sql語句
logging:
level:
com.gqlofe.userinfo.dao: debug
2.通過mybatis generator 生成實體類和mapper,以及xml
實體類
@Data
public class UserInfo implements Serializable {
// 用戶id
private Integer id;
// 用戶名
private String userName;
// 密碼
private String password;
// 手機(jī)
private String phone;
// 頭像鏈接地址
private String icon;
// 性別: 1 男肋乍,2 女鹅颊, 3 保密
private Integer sex;
// 年齡
private Integer age;
// 出生年月
private Long birthday;
// 創(chuàng)建時間
private Long createTime;
// 更新時間
private Long updateTime;
private static final long serialVersionUID = 1L;
}
生成mapper類,注意 @Mapper
注解 是mybatis的框架的注解墓造,需要手動加上
@Mapper
public interface UserInfoMapper {
int deleteByPrimaryKey(Integer id);
int insert(UserInfo record);
int insertSelective(UserInfo record);
UserInfo selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(UserInfo record);
int updateByPrimaryKey(UserInfo record);
UserInfo selectByNamePwd(@Param("userName") String userName, @Param("password") String password);
UserInfo getUser(UserInfo query);
}
生成的UserInfoMapper.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.gqlofe.userinfo.dao.mapper.UserInfoMapper">
<resultMap id="BaseResultMap" type="com.gqlofe.userinfo.bean.entity.UserInfo">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="user_name" jdbcType="VARCHAR" property="userName" />
<result column="password" jdbcType="VARCHAR" property="password" />
<result column="phone" jdbcType="VARCHAR" property="phone" />
<result column="icon" jdbcType="VARCHAR" property="icon" />
<result column="sex" jdbcType="INTEGER" property="sex" />
<result column="age" jdbcType="INTEGER" property="age" />
<result column="birthday" jdbcType="BIGINT" property="birthday" />
<result column="create_time" jdbcType="BIGINT" property="createTime" />
<result column="update_time" jdbcType="BIGINT" property="updateTime" />
</resultMap>
<sql id="Base_Column_List">
id, user_name, password, phone, icon, sex, age, birthday, create_time, update_time
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user_info
where id = #{id,jdbcType=INTEGER}
</select>
<!--通過用戶名和密碼查詢-->
<select id="selectByNamePwd" resultType="com.gqlofe.userinfo.bean.entity.UserInfo">
select
<include refid="Base_Column_List" />
from user_info
where user_name = #{userName} and password = #{password}
</select>
<!--通過用戶名或手機(jī)號查詢-->
<select id="getUser" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user_info
where 1 = 1
<if test="userName">
and user_name = #{userName}
</if>
<if test="phone">
and phone = #{phone}
</if>
and password = #{password}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from user_info
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.gqlofe.userinfo.bean.entity.UserInfo" keyProperty="id" useGeneratedKeys="true">
insert into user_info (id, user_name, password,
phone, icon, sex, age,
birthday, create_time, update_time
)
values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{phone,jdbcType=VARCHAR}, #{icon,jdbcType=VARCHAR}, #{sex,jdbcType=INTEGER}, #{age,jdbcType=INTEGER},
#{birthday,jdbcType=BIGINT}, #{createTime,jdbcType=BIGINT}, #{updateTime,jdbcType=BIGINT}
)
</insert>
<insert id="insertSelective" parameterType="com.gqlofe.userinfo.bean.entity.UserInfo" useGeneratedKeys="true" keyProperty="id">
insert into user_info
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="userName != null">
user_name,
</if>
<if test="password != null">
password,
</if>
<if test="phone != null">
phone,
</if>
<if test="icon != null">
icon,
</if>
<if test="sex != null">
sex,
</if>
<if test="age != null">
age,
</if>
<if test="birthday != null">
birthday,
</if>
<if test="createTime != null">
create_time,
</if>
<if test="updateTime != null">
update_time,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="userName != null">
#{userName,jdbcType=VARCHAR},
</if>
<if test="password != null">
#{password,jdbcType=VARCHAR},
</if>
<if test="phone != null">
#{phone,jdbcType=VARCHAR},
</if>
<if test="icon != null">
#{icon,jdbcType=VARCHAR},
</if>
<if test="sex != null">
#{sex,jdbcType=INTEGER},
</if>
<if test="age != null">
#{age,jdbcType=INTEGER},
</if>
<if test="birthday != null">
#{birthday,jdbcType=BIGINT},
</if>
<if test="createTime != null">
#{createTime,jdbcType=BIGINT},
</if>
<if test="updateTime != null">
#{updateTime,jdbcType=BIGINT},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.gqlofe.userinfo.bean.entity.UserInfo">
update user_info
<set>
<if test="userName != null">
user_name = #{userName,jdbcType=VARCHAR},
</if>
<if test="password != null">
password = #{password,jdbcType=VARCHAR},
</if>
<if test="phone != null">
phone = #{phone,jdbcType=VARCHAR},
</if>
<if test="icon != null">
icon = #{icon,jdbcType=VARCHAR},
</if>
<if test="sex != null">
sex = #{sex,jdbcType=INTEGER},
</if>
<if test="age != null">
age = #{age,jdbcType=INTEGER},
</if>
<if test="birthday != null">
birthday = #{birthday,jdbcType=BIGINT},
</if>
<if test="createTime != null">
create_time = #{createTime,jdbcType=BIGINT},
</if>
<if test="updateTime != null">
update_time = #{updateTime,jdbcType=BIGINT},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.gqlofe.userinfo.bean.entity.UserInfo">
update user_info
set user_name = #{userName,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
phone = #{phone,jdbcType=VARCHAR},
icon = #{icon,jdbcType=VARCHAR},
sex = #{sex,jdbcType=INTEGER},
age = #{age,jdbcType=INTEGER},
birthday = #{birthday,jdbcType=BIGINT},
create_time = #{createTime,jdbcType=BIGINT},
update_time = #{updateTime,jdbcType=BIGINT}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
3.基本增刪改查
1.查詢
@Autowired
private UserInfoMapper userInfoMapper;
@Test
public void selectUserInfo() {
UserInfo userInfo = userInfoMapper.selectByPrimaryKey(6);
System.out.println(userInfo);
}
查詢結(jié)果:
image.png
可以看到執(zhí)行的sql語句也打印了堪伍,數(shù)據(jù)也查出來了。
2.插入
@Test
public void addUserInfo() {
long now = System.currentTimeMillis();
UserInfo userInfo = new UserInfo();
userInfo.setUserName("test02").setPassword("test02").setPhone("15811111111")
.setIcon("").setSex(1).setAge(10).setBirthday(now)
.setCreateTime(now).setUpdateTime(now);
int insert = userInfoMapper.insert(userInfo);
System.out.println("insert = " + insert);
查詢結(jié)果:
image.png
image.png
可以看到數(shù)據(jù)庫多了一條記錄.
3.更新
@Test
public void updateUserInfo() {
long now = System.currentTimeMillis();
UserInfo userInfo = new UserInfo();
userInfo.setId(12).setPhone("15800000000").setUpdateTime(now);
int i = userInfoMapper.updateByPrimaryKeySelective(userInfo);
System.out.println("i = " + i);
}
更新結(jié)果:
image.png
image.png
4.刪除
@Test
public void deleteUserInfo() {
int i = userInfoMapper.deleteByPrimaryKey(12);
System.out.println("i = " + i);
}
刪除結(jié)果:
image.png
image.png
可以看到已經(jīng)被刪除了觅闽。
4.基于注解的增刪改查
使用注解方式帝雇,就需要將對應(yīng)的xml去掉
@Mapper
public interface UserInfoMapper {
int deleteByPrimaryKey(Integer id);
@Insert("insert into user_info (id, user_name, password, phone, icon, sex, age, birthday, create_time, update_time)values (#{id}, #{userName}, #{password}, #{phone}, #{icon}, #{sex}, #{age}, #{birthday}, #{createTime}, #{updateTime})")
int insert(UserInfo record);
int insertSelective(UserInfo record);
@Select("select * from user_info where id = #{id}")
UserInfo selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(UserInfo record);
int updateByPrimaryKey(UserInfo record);
UserInfo selectByNamePwd(@Param("userName") String userName, @Param("password") String password);
UserInfo getUser(UserInfo query);
}
經(jīng)過測試結(jié)果同上。