文章目录
一.Controller层
-
-
- 一.Controller层
- 二. Service层
- 三. Dao
- 四.测试
-
在FriendController中,添加如下的代码
其中,此处进行了Feign的远程调用,把user模块中,粉丝数和关注数进行了减一的操作.
@RequestMapping(value = "/{friendid}", method = RequestMethod.DELETE) public Result addFriend(@PathVariable String friendid) { //验证是否登录, 并且拿到登录用户的id Claims claims = (Claims) request.getAttribute("claims_user"); if (claims == null) { //说明当前用户没有user角色 return new Result(false, StatusCode.LOGINERROR, "权限不足"); } //得到当前登录的用户id String userId = claims.getId(); friendService.deleteFriend(userId, friendid); //更新粉丝数和关注数 userClient.updateFanscountAndFollowcount(-1,userId,friendid); return new Result(true, StatusCode.OK, "删除好友成功"); }
二. Service层
在FriendService中,添加如下的代码,进行用户的删除. 首先删除tb_friend表中的记录. 其次是修改被喜欢者的字段为0 接着是在 tb_nofriend表中添加一条不喜欢的人记录
/**
* 删除用户
* @param userId
* @param friendid
*/ public void deleteFriend(String userId, String friendid) { //删除好友表中userid到friendid的数据 friendDao.deleteFriend(userId,friendid); //更新friendid到userid的islike字段为0 //即更新被关注者的islike字段为0 ,原本可能是1的,但由于对方不喜欢她了,因此要改成0 //但也可能找不到该字段,为空操作. friendDao.updateIsLike("0",friendid,userId); //非好友列表中添加数据 NoFriend noFriend = new NoFriend(); noFriend.setUserid(userId); noFriend.setFriendid(friendid); noFriendDao.save(noFriend); }
三. Dao
dao层完整的代码如下
package com.tensquare.friend.dao; import com.tensquare.friend.pojo.Friend; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; /**
* 类名称:FriendDao
* 类描述:交友模块的dao层
*
* @author: taohongchao
* 创建时间:2019/2/17 15:42
* Version 1.0
*/ public interface FriendDao extends JpaRepository<Friend,String> { /**
* 方法名: findByUseridAndFriendid
* 方法描述: 通过当前用户和操作的用户查找
* 修改日期: 2019/2/17 15:48
* @param userid
* @param friendid
* @return com.tensquare.friend.pojo.Friend
* @author taohongchao
* @throws
*/ public Friend findByUseridAndFriendid(String userid, String friendid); /**
* 方法名: updateIsLike
* 方法描述: 更新喜欢的状态
* 修改日期: 2019/2/17 16:36
* @param islike
* @param userid
* @param friendid
* @return void
* @author taohongchao
* @throws
*/ @Modifying @Query(value = "update tb_friend set islike=? where userid=? and friendid = ?", nativeQuery = true) public void updateIsLike(String islike, String userid, String friendid); /**
* 方法名: deleteFriend
* 方法描述: 删除好友表中的信息
* 修改日期: 2019/2/17 19:52
* @param userid
* @param friendid
* @return void
* @author taohongchao
* @throws
*/ @Modifying @Query(value = "delete from tb_friend where userid=? and friendid = ?", nativeQuery = true) public void deleteFriend(String userid, String friendid); }
四.测试
启动Eureka项目, tensquare_user项目和tensquare_friend
id为111的用户登录,获取token
带上该token ,发送如下的delete请求.
代表id为111的用户不喜欢id为222的用户了.
http://localhost:9010/friend/222
响应的数据如下.
在数据库中可以看到tb_friend的数据为空了,代表删除了该表中的一条数据
在tb_nofriend表中,新增了一条数据userid为111, friendid为222
在tb_user表中,fanscount和followcount的数量变成了0
