文章目录
1、先看看service的类图吧
2、难点:
- BaseController要知道自己的Service是哪里来的。
- BaseServiceImpl要知道自己的Mapper是哪里来的。
解决问题:
// 将service的类型通过泛型传进来,然后使用@Autowired通过类型来进行注入
public abstract class MyBaseController<T,S extends MyBaseService<T>> {
@Autowired
S service;
}
// 使用:
@RestController
public class AdminController extends MyBaseController<Admin,IAdminService> {
}
//service层使用mapper层类似:
public class MyBaseServiceImpl<M extends MyBaseMapper<T>, T> extends ServiceImpl<M, T> implements MyBaseService<T> {
}
// 使用:
@Service
public class AdminServiceImpl extends MyBaseServiceImpl<AdminMapper, Admin> implements IAdminService {
}
3、全部代码:
包路径:
一、基础类:
1、MyBaseController(里面的接口可以复用,接口url为,子类外部url+方法url)
package com.tangxz.property.common.base;
import com.tangxz.property.common.utils.R;
import com.tangxz.property.common.page.PageUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.Map;
/**
* @author: Tangxz
* @email: 1171702529@qq.com
* @cate: 2021/12/14 20:20
*/
public abstract class MyBaseController<T,S extends MyBaseService<T>> {
@Autowired
S service;
/**
* 分页列表查询
*
* @param params{"page","num"}
* @return
*/
@ApiOperation(value = "分页列表查询", notes = "分页列表查询")
@GetMapping(value = "/list")
public R list(@RequestParam Map<String, Object> params) {
PageUtils page = service.queryPage(params);
return R.ok().put("page", page);
}
/**
* 添加
*
* @param pojo
* @return
*/
@ApiOperation(value = "添加", notes = "添加")
@PostMapping(value = "/insert")
public R insert(@RequestBody T pojo) {
int id = service.insert(pojo);
return R.ok("添加成功").put("id",id);
}
/**
* 添加
*
* @param pojo
* @return
*/
@ApiOperation(value = "添加", notes = "添加")
@PostMapping(value = "/add")
public R add(@RequestBody T pojo) {
service.save(pojo);
return R.ok("添加成功");
}
/**
* 编辑
*
* @param pojo
* @return
*/
@ApiOperation(value = "编辑", notes = "编辑")
@PutMapping(value = "/edit")
public R edit(@RequestBody T pojo) {
service.updateById(pojo);
return R.ok("编辑成功!");
}
/**
* 通过id删除
*
* @param id
* @return
*/
@ApiOperation(value = "通过id删除", notes = "通过id删除")
@DeleteMapping(value = "/delete")
public R delete(@PathVariable("id") String id) {
service.removeById(id);
return R.ok("删除成功!");
}
/**
* 批量删除
*
* @param ids
* @return
*/
@ApiOperation(value = "批量删除", notes = "批量删除")
@DeleteMapping(value = "/deleteBatch")
public R deleteBatch(@RequestBody Integer[] ids) {
service.removeByIds(Arrays.asList(ids));
return R.ok("批量删除成功!");
}
/**
* 通过id查询
*
* @param id
* @return
*/
@ApiOperation(value = "通过id查询", notes = "通过id查询")
@GetMapping(value = "/info/{id}")
public R queryById(@PathVariable("id") Integer id) {
T pojo = service.getById(id);
String name = pojo.getClass().getName();
name = name.substring(0, 1).toLowerCase() + name.substring(1);
return R.ok().put(name, pojo);
}
}
2、MyBaseService
package com.tangxz.property.common.base;
import com.baomidou.mybatisplus.extension.service.IService;
import com.tangxz.property.common.page.PageUtils;
import java.util.Map;
public interface MyBaseService<T> extends IService<T> {
Integer insert(T t);
PageUtils queryPage(Map<String, Object> params);
}
3、MyBaseServiceImpl
package com.tangxz.property.common.base;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tangxz.property.common.page.PageUtils;
import com.tangxz.property.common.page.Query;
import com.tangxz.property.common.utils.ReflexUtil;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Map;
/**
* @author: Tangxz
* @email: 1171702529@qq.com
* @cate: 2021/12/14 20:21
*/
public class MyBaseServiceImpl<M extends MyBaseMapper<T>, T> extends ServiceImpl<M, T> implements MyBaseService<T> {
@Autowired
M mapper;
@Override
public Integer insert(T t) {
mapper.insertOrBackId(t);
return Integer.valueOf(ReflexUtil.getFieldValueByFieldName("id", t));
}
@Override
public PageUtils queryPage(Map<String, Object> params) {
QueryWrapper<T> queryWrapper = new QueryWrapper<>();
/** 处理分页查询的特殊需求,前端发送:
{
'page': this.villageListPageIndex,
'limit': this.villageListPageSize,
'eq':{
"company_id":this.nowCompany.userId
}
}
匹配company_id字段
*/
if (params.containsKey("eq")) {
Map eqs = JSON.parseObject(String.valueOf(params.get("eq")));
for (Object key : eqs.keySet()) {
queryWrapper = queryWrapper.eq(String.valueOf(key), eqs.get(key));
}
}
IPage<T> page = this.page(
new Query<T>().getPage(params),
queryWrapper
);
return new PageUtils(page);
}
}
4、MyBaseMapper
package com.tangxz.property.common.base;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* @author: Tangxz
* @email: 1171702529@qq.com
* @cate: 2021/12/14 20:22
*/
public interface MyBaseMapper<T> extends BaseMapper<T> {
Integer insertOrBackId(T t);
}
二、使用类
1、AdminController
package com.tangxz.property.modules.admin.controller;
import com.tangxz.property.common.base.MyBaseController;
import com.tangxz.property.modules.admin.entity.Admin;
import com.tangxz.property.modules.admin.service.IAdminService;
import lombok.extern.slf4j.Slf4j;
import com.tangxz.property.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
/**
* @Description: 物业管理员表
* @Author: 唐小尊
* @Date: 2021-12-09 07:55:31
* @Version: V1.0
*/
@Slf4j
@Api(tags = "物业管理员表")
@RestController
@RequestMapping("/admin")
public class AdminController extends MyBaseController<Admin,IAdminService> {
@Autowired
private IAdminService service;
/**
* 管理员激活账户
*
* @param admin
* @param token
* @return
*/
@ApiOperation(value = "管理员激活账户", notes = "管理员激活账户")
@PutMapping(value = "/active")
public R activeAccount(@RequestBody Admin admin, @RequestBody String token) throws Exception {
boolean b = service.activeAccount(admin, token);
return b ? R.ok() : R.error();
}
}
2、IAdminService
package com.tangxz.property.modules.admin.service;
import com.tangxz.property.common.base.MyBaseService;
import com.tangxz.property.modules.admin.entity.Admin;
/**
* @Description: 物业管理员表
* @Author: 唐小尊
* @Date: 2021-12-09
* @Version: V1.0
*/
public interface IAdminService extends MyBaseService<Admin>{
boolean activeAccount(Admin admin, String token) throws Exception;
void add(Admin admin);
Integer insert(Admin admin);
}
3、AdminServiceImpl
package com.tangxz.property.modules.admin.service.impl;
import com.tangxz.property.common.base.MyBaseServiceImpl;
import com.tangxz.property.common.mail.SendEmail;
import com.tangxz.property.modules.admin.entity.Admin;
import com.tangxz.property.modules.admin.mapper.AdminMapper;
import com.tangxz.property.modules.admin.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
/**
* @Description: 物业管理员表
* @Author: 唐小尊
* @Date: 2021-12-09
* @Version: V1.0
*/
@Service
public class AdminServiceImpl extends MyBaseServiceImpl<AdminMapper, Admin> implements IAdminService {
@Autowired
AdminMapper mapper;
@Autowired
StringRedisTemplate redisTemplate;
@Autowired
SendEmail sendEmail;
/**
* 这个方法没有保证原子性,即redis存储token、发送邮箱、保存用户当前信息,都是要原子的
*
* @param admin
* @return
*/
// @Override
// public Integer insert(Admin admin) {
// admin.setState(AdminStates.NOT_ACTIVE);
String s = UUID.randomUUID().toString();
// boolean save = baseMapper.add(admin);
// 1、redis存储验证token
redisTemplate.opsForValue().set(getTokenKey(admin.getId()), s);
// 2、发送邮箱邀请激活
sendEmail.send(admin.getName(), "激活账户", s);
// admin.setCreateTime(new Date());
// mapper.insertOrBackId(admin);
// return admin.getId();
// }
@Override
public boolean activeAccount(Admin admin, String token) throws Exception {
String key = getTokenKey(admin.getId());
String s = redisTemplate.opsForValue().get(key);
if (token != null && token.equals(s)) {
redisTemplate.delete(key);
return save(admin);
}
return false;
}
@Override
public void add(Admin admin) {
}
private String getTokenKey(int adminId) {
return "admin:active:token:" + adminId;
}
}
4、AdminMapper
package com.tangxz.property.modules.admin.mapper;
import com.tangxz.property.common.base.MyBaseMapper;
import com.tangxz.property.modules.admin.entity.Admin;
import org.apache.ibatis.annotations.Param;
/**
* @Description: 物业管理员表
* @Author: 唐小尊
* @Date: 2021-12-09
* @Version: V1.0
*/
public interface AdminMapper extends MyBaseMapper<Admin> {
Integer insertOrBackId(@Param("admin")Admin admin);
}
5、AdminMapper.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.tangxz.property.modules.admin.mapper.AdminMapper">
<insert id="insertOrBackId" parameterType="com.tangxz.property.modules.admin.entity.Admin" useGeneratedKeys="true"
keyProperty="id">
INSERT INTO admin(name,phone,email,id_card,company,create_time,state,salt)
values
(#{admin.name},#{admin.phone},#{admin.email},#{admin.idCard},#{admin.company},#{admin.createTime},#{admin.state},#{admin.salt});
</insert>
</mapper>