MyBatis初级实战之二:增删改查

本文介绍了如何使用MyBatis进行增删改查操作,包括日志表和用户表的实体类、mapper映射文件、mapper接口、service层以及controller层的实现。还展示了单元测试代码,涵盖了新增、查询和删除操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

private Integer userId;

@ApiModelProperty(value = “日志内容”)

private String action;

@ApiModelProperty(value = “创建时间”)

private Date createTime;

@Override

public String toString() {

return “Log{” +

“id=” + id +

“, userId=” + userId +

“, action=’” + action + ‘’’ +

“, createTime=” + createTime +

‘}’;

}

// 省去get和set方法,请您自行补齐

}

  1. 为联表查询的结果准备一个bean,名为LogExtend.java,继承自Log.java,自己只有个userName字段,对应联表查询user表的name字段:

package com.bolingcavalry.curd.entity;

import io.swagger.annotations.ApiModel;

import io.swagger.annotations.ApiModelProperty;

@ApiModel(description = “日志实体类(含用户表的字段)”)

public class LogExtend extends Log {

public String getUserName() {

return userName;

}

public void setUserName(String userName) {

this.userName = userName;

}

@ApiModelProperty(value = “用户名”)

private String userName;

@Override

public String toString() {

return “LogExtend{” +

“id=” + getId() +

“, userId=” + getUserId() +

“, userName=’” + getUserName() + ‘’’ +

“, action=’” + getAction() + ‘’’ +

“, createTime=” + getCreateTime() +

‘}’;

}

}

  1. 增加user表的mapper映射文件,可见都是些很简单sql,要注意的是批量新增的节点,这里面用到了foreach语法,可以通过集合动态生成sql:
<?xml version="1.0" encoding="UTF-8"?>

select * from user where id = #{id}

insert into user (id, name, age) values (#{id}, #{name}, #{age})

insert into user (id, name, age)

values

(#{user.id}, #{user.name}, #{user.age})

select id, name, age from user where name like concat(’%’, #{name}, ‘%’)

delete from user where id= #{id}

delete from user

update user set name = #{name}, age = #{age} where id = #{id}

select count(*) from user

  1. 增加log表的mapper映射文件,如下所示,请关注联表操作selExtend,其结果是logExtendResultMap:
<?xml version="1.0" encoding="UTF-8"?>

insert into log (id, user_id, action, create_time) values (#{id}, #{userId}, #{action}, #{createTime})

select l.id as id,

l.user_id as user_id,

l.action as action,

l.create_time as create_time,

u.name as user_name

from log as l

left join user as u

on l.user_id = u.id

where l.id = #{id}

  1. 增加用户表的mapper接口类UserMapper.java ,对应着映射文件中的sql节点的id:

package com.bolingcavalry.curd.mapper;

import com.bolingcavalry.curd.entity.LogExtend;

import com.bolingcavalry.curd.entity.User;

import org.springframework.stereotype.Repository;

import java.util.List;

@Repository

public interface UserMapper {

User sel(int id);

int insertWithFields(User user);

int insertBatch(List users);

int clearAll();

List findByName(String name);

int update(User user);

int delete(int id);

int totalCount();

LogExtend selExtend(int id);

}

  1. 增加日志表的mapper接口类LogMapper.java,对应着映射文件中的sql节点的id:

package com.bolingcavalry.curd.mapper;

import com.bolingcavalry.curd.entity.Log;

import com.bolingcavalry.curd.entity.LogExtend;

import org.springframework.stereotype.Repository;

@Repository

public interface LogMapper {

Log sel(int id);

LogExtend selExtend(int id);

int insertWithFields(Log log);

}

  1. mapper接口完成后就是service层,先写user表的service,如下所示,可见都是对mapper接口的调用:

package com.bolingcavalry.curd.service;

import com.bolingcavalry.curd.entity.User;

import com.bolingcavalry.curd.mapper.UserMapper;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.util.List;

@Service

public class UserService {

@Autowired

UserMapper userMapper;

public User sel(int id) {

return userMapper.sel(id);

}

public User insertWithFields(User user) {

userMapper.insertWithFields(user);

return user;

}

public List insertBatch(List users) {

userMapper.insertBatch(users);

return users;

}

public int clearAll() {

return userMapper.clearAll();

}

public List findByName(String name) {

return userMapper.findByName(name);

}

public int update(User user) {

return userMapper.update(user);

}

public int delete(int id) {

return userMapper.delete(id);

}

public int totalCount() {

return userMapper.totalCount();

}

}

  1. 还有log表的service:

package com.bolingcavalry.curd.service;

import com.bolingcavalry.curd.entity.Log;

import com.bolingcavalry.curd.entity.LogExtend;

import com.bolingcavalry.curd.entity.User;

import com.bolingcavalry.curd.mapper.LogMapper;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

@Service

public class LogService {

@Autowired

LogMapper logMapper;

public Log sel(int id){

return logMapper.sel(id);

}

public LogExtend selExtend(int id) {

return logMapper.selExtend(id);

}

public Log insertWithFields(Log log) {

logMapper.insertWithFields(log);

return log;

}

}

  1. 最后是controller层了,由于使用了swagger,导致controller相对上一篇略微复杂(多了些注解):

package com.bolingcavalry.curd.controller;

import com.bolingcavalry.curd.entity.User;

import com.bolingcavalry.curd.service.UserService;

import io.swagger.annotations.Api;

import io.swagger.annotations.ApiImplicitParam;

import io.swagger.annotations.ApiOperation;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;

import java.util.List;

@RestController

@RequestMapping("/user")

@Api(tags = {“UserController”})

public class UserController {

@Autowired

private UserService userService;

@ApiOperation(value = “新增user记录”, notes=“新增user记录”)

@RequestMapping(value = “/insertwithfields”,method = RequestMethod.PUT)

public User create(@RequestBody User user) {

return userService.insertWithFields(user);

}

@ApiOperation(value = “批量新增user记录”, notes=“批量新增user记录”)

@RequestMapping(value = “/insertbatch”, method = RequestMethod.PUT)

public List insertBatch(@RequestBody List users) {

ret

【一线大厂Java面试题解析+核心总结学习笔记+最新架构讲解视频+实战项目源码讲义】

浏览器打开:qq.cn.hn/FTf 免费领取

urn userService.insertBatch(users);

}

@ApiOperation(value = “删除指定ID的user记录”, notes=“删除指定ID的user记录”)

@ApiImplicitParam(name = “id”, value = “用户ID”, paramType = “path”, required = true, dataType = “Integer”)

@RequestMapping(value = “/{id}”, method = RequestMethod.DELETE)

public int delete(@PathVariable int id){

return userService.delete(id);

}

@ApiOperation(value = “删除user表所有数据”, notes=“删除user表所有数据”)

@RequestMapping(value = “/clearall”, method = RequestMethod.DELETE)

public int clearAll(){

return userService.clearAll();

}

@ApiOperation(value = “根据ID修改user记录”, notes=“根据ID修改user记录”)

@RequestMapping(value = “/update”, method = RequestMethod.POST)

public int update(@RequestBody User user){

return userService.update(user);

}

@ApiOperation(value = “根据名称模糊查找所有user记录”, notes=“根据名称模糊查找所有user记录”)

@ApiImplicitParam(name = “name”, value = “用户名”, paramType = “path”, required = true, dataType = “String”)

@RequestMapping(value = “/findbyname/{name}”, method = RequestMethod.GET)

public List findByName(@PathVariable(“name”) String name){

return userService.findByName(name);

}

@ApiOperation(value = “根据ID查找user记录”, notes=“根据ID查找user记录”)

@ApiImplicitParam(name = “id”, value = “用户ID”, paramType = “path”, required = true, dataType = “Integer”)

@RequestMapping(value = “/{id}”, method = RequestMethod.GET)

public User GetUser(@PathVariable int id){

return userService.sel(id);

}

@ApiOperation(value = “获取总数”, notes=“获取总数”)

@RequestMapping(value = “/totalcount”, method = RequestMethod.GET)

public int totalcount(){

return userService.totalCount();

}

}

  1. log的controller如下:

package com.bolingcavalry.curd.controller;

import com.bolingcavalry.curd.entity.Log;

import com.bolingcavalry.curd.entity.LogExtend;

import com.bolingcavalry.curd.service.LogService;

import io.swagger.annotations.Api;

import io.swagger.annotations.ApiImplicitParam;

import io.swagger.annotations.ApiOperation;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

@RestController

@RequestMapping("/log")

@Api(tags = {“LogController”})

public class LogController {

@Autowired

private LogService logService;

@ApiOperation(value = “根据ID查找日志记录”, notes=“根据ID查找日志记录”)

@ApiImplicitParam(name = “id”, value = “日志ID”, paramType = “path”, required = true, dataType = “Integer”)

@RequestMapping(value = “/{id}”, method = RequestMethod.GET)

public LogExtend logExtend(@PathVariable int id){

return logService.selExtend(id);

}

@ApiOperation(value = “新增日志记录”, notes=“新增日志记录”)

@RequestMapping(value = “/insertwithfields”,method = RequestMethod.PUT)

public Log create(@RequestBody Log log) {

return logService.insertWithFields(log);

}

}

  1. 最后是一段单元测试的代码,咱们试试通过junit进行自测,如下所示,可见一共测试了三个controller接口:先新增,再查找,最后删除,要注意的是MockMvc的用法,以及jsonPath方法的用法,还有就是通过Order注解控制执行顺序(一定要添加TestMethodOrder注解,否则Order注解不生效):

package com.bolingcavalry.curd.controller;

import com.bolingcavalry.curd.entity.User;

import com.google.gson.Gson;

import com.google.gson.JsonArray;

import com.google.gson.JsonParser;

import org.junit.Ignore;

import org.junit.jupiter.api.*;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;

import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.http.MediaType;

import org.springframework.test.context.junit4.SpringRunner;

import org.springframework.test.web.servlet.MockMvc;

import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import java.util.List;

import java.util.UUID;

import static org.hamcrest.Matchers.hasSize;

import static org.hamcrest.Matchers.is;

import static org.hamcrest.core.IsEqual.equalTo;

import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@RunWith(SpringRunner.class)

@SpringBootTest

@AutoConfigureMockMvc

@TestMethodOrder(MethodOrderer.OrderAnnotation.class)

class UserControllerTest {

@Autowired

private MockMvc mvc;

// user表的name字段,这里为了保证测试时新增和删除的记录是同一条,用UUID作为用户名

static String testName;

@BeforeAll

static void init() {

testName = UUID.randomUUID().toString().replaceAll("-","");;

}

@Test

@Order(1)

void insertWithFields() throws Exception {

String jsonStr = “{“name”: “” + testName + “”, “age”: 10}”;

mvc.perform(

MockMvcRequestBuilders.put("/user/insertwithfields")

.contentType(MediaType.APPLICATION_JSON)

.content(jsonStr)

.accept(MediaType.APPLICATION_JSON))

.andExpect(status().isOk())

.andExpect(jsonPath("$.name", is(testName)))

.andDo(print())

.andReturn()

.getResponse()

.getContentAsString();

}

@Test

@Order(2)

void findByName() throws Exception {

mvc.perform(MockMvcRequestBuilders.get("/user/findbyname/"+ testName).accept(MediaType.APPLICATION_JSON))

.andExpect(status().isOk())

.andExpect(jsonPath("$", hasSize(1)))

.andDo(print());

}

@Test

@Order(3)

void delete() throws Exception {

// 先根据名称查出记录

String responseString = mvc.perform(MockMvcRequestBuilders.get("/user/findbyname/"+ testName).accept(MediaType.APPLICATION_JSON))

.andExpect(status().isOk())

.andExpect(jsonPath("$", hasSize(1)))

.andDo(print())

.andReturn()

.getResponse()

.getContentAsString();

// 反序列化得到数组

JsonArray jsonArray = JsonParser.parseString(responseString).getAsJsonArray();

// 反序列化得到user实例

User user = new Gson().fromJson(jsonArray.get(0), User.class);

// 执行删除

mvc.perform(MockMvcRequestBuilders.delete("/user/"+ user.getId()).accept(MediaType.APPLICATION_JSON))

.andExpect(status().isOk())

.andExpect(content().string(equalTo(“1”)))

.andDo(print());

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值