1、Mybatis 簡介
MyBatis
支持定製化 SQL、存儲過程以及高級映射,避免了 JDBC 代碼和手動設置參數以及結果集的獲取,使用簡單的 XML 或註解來配置和映射原生信息,在國內mybatis的使用率很高,前面提到的jpa在國外使用較高一些
2、添加依賴
在
pom.xml
中添加mybatis-spring-boot-starter
的依賴,添加 mysql 的依賴
<!-- mybatis包 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!-- MYSQL包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
3、配置數據源,連接數據庫
在
application.properties
中添加如下配置,連接數據庫以及mybatis的相關設置
spring.datasource.url=jdbc:mysql://localhost:3306/wzp?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false
spring.datasource.password=root
spring.datasource.username=root
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.wzp.wzx.*
# 駝峯命名規範 如:數據庫字段是 order_id 那麼 實體字段就要寫成 orderId
mybatis.configuration.map-underscore-to-camel-case=true
4、構建一張數據表,用於測試
DROP TABLE IF EXISTS `admin`;
CREATE TABLE `admin` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
`uid` int(11) NULL DEFAULT NULL,
`username` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '用戶名',
`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL COMMENT '密碼',
`age` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
`sex` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
`tel` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
`email` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 58 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;
5、構建實體類
package com.wzp.wzx.admin.entity;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import java.io.Serializable;
@Entity
@Getter
@Setter
public class Admin implements Serializable {
private static final long serialVersionUID = -1493660405397259028L;
private Integer id;
private Integer uid;
private String username;
private String password;
private String age;
private String sex;
private String tel;
private String email;
}
6、構建mapper層
package com.wzp.wzx.admin.mapper;
import com.wzp.wzx.admin.entity.Admin;
import org.apache.ibatis.annotations.*;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import java.util.HashMap;
import java.util.List;
@Mapper
public interface AdminMapper {
/**
* 增加數據
* 基於mybatis3.x版本後提供的註解方式 同理它還有@Update、@Delete、@Insert等等一系列註解
*
* @param admin
* @return
*/
@CacheEvict(value = "admin", allEntries = true)
@Insert("insert into Admin(uid,username,password,age,sex,tel,email) VALUES (#{uid},#{username},#{password},#{age},#{sex},#{tel},#{email})")
Admin save(Admin admin);
/**
* 根據id刪除
*
* @param id
*/
@CacheEvict(value = "admin", allEntries = true)
@Delete("delete from Admin where id=#{id}")
int deleteById(int id);
/**
* 根據id進行信息修改
*
* @param admin
* @return
*/
@CacheEvict(value = "admin", allEntries = true)
@Update("update Admin set uid=#{uid},username=#{username},password=#{password},age=#{age},sex=#{sex},tel=#{tel},email=#{email} where id=#{id}")
Admin update(Admin admin);
/**
* 根據id查詢
*
* @param id
* @return
*/
@Cacheable(value = "admin")
@Select("select * from Admin where id = #{id}")
Admin findById(Integer id);
/**
* 查找所有
*
* @return
*/
@Cacheable(value = "admin")
@Select("select * from Admin")
List<Admin> findAll();
/**
* 早期寫法,將SQL寫在 XML 中 示例往後看
*
* @param
* @param
* @param
* @return
*/
/*int insert1(Admin admin);
int insert2(Admin admin);
int deleteById1(Integer id);
int updateById1(Admin admin);
int updateById2(Admin admin);
Admin findById1(Integer id);
List<User> findAllUser();*/
@Cacheable(value = "admin")
List<Admin>findAllBySome(HashMap map);
}
xml 文件 sql 示例
<!-- 條件查詢 -->
<select id="findAllBySome" parameterType="hashmap" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from Admin
where 1=1
<if test="uid != null and uid != '' ">
AND uid Like CONCAT(CONCAT('%',#{uid, jdbcType=INTEGER},'%'))
</if>
<if test="username != null and username != ''">
AND username Like CONCAT(CONCAT('%',#{username, jdbcType=VARCHAR},'%'))
</if>
<if test="age != null and age != '' ">
AND age Like CONCAT(CONCAT('%',#{age, jdbcType=VARCHAR},'%'))
</if>
<if test="sex != null and sex != '' ">
AND sex Like CONCAT(CONCAT('%',#{sex, jdbcType=VARCHAR},'%'))
</if>
<if test="tel != null and tel != '' ">
AND tel Like CONCAT(CONCAT('%',#{tel, jdbcType=VARCHAR},'%'))
</if>
<if test="email != null and email != '' ">
AND email Like CONCAT(CONCAT('%',#{email, jdbcType=VARCHAR},'%'))
</if>
</select>
7、來個Controller層,測試走一波
package com.wzp.wzx.admin.controller;
import com.github.pagehelper.PageInfo;
import com.wzp.wzx.admin.entity.Admin;
import com.wzp.wzx.admin.mapper.AdminMapper;
import com.wzp.wzx.config.BaseController;
import com.wzp.wzx.config.MD5Util;
import com.wzp.wzx.config.Result;
import com.wzp.wzx.enums.ErrorCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
@RestController
@CrossOrigin
@RequestMapping("/admin")
@Api(description = "後臺相關管理接口")
public class AdminController extends BaseController {
@Autowired
private AdminMapper AdminMapper;
@PostMapping("/findAll")
public Result findAll(@RequestBody Map<String, String> parameters) {
if (!hasParameter(parameters, "pageNumber") || !hasParameter(parameters, "pageSize") || !hasParameter(parameters, "propertiesAndSort")) {
return Result.error(ErrorCodeEnum.MISSING_REQUIRED_ARGUMENTS);
}
pageRequest(parameters);
HashMap<String, Object> map = new HashMap();
if (hasParameter(parameters, "uid")) {
map.put("uid", Integer.valueOf(parameters.get("uid")));
}
if (hasParameter(parameters, "username")) {
map.put("username", parameters.get("username"));
}
if (hasParameter(parameters, "age")) {
map.put("age", parameters.get("age"));
}
if (hasParameter(parameters, "sex")) {
map.put("sex", parameters.get("sex"));
}
if (hasParameter(parameters, "tel")) {
map.put("tel", parameters.get("tel"));
}
if (hasParameter(parameters, "email")) {
map.put("email", parameters.get("email"));
}
PageInfo<Admin> tb_user = new PageInfo<>(this.AdminMapper.findAllBySome(map));
return Result.ok(tb_user);
}
}
測試結果就不寫了,就那麼回事,有興趣的可以自己測測,當然,這裏面涉及到很多我自己封裝的東西,這裏就不貼出來了,佔地方......
8、結語
按照慣例寫個結語,嗯...看了很多大佬的教程,結合我自己的總結了一波,當然了,不足之處請多包涵,也請多指教...如有雷同,也請多包涵......
注:如有需要,可自行轉載,但是要加上原創作者及原文章鏈接哦...