转自:https://idig8.com/2018/09/24/xiaochengxujavashizhanxiaochengxudeshipindianzangongnengkaifa61/

视频点赞关系有3张表,用户表(获得点赞数量),视频表(获得点赞数量),用户喜欢视频的关联表,需要同时操作三张表。源码:https://github.com/limingios/wxProgram.git 中No.15和springboot

后台开发

  • mapper.xml开发
    >VideosUserMapper.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.idig8.mapper.VideosUsersMapper" >
<resultMap id="BaseResultMap" type="com.idig8.pojo.vo.VideosVO" > <!--
WARNING - @mbg.generated
-->
<id column="id" property="id" jdbcType="VARCHAR" />
<result column="user_id" property="userId" jdbcType="VARCHAR" />
<result column="audio_id" property="audioId" jdbcType="VARCHAR" />
<result column="video_desc" property="videoDesc" jdbcType="VARCHAR" />
<result column="video_path" property="videoPath" jdbcType="VARCHAR" />
<result column="video_seconds" property="videoSeconds" jdbcType="REAL" />
<result column="video_width" property="videoWidth" jdbcType="INTEGER" />
<result column="video_height" property="videoHeight" jdbcType="INTEGER" />
<result column="cover_path" property="coverPath" jdbcType="VARCHAR" />
<result column="like_counts" property="likeCounts" jdbcType="BIGINT" />
<result column="status" property="status" jdbcType="INTEGER" />
<result column="create_time" property="createTime" jdbcType="TIMESTAMP" />
<result column="username" property="username" jdbcType="VARCHAR" />
<result column="face_image" property="faceImage" jdbcType="VARCHAR" />
<result column="nickname" property="nickname" jdbcType="VARCHAR" />
</resultMap> <select id="queryAllVideos" resultMap="BaseResultMap" parameterType="String">
select v.*,u.face_image,u.username,u.nickname from videos v
left join users u on v.user_id = u.id
where
1 = 1
<if test="videoDesc !=null and videoDesc != '' ">
and v.video_desc like '%${videoDesc}%'
</if>
and v.status = 1
order by v.create_time </select> <update id="addVideoLikeCount" parameterType="String">
update videos set like_counts=like_counts+1 where id=#{videoId}
</update> <update id="reduceVideoLikeCount" parameterType="String">
update videos set like_counts=like_counts-1 where id=#{videoId}
</update>
</mapper>

UsersMapper.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.idig8.mapper.UsersMapper" >
<resultMap id="BaseResultMap" type="com.idig8.pojo.Users" >
<!--
WARNING - @mbg.generated
-->
<id column="id" property="id" jdbcType="VARCHAR" />
<result column="username" property="username" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
<result column="face_image" property="faceImage" jdbcType="VARCHAR" />
<result column="nickname" property="nickname" jdbcType="VARCHAR" />
<result column="fans_counts" property="fansCounts" jdbcType="INTEGER" />
<result column="follow_counts" property="followCounts" jdbcType="INTEGER" />
<result column="receive_like_counts" property="receiveLikeCounts" jdbcType="INTEGER" />
</resultMap> <update id="addReceiveLikeCount" parameterType="String">
update users set receive_like_counts = receive_like_counts+1 where id=#{userId}
</update> <update id="reduceReceiveLikeCount" parameterType="String">
update users set receive_like_counts = receive_like_counts-1 where id=#{userId}
</update> </mapper>
  • service 和 serviceImpl
    >VideoService.java
package com.idig8.service;

import java.util.List;

import com.idig8.pojo.Videos;
import com.idig8.utils.PagedResult; public interface VideoService { /**
* 保存视频信息
* @param Id
* @return
*/
public String saveVideo(Videos video); /**
* 分析查询视频列表
* @param video
* @param isSaveRecord
* @param page
* @param pageSize
* @return
*/
public PagedResult getAllVideos(Videos video,Integer isSaveRecord,Integer page,Integer pageSize); /**
* 获取热搜词列表
* @return
*/
public List<String> gethostList(); public void userLikeVideo(String userId,String videoId,String videoCreaterId); public void userUnLikeVideo(String userId,String videoId,String videoCreaterId); }

VideoServiceImpl.java

package com.idig8.service.Impl;

import java.util.List;

import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.idig8.mapper.SearchRecordsMapper;
import com.idig8.mapper.UsersLikeVideosMapper;
import com.idig8.mapper.UsersMapper;
import com.idig8.mapper.VideosMapper;
import com.idig8.mapper.VideosUsersMapper;
import com.idig8.pojo.SearchRecords;
import com.idig8.pojo.UsersLikeVideos;
import com.idig8.pojo.Videos;
import com.idig8.pojo.vo.VideosVO;
import com.idig8.service.VideoService;
import com.idig8.utils.PagedResult; import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria; @Service
public class VideoServiceImpl implements VideoService { @Autowired
private VideosMapper videosMapper; @Autowired
private UsersMapper usersMapper; @Autowired
private VideosUsersMapper videosUsersMapper; @Autowired
private SearchRecordsMapper searchRecordsMapper; @Autowired
private UsersLikeVideosMapper usersLikeVideosMapper; @Autowired
private Sid sid; @Transactional(propagation = Propagation.REQUIRED)
public String saveVideo(Videos video) {
String id = sid.nextShort();
video.setId(id); videosMapper.insertSelective(video);
return id; } @Override
@Transactional(propagation = Propagation.REQUIRED)
public PagedResult getAllVideos(Videos video, Integer isSaveRecord, Integer page, Integer pageSize) { String desc = video.getVideoDesc();
if (isSaveRecord != null && isSaveRecord == 1) {
SearchRecords record = new SearchRecords();
String recordId = sid.nextShort();
record.setId(recordId);
record.setContent(desc);
searchRecordsMapper.insert(record);
} PageHelper.startPage(page, pageSize);
List<VideosVO> list = videosUsersMapper.queryAllVideos(desc);
PageInfo<VideosVO> pageList = new PageInfo<>(list); PagedResult result = new PagedResult();
result.setPage(page);
result.setTotal(pageList.getPages());
result.setRows(list);
result.setRecords(pageList.getTotal()); return result;
} @Transactional(propagation = Propagation.SUPPORTS)
@Override
public List<String> gethostList() { return searchRecordsMapper.gethotList();
} @Override
public void userLikeVideo(String userId, String videoId, String videoCreaterId) { // 1.保存用戶和视频的关联关系
String likeId = sid.nextShort();
UsersLikeVideos usersLikeVideos = new UsersLikeVideos();
usersLikeVideos.setId(likeId);
usersLikeVideos.setUserId(userId);
usersLikeVideos.setVideoId(videoId);
usersLikeVideosMapper.insert(usersLikeVideos); // 2.视频喜欢的累加
videosUsersMapper.addVideoLikeCount(videoId); // 3. 用户喜欢的累加
usersMapper.addReceiveLikeCount(userId); } @Override
public void userUnLikeVideo(String userId, String videoId, String videoCreaterId) {
Example example = new Example(UsersLikeVideos.class);
Criteria criteria = example.createCriteria();
criteria.andEqualTo("userId", userId);
criteria.andEqualTo("videoId", videoId);
usersLikeVideosMapper.deleteByExample(example);
// 2.视频喜欢的累减
videosUsersMapper.reduceVideoLikeCount(videoId); // 3. 用户喜欢的累减
usersMapper.reduceReceiveLikeCount(userId);
}
}
  • mapper.java文件
    >UsersMapper.java
package com.idig8.mapper;

import com.idig8.pojo.Users;
import com.idig8.utils.MyMapper; public interface UsersMapper extends MyMapper<Users> { public void addReceiveLikeCount(String userId); public void reduceReceiveLikeCount(String userId); }

VideosUsersMapper.java

package com.idig8.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.idig8.pojo.Videos;
import com.idig8.pojo.vo.VideosVO;
import com.idig8.utils.MyMapper; public interface VideosUsersMapper extends MyMapper<VideosVO> { public List<VideosVO> queryAllVideos(@Param("videoDesc") String videoDesc); public void addVideoLikeCount(String videoId); public void reduceVideoLikeCount(String videoId); }
  • controller.java
    >VideoController.java
package com.idig8.controller;

import java.io.File;
import java.util.Date;
import java.util.UUID; import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import com.idig8.pojo.Bgm;
import com.idig8.pojo.Videos;
import com.idig8.service.BgmService;
import com.idig8.service.VideoService;
import com.idig8.utils.FetchVideoCover;
import com.idig8.utils.JSONResult;
import com.idig8.utils.MergeVideoMp3;
import com.idig8.utils.PagedResult;
import com.idig8.utils.enums.VideoStatusEnum;
import com.idig8.utils.file.FileUtil; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam; @RestController
@Api(value="视频相关业务的接口", tags= {"视频相关业务的controller"})
@RequestMapping("/video")
public class VideoController extends BasicController { @Autowired
private BgmService bgmService; @Autowired
private VideoService videosService; @Value("${server.file.path}")
private String fileSpace; @Value("${server.ffmpeg.path}")
private String ffmpegexe; @ApiOperation(value="上传视频", notes="上传视频的接口")
@ApiImplicitParams({
@ApiImplicitParam(name="userId", value="用户id", required=true,
dataType="String", paramType="form"),
@ApiImplicitParam(name="bgmId", value="背景音乐id", required=false,
dataType="String", paramType="form"),
@ApiImplicitParam(name="videoSeconds", value="背景音乐播放长度", required=true,
dataType="String", paramType="form"),
@ApiImplicitParam(name="videoWidth", value="视频宽度", required=true,
dataType="String", paramType="form"),
@ApiImplicitParam(name="videoHeight", value="视频高度", required=true,
dataType="String", paramType="form"),
@ApiImplicitParam(name="desc", value="视频描述", required=false,
dataType="String", paramType="form")
})
@PostMapping(value="/upload", headers="content-type=multipart/form-data")
public JSONResult upload(String userId,
String bgmId, double videoSeconds,
int videoWidth, int videoHeight,
String desc,
@ApiParam(value="短视频", required=true)
MultipartFile file) throws Exception { if (StringUtils.isBlank(userId)) {
return JSONResult.errorMsg("用户id不能为空...");
}
// 文件保存的命名空间
String fileName = file.getOriginalFilename();
// 保存到数据库中的相对路径
String path = "";
String videOutPath = "";
String ImagePath = "";
try {
path = FileUtil.uploadFile(file.getBytes(), fileSpace, fileName);
} catch (Exception e) {
e.getStackTrace();
return JSONResult.errorMsg(e.getMessage());
} if(StringUtils.isNotBlank(bgmId)){
Bgm bgm = bgmService.queryBgmById(bgmId);
String mp3BgmPath = fileSpace + bgm.getPath();
MergeVideoMp3 mergeVideoMp3 = new MergeVideoMp3(ffmpegexe);
String videOutPathName = UUID.randomUUID().toString()+".mp4";
File targetFile = new File(fileSpace + userId);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
videOutPath = "/"+userId+"/"+videOutPathName;
String videoInput = fileSpace +path;
mergeVideoMp3.convertor(videoInput, mp3BgmPath, videoSeconds, fileSpace +videOutPath); }else{
videOutPath = path; } ImagePath = "/"+userId+"/"+UUID.randomUUID().toString()+".jpg";;
FetchVideoCover fetchVideoCover = new FetchVideoCover(ffmpegexe);
fetchVideoCover.getCover(fileSpace +videOutPath, fileSpace +ImagePath); Videos videos = new Videos();
videos.setAudioId(bgmId);
videos.setCreateTime(new Date());
videos.setVideoDesc(desc);
videos.setId(UUID.randomUUID().toString());
videos.setUserId(userId);
videos.setVideoHeight(videoHeight);
videos.setVideoWidth(videoWidth);
videos.setVideoPath(videOutPath);
videos.setCoverPath(ImagePath);
videos.setStatus(VideoStatusEnum.SUCCESS.value);
videosService.saveVideo(videos); return JSONResult.ok(path); } @PostMapping(value="/showAll")
@ApiOperation(value="视频列表", notes="分页的视频列表")
public JSONResult upload(@RequestBody Videos video,Integer isSaveRecord,
Integer page) throws Exception {
if(page == null){
page = 1;
}
PagedResult result = videosService.getAllVideos(video,isSaveRecord,page, PAGE_SIZE);
return JSONResult.ok(result); } @PostMapping(value="/userLike")
@ApiOperation(value="热搜词列表", notes="热搜词列表")
public JSONResult userLike(String userId,String videoId,String videoCreaterId) throws Exception { videosService.userLikeVideo(userId, videoId, videoCreaterId);
return JSONResult.ok(); } @PostMapping(value="/userUnLike")
public JSONResult userUnLike(String userId,String videoId,String videoCreaterId) throws Exception {
videosService.userUnLikeVideo(userId, videoId, videoCreaterId);
return JSONResult.ok(); } @PostMapping(value="/hot")
public JSONResult upload() throws Exception { return JSONResult.ok(videosService.gethostList()); }
}

小程序前端修改


var videoUtils = require('../../utils/videoUtils.js')
const app = getApp()
Page({ data: {
cover:'cover',
videoContext:"",
videoInfo:{},
videId:'',
src:'',
userLikeVideo:false
}, showSearch:function(){
wx.navigateTo({
url: '../videoSearch/videoSearch',
})
},
onLoad:function(params){
var me = this;
me.videoContext = wx.createVideoContext('myVideo', me);
var videoInfo = JSON.parse(params.videoInfo);
var videoWidth = videoInfo.videoWidth;
var videoHeight = videoInfo.videoHeight;
var cover = 'cover';
if (videoWidth > videoHeight){
cover = '';
}
me.setData({
videId: videoInfo.id,
src: app.serverUrl + videoInfo.videoPath,
videoInfo: videoInfo,
cover: cover
}) },
showIndex:function(){
wx.redirectTo({
url: '../index/index',
})
}, onShow:function(){
var me = this;
me.videoContext.play();
},
onHide:function(){
var me = this;
me.videoContext.pause();
},
upload:function(){ var me = this;
var userInfo = app.getGlobalUserInfo(); var videoInfo = JSON.stringify(me.data.videoInfo);
var realUrl = '../videoInfo/videoInfo#videoInfo@' + videoInfo; if (userInfo.id == '' || userInfo.id == undefined) {
wx.navigateTo({
url: '../userLogin/userLogin?realUrl=' + realUrl,
})
} else {
videoUtils.uploadVideo();
} },
showMine: function () {
var me = this;
var userInfo = app.getGlobalUserInfo(); var videoInfo = JSON.parse if (userInfo.id == '' || userInfo.id == undefined){
wx.navigateTo({
url: '../userLogin/userLogin',
})
}else{
wx.navigateTo({
url: '../mine/mine',
})
} }, likeVideoOrNot: function () {
var me = this;
var userInfo = app.getGlobalUserInfo(); var videoInfoStr = JSON.stringify(me.data.videoInfo);
var realUrl = '../videoInfo/videoInfo#videoInfo@' + videoInfoStr;
if (userInfo.id == '' || userInfo.id == undefined) {
wx.navigateTo({
url: '../userLogin/userLogin?realUrl=' + realUrl,
})
} else {
var videoInfo = me.data.videoInfo;
var userLikeVideo = me.data.userLikeVideo;
var url = "/video/userLike?userId=" + userInfo.id + "&videoId=" + videoInfo.id + "&videoCreaterId=" + userLikeVideo.userId; if (userLikeVideo){
var url = "/video/userUnLike?userId=" + userInfo.id + "&videoId=" + videoInfo.id + "&videoCreaterId=" + userLikeVideo.userId;
}
wx.showLoading({
title: '....',
})
wx.request({
url: app.serverUrl + url,
method: "POST",
header: {
'content-type': 'application/json', // 默认值
'headerUserId': userInfo.id,
'headerUserToken': userInfo.userToken
},
success: function (res) {
wx.hideLoading();
me.setData({
userLikeVideo: !userLikeVideo,
})
}
}) } }
})

PS:许多的功能如果分解,逻辑清晰的话,剩下的都是搬砖活。

「小程序JAVA实战」小程序的视频点赞功能开发(62)的更多相关文章

  1. 「小程序JAVA实战」小程序页面的上拉下拉刷新(50)

    转自:https://idig8.com/2018/09/21/xiaochengxujavashizhanxiaochengxuyemiandeshanglaxialashuaxin49/ 之前已经 ...

  2. 「小程序JAVA实战」小程序的flex布局(22)

    转自:https://idig8.com/2018/08/09/xiaochengxu-chuji-22/ 之前已经把小程序的框架说完了,接下来说说小程序的组件,在说组件之前,先说说布局吧.源码:ht ...

  3. 「小程序JAVA实战」小程序通用模板的使用(17)

    转自:https://idig8.com/2018/08/09/xiaochengxu-chuji-17/ 小程序也为了页面增加了通用模板的功能,如何去理解一个通用的模板呢?模板的定义就是为了让我们的 ...

  4. 「小程序JAVA实战」小程序搜索功能(55)

    转自:https://idig8.com/2018/09/23/xiaochengxujavashizhanxiaochengxusousuogongneng54/ 通过用户搜索热销词,将热销词添加到 ...

  5. 「小程序JAVA实战」小程序的留言和评价功能(70)

    转自:https://idig8.com/2018/10/28/xiaochengxujavashizhanxiaochengxudeliuyanhepingjiagongneng69/ 目前小程序这 ...

  6. 「小程序JAVA实战」小程序的举报功能开发(68)

    转自:https://idig8.com/2018/09/25/xiaochengxujavashizhanxiaochengxudeweixinapicaidancaozuo66-2/ 通过点击举报 ...

  7. 「小程序JAVA实战」小程序的个人信息作品,收藏,关注(66)

    转自:https://idig8.com/2018/09/24/xiaochengxujavashizhanxiaochengxudegerenxinxizuopinshoucangguanzhu65 ...

  8. 「小程序JAVA实战」小程序的关注功能(65)

    转自:https://idig8.com/2018/09/24/xiaochengxujavashizhanxiaochengxudeguanzhugongneng64/ 在个人页面,根据发布者个人和 ...

  9. 「小程序JAVA实战」小程序的springboot后台拦截器(61)

    转自:https://idig8.com/2018/09/24/xiaochengxujavashizhanxiaochengxudespringboothoutailanjieqi60/ 之前咱们把 ...

随机推荐

  1. css3伪放大镜(图片放大动画)效果(鼠标移入圆形区域放大图片)

    源码: <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8&q ...

  2. HttpClient将手机上的数据发送到服务器

    到官网下载jar包,下载GA发布版本即可 在项目中将httpclient-4.5.5.jar.httpcore-4.4.9.jar.httpmime-4.5.5.jar.commons-logging ...

  3. 本地RUN Page时报无法显示该网页

    经检查,是我本地安装了浏览器广告屏蔽插件引起的,关闭该插件即可.

  4. MySql中Blob与Text的区别

    BLOB是一个二进制大对象,可以容纳可变数量的数据.有4种BLOB类型:TINYBLOB.BLOB.MEDIUMBLOB和LONGBLOB.它们只是可容纳值的最大长度不同. 有4种TEXT类型:TIN ...

  5. do-while语句和while的区别

    do-while语句是一种后测试循环语句,即只有在循环体中的代码执行之后,才会测试出口条件.其实就是,代码在刚开始执行的时候,都是要先走一遍do循环体内的代码,然后在与while里面的条件进行判断,成 ...

  6. 面筋: 奇虎360 c++ 后台开发 实习生 面试

    投的是360上海的商业化部门,岗位是C++服务端开发实习生,记录一下面试历程: 视频面试,但是是有代码框让你写代码的. 一面: Q:先说一下个人信息,做过的项目 A:.......... Q:先写个翻 ...

  7. Howto: 在ArcGIS10中将地图文档(mxd文档)批量保存到之前版本

     Howto: 在ArcGIS10中将地图文档(mxd文档)批量保存到之前版本 文章编号 : 38783 软件: ArcGIS - ArcEditor 10 ArcGIS - ArcInfo 10 A ...

  8. C#读写 AB PLC 直接通过节点来读写数据 读写 AllenBradley PLC

    本文将使用一个Github开源的组件库技术来读写AB PLC,使用的是基于以太网的实现,不需要额外的组件,读取操作只要放到后台线程就不会卡死线程,本组件支持超级方便的高性能读写操作 官网:http:/ ...

  9. 使用Junit进行Java单元测试

    1.新建一个Number类,该类中包含两个函数,求和.求差 2.在eclipse上安装Junit 右键test工程,选择“Properties”→“Java Build Path”→“Librarie ...

  10. Linux wget auto login and backup database

    #!/bin/bash # 这是一份本来打算采用自动备份数据的代码,由于测试过程中出现了无法连接的问题,导致不能测试, # 于是最后放弃了这份代码的进一步的开发,但是记录还是有必要的 login_ur ...