文章目录
添加非好友,就是在页面中,不喜欢某个人. 进行点击X号.
一.Controller层
- 一.Controller层
- 二. Service层
- 三. Dao
- 四. 测试
在tensquare_friend模块的com.tensquare.friend.controller.FriendController中,修改addFriend方法. 具体内容如下
@RequestMapping(value = "/like/{friendid}/{type}", method = RequestMethod.PUT)
public Result addFriend(@PathVariable String friendid, @PathVariable String type) {
//验证是否登录, 并且拿到登录用户的id
Claims claims = (Claims) request.getAttribute("claims_user");
if (claims == null) {
//说明当前用户没有user角色
return new Result(false, StatusCode.LOGINERROR, "权限不足");
}
//得到当前登录的用户id
String userId = claims.getId();
//判断是添加好友,还是添加非好友
if (type != null && !"".equals(type)) {
if ("1".equals(type)) {
//添加好友
int flag = friendService.addFriend(userId, friendid);
if (flag == 0) {
return new Result(false, StatusCode.ERROR, "不能重复添加好友");
}
if (flag == 1) {
return new Result(true, StatusCode.OK, "添加成功");
}
} else if ("2".equals(type)) {
//添加非好友
int flag = friendService.addNoFriend(userId, friendid);
if (flag == 0) {
return new Result(false, StatusCode.ERROR, "不能重复添加非好友");
}
if (flag == 1) {
return new Result(true, StatusCode.OK, "添加成功");
}
}
return new Result(false, StatusCode.ERROR, "参数异常");
} else {
return new Result(false, StatusCode.ERROR, "参数异常");
}
}
二. Service层
在com.tensquare.friend.service.FriendService 修改如下. 添加addNoFriend方法, 注入NoFriendDao . 先判断是否已经为非好友了,再进行添加进数据库
@Autowired
private NoFriendDao noFriendDao;
public int addNoFriend(String userId, String friendid) {
//通过数据库查询是否已经是非好友
NoFriend noFriend = noFriendDao.findByUseridAndFriendid(userId, friendid);
if (noFriend != null) {
//代表是重复添加
return 0;
}
//不是好友
noFriend = new NoFriend();
noFriend.setFriendid(friendid);
noFriend.setUserid(userId);
noFriendDao.save(noFriend);
return 1;
}
三. Dao
新建NoFriendDao. 内容如下
package com.tensquare.friend.dao;
import com.tensquare.friend.pojo.Friend;
import com.tensquare.friend.pojo.NoFriend;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
/**
* 类名称:NoFriendDao
* 类描述:交友模块的dao层
*
* @author: taohongchao
* 创建时间:2019/2/17 15:42
* Version 1.0
*/
public interface NoFriendDao extends JpaRepository {
/**
* 方法名: findByUseridAndFriendid
* 方法描述: 通过当前用户和操作的用户查找
* 修改日期: 2019/2/17 15:48
* @param userid
* @param friendid
* @return com.tensquare.friend.pojo.NoFriend
* @author taohongchao
* @throws
*/
public NoFriend findByUseridAndFriendid(String userid, String friendid);
}
四. 测试
运行如下的两个项目. 在数据库中, 添加id为333的用户.
首先id为222的用户登录,获取token .带上该token,发送如下的put请求
http://localhost:9010/friend/like/333/2
代表id为222的用户不喜欢id为333的用户. 响应数据如下
在tb_nofriend表中,有如下的数据,代表成功添加了非好友.