記錄一個使用redis記錄token的用戶登陸登出html
參考demo地址https://gitee.com/super_star_man/junewebjava
1.用戶實例git
package top.xzhand.po; import lombok.Data; import java.io.Serializable; import java.util.Date; @Data public class UserInfo implements Serializable { private Long id; private String username; private String password; private String mobile; private Date createAt; private Date updateAt; private Integer status; private String photoUrl; private String nickname; private String wxId; }
package top.xzhand.dto; import lombok.Data; import java.io.Serializable; import java.util.Date; @Data public class UserInfoDto implements Serializable { private static final long serialVersionUID = 7385797311824035903L; private Long id; private String username; private String password; private String mobile; private Date createAt; private Date updateAt; private Integer status; private String photoUrl; private String nickname; private String wxId; }
package top.xzhand.vo; import lombok.Data; import java.io.Serializable; import java.util.Date; @Data public class UserInfoVo implements Serializable { private static final long serialVersionUID = -3532912344120689693L; private Long id; private String username; private String password; private String mobile; private Date createAt; private Date updateAt; private Integer status; private String photoUrl; private String nickname; private String wxId; }
2.token校驗設置,redis配置,請參考上一篇web
package top.xzhand.service; public interface TokenService { public boolean setCode(String token, String userString, Integer expire); public String getCode(String token); public boolean verify(String code, Integer id); public String setToken(Long id) ; public boolean setUser(String token, String userString, Integer expire); public String getUser(String token); public boolean remove(String key); public void exit(Integer tokenid, String token); }
token實現ajax
package top.xzhand.service.impl; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import top.xzhand.constant.ConstantConfig; import top.xzhand.service.RedisService; import top.xzhand.service.TokenService; import top.xzhand.util.MD5; import top.xzhand.util.RedisClientTemplate; import javax.annotation.Resource; import java.util.Date; import java.util.UUID; @Service @Slf4j public class TokenServiceImpl implements TokenService { @Resource private RedisService redisService; @Resource private RedisClientTemplate redisClientTemplate; @Override public boolean setCode(String token, String userString, Integer expire) { // return redisService.set(ConstantConfig.CHECKCODE + token, userString, expire == null ? ConstantConfig.CHECKCODE_TIME : expire); return redisClientTemplate.set(ConstantConfig.CHECKCODE + token, userString, expire == null ? ConstantConfig.CHECKCODE_TIME : expire); } @Override public String getCode(String token) { // Object userString = redisService.get(ConstantConfig.CHECKCODE + token); Object userString = redisClientTemplate.get(ConstantConfig.CHECKCODE + token); if (userString == null) { userString = ""; } return userString.toString(); } @Override public boolean verify(String code, Integer id) { boolean isRight = false; // Object rel_code = redisService.get(ConstantConfig.TOKEN_ID + id); Object rel_code = redisClientTemplate.get(ConstantConfig.TOKEN_ID + id); if (code != null && code.equals(rel_code.toString())) { isRight = true; } rechangeStay(id, rel_code.toString()); return isRight; } @Override public String setToken(Long id) { String user = this.getUser(ConstantConfig.TOKEN_ID + id); if (user != null && !user.equals("")) { // long time = redisService.getExpire(ConstantConfig.TOKEN_ID + id); // log.info("---------------------------------" + id + "用戶已經登陸,當前時間爲:" + new Date() + "鍵過時時間爲:" + time); log.info("---------------------------------" + id + "用戶已經登陸,當前時間爲:" + new Date() + "鍵過時時間爲:" ); return null; } String token = MD5.encode(UUID.randomUUID().toString() + id); // redisService.set(ConstantConfig.TOKEN_ID + id, token, ConstantConfig.LOGIN_TIME); redisClientTemplate.set(ConstantConfig.TOKEN_ID + id, token, ConstantConfig.LOGIN_TIME.intValue()); return token; } @Override public boolean setUser(String token, String userString, Integer expire) { // return redisService.set(ConstantConfig.ADMIN_USER + token, userString, expire == null ? ConstantConfig.LOGIN_TIME : expire); return redisClientTemplate.set(ConstantConfig.ADMIN_USER + token, userString, (expire == null ? ConstantConfig.LOGIN_TIME.intValue() : expire)); } @Override public String getUser(String token) { // Object userString = redisService.get(ConstantConfig.ADMIN_USER + token); Object userString = redisClientTemplate.get(ConstantConfig.ADMIN_USER + token); if (userString == null) { userString = ""; } return userString.toString(); } /** * 重置redis過時時間 */ private void rechangeStay(Integer id, String token) { String key1 = ConstantConfig.TOKEN_ID + id; String key2 = ConstantConfig.ADMIN_USER + token; redisService.expire(key1, ConstantConfig.LOGIN_TIME); redisService.expire(key2, ConstantConfig.LOGIN_TIME); // redisClientTemplate.expire(key1, ConstantConfig.LOGIN_TIME.intValue()); // redisClientTemplate.expire(key2, ConstantConfig.LOGIN_TIME.intValue()); } /** * 銷燬key */ @Override public boolean remove(String key) { return redisService.del(key); } @Override public void exit(Integer tokenid, String token) { String key1 = ConstantConfig.TOKEN_ID + tokenid; String key2 = ConstantConfig.ADMIN_USER + token; // this.remove(key1); // this.remove(key2); redisClientTemplate.delete(key1); redisClientTemplate.delete(key2); } }
3.全局攔截校驗redis
package top.xzhand.interceptor; import com.alibaba.fastjson.JSON; import org.springframework.util.StringUtils; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import top.xzhand.po.UserInfo; import top.xzhand.res.JsonResult; import top.xzhand.service.TokenService; import top.xzhand.util.BizContext; import top.xzhand.util.JSonUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; import java.net.URLDecoder; import java.util.Map; //登陸攔截 public class LoginInterceptor extends HandlerInterceptorAdapter { private TokenService tokenService; public LoginInterceptor(TokenService tokenService) { this.tokenService = tokenService; } /** * 準備請求 * * @param request * @param response * @param handler * @return * @throws Exception */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return authFailed(request, response); } /** * 請求完成 * * @param request * @param response * @param handler * @param ex */ @Override public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex) { //清理緩存 BizContext.clear(); } /** * 權限校驗 * * @param request * @param response * @return * @throws Exception */ private boolean authFailed(HttpServletRequest request, HttpServletResponse response) throws Exception { response.setHeader("Content-type", "text/html;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); String token = getParam(request, "token"); String tokenId = getParam(request, "tokenid"); JsonResult jsonResult=new JsonResult(); if (!StringUtils.isEmpty(token) && !StringUtils.isEmpty(tokenId) && !token.equals("null") && !tokenId.equals("null")) { if (tokenService.verify(token, Integer.valueOf(tokenId))) { String userString = URLDecoder.decode(tokenService.getUser(token), "UTF-8"); UserInfo user = new UserInfo(); if (!StringUtils.isEmpty(userString)) { user = JSonUtils.readValue(userString, UserInfo.class); } //等待成功,緩存用戶信息 BizContext.putUser(user); //身份驗證經過,獲取用戶信息 return true; } else { String message = JSON.toJSONString(jsonResult.errorMapper("登陸失敗")); PrintWriter out = response.getWriter(); out.print(message); out.close(); } } else { String message = JSON.toJSONString(jsonResult.errorMapper("未登陸")); PrintWriter out = response.getWriter(); out.print(message); out.close(); } return false; } /** * 獲取token信息 * * @param request * @return */ private String getParam(HttpServletRequest request, String paramName) { //先從Header中獲取請求參數 String token = request.getHeader(paramName); if (StringUtils.isEmpty(token)) { Map<String, String[]> parm = request.getParameterMap(); //再從參數中讀取 String tokens[] = parm.get(paramName); if (tokens == null) { return null; } token = tokens[0]; } return token; } }
4.相關依賴model,工具spring
package top.xzhand.constant; import lombok.experimental.UtilityClass; @UtilityClass public final class ConstantConfig { public String SYS_NAME = "june_"; public String CHARSET = "UTF-8"; public String TOKEN_ID = SYS_NAME + "token_id_"; public String ADMIN_USER = SYS_NAME + "user_"; public Long LOGIN_TIME = 1800000L;// 30 * 60 * 1000;// 30分鐘 public String LOGIN_USER = SYS_NAME + "loginUser"; public String CHECKCODE = SYS_NAME + "checkcode_"; public Integer CHECKCODE_TIME = 60000;// 60 * 1000;// 60秒 public String VERIFY_CODE_KEY="june_code"; }
package top.xzhand.util; import top.xzhand.po.UserInfo; import java.util.HashMap; import java.util.Map; public class BizContext { private static ThreadLocal<Map<String, Object>> local = new ThreadLocal<>(); public static <V> void putValue(String key, V value) { if (null == local.get()) { local.set(new HashMap<String, Object>()); } Map<String, Object> context = local.get(); context.put(key, value); } public static void putUser(UserInfo user) { putValue("user", user); putValue("userId", user.getId()); putValue("userName", user.getUsername()); } /** * 用戶 * * @return */ public static UserInfo getUser() { return getValue("user"); } /** * 用戶 * * @return */ public static Integer getUserId() { return getValue("userId"); } /** * 用戶姓名 * * @return */ public static String getUserName() { return getValue("userName"); } @SuppressWarnings("unchecked") public static <T> T getValue(String key) { if (null == local.get()) { return null; } Map<String, Object> context = local.get(); if (!context.containsKey(key)) { return null; } return (T) context.get(key); } public static void clear() { if (null != local.get()) { local.set(null); } } }
package top.xzhand.res; import lombok.Getter; import lombok.Setter; import top.xzhand.common.Pager; import java.util.LinkedHashMap; /** * ajax調用時返回的json數據封裝 返回值使用toMapper方法獲取 * * @author songhailiang */ public class JsonResult { public static JsonResult createResult() { JsonResult result = new JsonResult(); result.setResultCode(ERROR); result.setBizCode(ERROR); result.setData(null); result.setDataReserve1(null); result.setDataReserve2(null); result.setError(""); result.setPager(null); result.setMessage(""); return result; } public static JsonResult newInstance(Object data) { return newInstance(data, SUCCESS, SUCCESS, "訪問成功"); } public static JsonResult newInstance(Object data, String message) { return newInstance(data, SUCCESS, SUCCESS, message); } public static JsonResult newInstance(Object data, int resultCode, String message) { return newInstance(data, resultCode, resultCode, message); } public static JsonResult newInstance(Object data, int resultCode, int bizCode, String message) { JsonResult jsonResult = new JsonResult(); jsonResult.setResultCode(resultCode); jsonResult.setBizCode(bizCode); jsonResult.setData(data); jsonResult.setMessage(message); jsonResult.setError(message); return jsonResult; } public static JsonResult errorInstance(String message) { JsonResult jsonResult = new JsonResult(); jsonResult.setResultCode(JsonResult.ERROR); jsonResult.setBizCode(JsonResult.ERROR); jsonResult.setData(null); jsonResult.setMessage(message); jsonResult.setError(message); return jsonResult; } public static final int SUCCESS = 1000; public static final int ERROR = 1001; /** * 返回碼: */ private int resultCode; @Getter @Setter private int bizCode;//業務碼 private Object data; private String message; private String error; private Pager<?> pager; // 預留,通常不用 private Object dataReserve1; // 預留,通常不用 private Object dataReserve2; public Object getDataReserve1() { return dataReserve1; } public void setDataReserve1(Object dataReserve) { this.dataReserve1 = dataReserve; } public Object getDataReserve2() { return dataReserve2; } public void setDataReserve2(Object dataReserve) { this.dataReserve2 = dataReserve; } public int getResultCode() { return resultCode; } public void setResultCode(int resultCode) { this.resultCode = resultCode; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getError() { return error; } public void setError(String error) { this.error = error; } public Pager<?> getPager() { return pager; } public void setPager(Pager<?> pager) { this.pager = pager; } /** * @return */ public LinkedHashMap<String, Object> toMapper() { LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>(); map.put("resultCode", this.resultCode); map.put("bizCode", this.bizCode); map.put("message", this.message); map.put("error", this.error); map.put("data", this.data); map.put("dataReserve1", this.dataReserve1); map.put("dataReserve2", this.dataReserve2); if (this.pager != null) { map.put("rows", this.pager.getResults()); map.put("page", this.pager.getPageNo()); map.put("total", this.pager.getTotalPage()); map.put("records", this.pager.getTotalRecord()); } return map; } public LinkedHashMap<String, Object> toMap() { LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>(); map.put("resultCode", this.resultCode); map.put("bizCode", this.bizCode); map.put("message", this.message); map.put("error", this.error); map.put("dataReserve1", this.dataReserve1); map.put("dataReserve2", this.dataReserve2); map.put("rows", this.data); map.put("total", this.pager.getTotalRecord()); return map; } public LinkedHashMap<String, Object> errorMapper(String error) { LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>(); map.put("resultCode", ERROR); map.put("error", error); return map; } }
package top.xzhand.res; import java.io.Serializable; public class ResonseResult<T> implements Serializable { public static final int CODE_OK = 1000; public static final int CODE_ERR = 4001; private int code; private String message; private T data; public boolean isSuccess() { return this.code == 1000; } public static <T> ResonseResult success(T data) { ResonseResult<T> json = new ResonseResult(); json.setCode(1000); json.setData(data); return json; } public static ResonseResult success() { ResonseResult json = new ResonseResult(); json.setCode(1000); return json; } public static ResonseResult fail(String message) { ResonseResult json = new ResonseResult(); json.setCode(4001); json.setMessage(message); return json; } public static ResonseResult fail(String message, int code) { ResonseResult json = new ResonseResult(); json.setCode(code); json.setMessage(message); return json; } public ResonseResult() { } public int getCode() { return this.code; } public String getMessage() { return this.message; } public T getData() { return this.data; } public void setCode(int code) { this.code = code; } public void setMessage(String message) { this.message = message; } public void setData(T data) { this.data = data; } @Override public boolean equals(Object o) { if (o == this) { return true; } else if (!(o instanceof ResonseResult)) { return false; } else { ResonseResult<?> other = (ResonseResult) o; if (!other.canEqual(this)) { return false; } else if (this.getCode() != other.getCode()) { return false; } else { Object this$message = this.getMessage(); Object other$message = other.getMessage(); if (this$message == null) { if (other$message != null) { return false; } } else if (!this$message.equals(other$message)) { return false; } Object this$data = this.getData(); Object other$data = other.getData(); if (this$data == null) { if (other$data != null) { return false; } } else if (!this$data.equals(other$data)) { return false; } return true; } } } protected boolean canEqual(Object other) { return other instanceof ResonseResult; } @Override public int hashCode() { int result = 1; result = result * 59 + this.getCode(); Object $message = this.getMessage(); result = result * 59 + ($message == null ? 43 : $message.hashCode()); Object $data = this.getData(); result = result * 59 + ($data == null ? 43 : $data.hashCode()); return result; } @Override public String toString() { return "ResonseResult(code=" + this.getCode() + ", message=" + this.getMessage() + ", data=" + this.getData() + ")"; } }
5.登陸接口sql
package top.xzhand.controller; import com.alibaba.fastjson.JSON; import com.google.common.base.Strings; import com.sun.deploy.net.URLEncoder; import com.wordnik.swagger.annotations.Api; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import top.xzhand.constant.ConstantConfig; import top.xzhand.dto.UserInfoDto; import top.xzhand.po.UserInfo; import top.xzhand.res.JsonResult; import top.xzhand.res.ResonseResult; import top.xzhand.service.TokenService; import top.xzhand.service.UserInfoService; import top.xzhand.vo.UserInfoVo; import java.util.HashMap; import java.util.List; import java.util.Map; @RestController @RequestMapping("userinfo") @Api(value = "user", description = "用戶中心") public class UserInfoController { @Autowired private TokenService tokenService; @Autowired private UserInfoService userInfoService; @RequestMapping("list") public Map list(UserInfoDto userInfoDto) { JsonResult jsonResult = new JsonResult(); try { List<UserInfoVo> listvo = userInfoService.search(userInfoDto); jsonResult.setResultCode(JsonResult.SUCCESS); jsonResult.setData(listvo); return jsonResult.toMapper(); } catch (Exception e) { e.printStackTrace(); jsonResult.setError(e.getMessage()); jsonResult.setResultCode(JsonResult.ERROR); } return jsonResult.toMapper(); } @RequestMapping("add") public Map add(UserInfoDto userInfoDto) { JsonResult jsonResult = new JsonResult(); try { UserInfo userInfo=new UserInfo(); BeanUtils.copyProperties(userInfoDto,userInfo); jsonResult = userInfoService.add(userInfo); return jsonResult.toMapper(); } catch (Exception e) { e.printStackTrace(); jsonResult.setError(e.getMessage()); jsonResult.setResultCode(JsonResult.ERROR); } return jsonResult.toMapper(); } @RequestMapping("aduit") public Map aduit(UserInfoDto userInfoDto) { JsonResult jsonResult = new JsonResult(); try { UserInfo userInfo=new UserInfo(); BeanUtils.copyProperties(userInfoDto,userInfo); jsonResult = userInfoService.aduit(userInfo); return jsonResult.toMapper(); } catch (Exception e) { e.printStackTrace(); jsonResult.setError(e.getMessage()); jsonResult.setResultCode(JsonResult.ERROR); } return jsonResult.toMapper(); } @RequestMapping("info") public Map aduit(Long id) { JsonResult jsonResult = new JsonResult(); try { UserInfo userInfo = userInfoService.find(id); jsonResult.setResultCode(JsonResult.SUCCESS); jsonResult.setData(userInfo); System.out.println(); return jsonResult.toMapper(); } catch (Exception e) { e.printStackTrace(); jsonResult.setError(e.getMessage()); jsonResult.setResultCode(JsonResult.ERROR); } return jsonResult.toMapper(); } /** * 登陸 */ @RequestMapping(value = "/login") public Map doLogin( String userName, String password, String checkCode, String key) throws Exception { JsonResult jsonResult=new JsonResult(); if (Strings.isNullOrEmpty(userName)) { return jsonResult.errorMapper("請輸入用戶名"); } if (Strings.isNullOrEmpty(password)) { return jsonResult.errorMapper("請輸入密碼"); } String code = tokenService.getCode(key); if (code == null || !checkCode.equals(code)) { return jsonResult.errorMapper("驗證碼錯誤"); } userName = userName.trim(); password = password.trim(); ResonseResult<UserInfoVo> response=userInfoService.login(userName, password); if (!response.isSuccess()) { return jsonResult.errorMapper(response.getMessage()); } UserInfoVo userInfo = response.getData(); String userString = URLEncoder.encode(JSON.toJSONString(userInfo), "UTF-8"); Map<String, Object> map = new HashMap<>(); String token = tokenService.setToken(userInfo.getId()); map.put("tokenid", userInfo.getId()); map.put("token", token); // 存放用戶信息 map.put("userInfo", userInfo); tokenService.setUser(token, userString, null); jsonResult.setResultCode(JsonResult.SUCCESS); jsonResult.setData(map); return jsonResult.toMapper(); } /** * 登出 */ @RequestMapping("exit") public Map<String, Object> exit(String token, Integer tokenid) { JsonResult result = new JsonResult(); try { String key1 = ConstantConfig.TOKEN_ID + tokenid; String key2 = ConstantConfig.ADMIN_USER + token; tokenService.remove(key1); tokenService.remove(key2); result.setResultCode(JsonResult.SUCCESS); return result.toMapper(); } catch (Exception e) { return result.errorMapper("服務器異常!"); } } }
6.用戶接口及實現json
package top.xzhand.service; import top.xzhand.dto.UserInfoDto; import top.xzhand.po.UserInfo; import top.xzhand.res.JsonResult; import top.xzhand.res.ResonseResult; import top.xzhand.vo.UserInfoVo; import java.util.List; public interface UserInfoService { List<UserInfoVo> search(UserInfoDto userInfoDto); JsonResult add(UserInfo userInfo); JsonResult aduit(UserInfo userInfo); UserInfo find(Long id); ResonseResult<UserInfoVo> login(String username, String password); }
package top.xzhand.service.impl; import com.google.common.base.Joiner; import com.google.common.base.Objects; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import top.xzhand.dto.UserInfoDto; import top.xzhand.mapper.UserInfoMapper; import top.xzhand.po.UserInfo; import top.xzhand.res.JsonResult; import top.xzhand.res.ResonseResult; import top.xzhand.service.UserInfoService; import top.xzhand.vo.UserInfoVo; import java.util.List; import java.util.UUID; @Service public class UserInfoServiceImpl implements UserInfoService { @Autowired private UserInfoMapper userInfoMapper; private final static HashFunction sha512 = Hashing.sha512(); private final static Splitter splitter = Splitter.on(',').trimResults(); private final static HashFunction md5 = Hashing.md5(); private final static Joiner joiner = Joiner.on(',').skipNulls(); @Override public List<UserInfoVo> search(UserInfoDto userInfoDto) { return userInfoMapper.search(userInfoDto); } @Override public JsonResult add(UserInfo userInfo) { JsonResult jsonResult=new JsonResult(); String encryptPassword = this.encryptPassword(userInfo.getPassword()); userInfo.setPassword(encryptPassword); if(userInfoMapper.insertSelective(userInfo)>0){ jsonResult.setResultCode(JsonResult.SUCCESS); jsonResult.setData(userInfo.getId()); return jsonResult; } jsonResult.setResultCode(JsonResult.ERROR); jsonResult.setError("添加失敗"); return jsonResult; } @Override public JsonResult aduit(UserInfo userInfo) { JsonResult jsonResult=new JsonResult(); // if(!StringUtils.isEmpty(userInfo.getPassword())){ // String encryptPassword = this.encryptPassword(userInfo.getPassword()); // userInfo.setPassword(encryptPassword); // } if(userInfoMapper.updateByPrimaryKey(userInfo)>0){ jsonResult.setResultCode(JsonResult.SUCCESS); jsonResult.setData(userInfo.getId()); return jsonResult; } jsonResult.setResultCode(JsonResult.ERROR); jsonResult.setError("修改失敗"); return jsonResult; } @Override public UserInfo find(Long id) { return userInfoMapper.selectByPrimaryKey(id); } @Override public ResonseResult<UserInfoVo> login(String userName, String password) { UserInfoVo record = userInfoMapper.loadByUserName(userName); if (record == null) { return ResonseResult.fail("用戶不存在"); } if (!passwordMatch(password, record.getPassword())) { return ResonseResult.fail("密碼錯誤"); } if (!record.getStatus().equals(1)) { return ResonseResult.fail("帳戶已被禁用!"); } return ResonseResult.success(record); } //解密校驗 private boolean passwordMatch(String password, String encryptedPassword) { Iterable<String> parts = splitter.split(encryptedPassword); String salt = Iterables.get(parts, 0); String realPassword = Iterables.get(parts, 1); String enFromPassword = sha512.hashUnencodedChars(password + salt) .toString().substring(0, 20); return Objects.equal(enFromPassword, realPassword); } //加密 private String encryptPassword(String password) { String salt = md5.newHasher() .putUnencodedChars(UUID.randomUUID().toString()) .putLong(System.currentTimeMillis()).hash().toString() .substring(0, 4); String realPassword = sha512.hashUnencodedChars(password + salt) .toString().substring(0, 20); return joiner.join(salt, realPassword); } }
package top.xzhand.mapper; import org.springframework.stereotype.Repository; import top.xzhand.dto.UserInfoDto; import top.xzhand.po.UserInfo; import top.xzhand.vo.UserInfoVo; import java.util.List; @Repository public interface UserInfoMapper { int deleteByPrimaryKey(Long id); int insert(UserInfo record); int insertSelective(UserInfo record); UserInfo selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(UserInfo record); int updateByPrimaryKey(UserInfo record); List<UserInfoVo> search(UserInfoDto userInfoDto); UserInfoVo loadByUserName(String userName); }
<?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="top.xzhand.mapper.UserInfoMapper" > <resultMap id="BaseResultMap" type="top.xzhand.po.UserInfo" > <id column="id" property="id" jdbcType="BIGINT" /> <result column="username" property="username" jdbcType="VARCHAR" /> <result column="password" property="password" jdbcType="VARCHAR" /> <result column="mobile" property="mobile" jdbcType="VARCHAR" /> <result column="create_at" property="createAt" jdbcType="TIMESTAMP" /> <result column="update_at" property="updateAt" jdbcType="TIMESTAMP" /> <result column="status" property="status" jdbcType="INTEGER" /> <result column="photo_url" property="photoUrl" jdbcType="VARCHAR" /> <result column="nickname" property="nickname" jdbcType="VARCHAR" /> <result column="wx_id" property="wxId" jdbcType="VARCHAR" /> </resultMap> <sql id="Base_Column_List" > id, username, password, mobile, create_at, update_at, status, photo_url, nickname, wx_id </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" > select <include refid="Base_Column_List" /> from user_info where id = #{id,jdbcType=BIGINT} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" > delete from user_info where id = #{id,jdbcType=BIGINT} </delete> <insert id="insert" parameterType="top.xzhand.po.UserInfo" > <selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER" > SELECT LAST_INSERT_ID() </selectKey> insert into user_info (username, password, mobile, create_at, update_at, status, photo_url, nickname, wx_id ) values (#{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{mobile,jdbcType=VARCHAR}, #{createAt,jdbcType=TIMESTAMP}, #{updateAt,jdbcType=TIMESTAMP}, #{status,jdbcType=INTEGER}, #{photoUrl,jdbcType=VARCHAR}, #{nickname,jdbcType=VARCHAR}, #{wxId,jdbcType=VARCHAR} ) </insert> <insert id="insertSelective" parameterType="top.xzhand.po.UserInfo" > <selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER" > SELECT LAST_INSERT_ID() </selectKey> insert into user_info <trim prefix="(" suffix=")" suffixOverrides="," > <if test="username != null" > username, </if> <if test="password != null" > password, </if> <if test="mobile != null" > mobile, </if> <if test="createAt != null" > create_at, </if> <if test="updateAt != null" > update_at, </if> <if test="status != null" > status, </if> <if test="photoUrl != null" > photo_url, </if> <if test="nickname != null" > nickname, </if> <if test="wxId != null" > wx_id, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="username != null" > #{username,jdbcType=VARCHAR}, </if> <if test="password != null" > #{password,jdbcType=VARCHAR}, </if> <if test="mobile != null" > #{mobile,jdbcType=VARCHAR}, </if> <if test="createAt != null" > #{createAt,jdbcType=TIMESTAMP}, </if> <if test="updateAt != null" > #{updateAt,jdbcType=TIMESTAMP}, </if> <if test="status != null" > #{status,jdbcType=INTEGER}, </if> <if test="photoUrl != null" > #{photoUrl,jdbcType=VARCHAR}, </if> <if test="nickname != null" > #{nickname,jdbcType=VARCHAR}, </if> <if test="wxId != null" > #{wxId,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="top.xzhand.po.UserInfo" > update user_info <set > <if test="username != null" > username = #{username,jdbcType=VARCHAR}, </if> <if test="password != null" > password = #{password,jdbcType=VARCHAR}, </if> <if test="mobile != null" > mobile = #{mobile,jdbcType=VARCHAR}, </if> <if test="createAt != null" > create_at = #{createAt,jdbcType=TIMESTAMP}, </if> <if test="updateAt != null" > update_at = #{updateAt,jdbcType=TIMESTAMP}, </if> <if test="status != null" > status = #{status,jdbcType=INTEGER}, </if> <if test="photoUrl != null" > photo_url = #{photoUrl,jdbcType=VARCHAR}, </if> <if test="nickname != null" > nickname = #{nickname,jdbcType=VARCHAR}, </if> <if test="wxId != null" > wx_id = #{wxId,jdbcType=VARCHAR}, </if> </set> where id = #{id,jdbcType=BIGINT} </update> <update id="updateByPrimaryKey" parameterType="top.xzhand.po.UserInfo" > update user_info set username = #{username,jdbcType=VARCHAR}, password = #{password,jdbcType=VARCHAR}, mobile = #{mobile,jdbcType=VARCHAR}, create_at = #{createAt,jdbcType=TIMESTAMP}, update_at = #{updateAt,jdbcType=TIMESTAMP}, status = #{status,jdbcType=INTEGER}, photo_url = #{photoUrl,jdbcType=VARCHAR}, nickname = #{nickname,jdbcType=VARCHAR}, wx_id = #{wxId,jdbcType=VARCHAR} where id = #{id,jdbcType=BIGINT} </update> <select id="search" parameterType="top.xzhand.dto.UserInfoDto" resultType="top.xzhand.vo.UserInfoVo"> select * from user_info <where> <if test="id!=null "> and id = #{id,jdbcType=BIGINT} </if> <if test="username!=null and username!='' "> and username = #{username,jdbcType=VARCHAR} </if> <if test="nickname!=null and nickname!='' "> and nickname = #{nickname,jdbcType=VARCHAR} </if> <if test="mobile!=null and mobile!='' "> and mobile = #{mobile,jdbcType=VARCHAR} </if> </where> </select> <select id="loadByUserName" parameterType="java.lang.String" resultType="top.xzhand.vo.UserInfoVo"> select * from user_info where username = #{username,jdbcType=VARCHAR} </select> </mapper>