前言

一、视频查询

1.准备项目前工作

2.配置mybatis 链接数据库

3.创建实体类 entity包下

4.分别创建Controller层,mapper层,service层,分别创建其实现类和接口

5.在Controller包下创建VideoController类

6.在service层中编写VideoContorller实现方法

7.在mapper层中编写VideoController查询对接数据库的接口

8.创建ViodeServiceMapper.xml配置文件

二、开发注册,登录,用户信息查询功能。

1.在request包下创建LoginRequest类

2.在Util包下创建CommenUtils工具类 用于MD5加密

3.在Util包下创建JWTUtils工具类 用于安全认证 ,令牌等用户信息安全问题

4.开发拦截器

5.创建UserController 编写注册,登录,用户信息查询功能。

三,开发自定义异常,用户下单,下单后的章节信息

1.自定义异常的开发

2.用户下单,下单后的章节信息的开发

四.pom.xml配置

五.JDBC配置

六.目录

总结


前言

使用工具idea编写接口 使用postman进行调试工作

此项目 运用技术 mysql, mybatis, spring,javese,maven 等技术编写接口


一、视频查询

1.准备项目前工作

导入相对应的数据库

2.配置mybatis 链接数据库

server.port=8181spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/online_xdclass?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456#开启控制台 打印sql
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#下划线转驼峰配置
mybatis.configuration.map-underscore-to-camel-case=true#配置xml的结果别名
mybatis.type-aliases-package=com.xdclass.project.pojo.entitymybatis.mapper-locations=classpath:mapper/*xml

3.创建实体类 entity包下

Chapter

package com.xdclass.project.pojo.entity;import lombok.*;import java.util.Date;
import java.util.List;@Data
@ToString
@NoArgsConstructor
@AllArgsConstructorpublic class Chapter {private Integer id;private Integer videoId;private String title;private Integer ordered;private Date createTime;private List<Episode> episodeList;

Epsiode

package com.xdclass.project.pojo.entity;import lombok.*;import java.util.Date;@Data@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Episode {private Integer id;private  String title;private Integer num;private  Integer ordered;private String playUrl;private  Integer chapterId;private Integer free;private  Integer videoId;private Date createTime;}

playRecord

package com.xdclass.project.pojo.entity;import lombok.*;import java.util.Date;@Data
@ToString@AllArgsConstructor
@NoArgsConstructor
public class playRecord {private Integer id;private Integer userId;private Integer videoId;private Integer currentNum;private Integer episodeId;private Date createTime;}

User

package com.xdclass.project.pojo.entity;import lombok.*;import java.util.Date;@Data@ToString
@AllArgsConstructor
@NoArgsConstructor
public class User {private Integer id ;private  String name ;private  String pwd;private String headImg;private String phone;private Date createTime;}

Video

package com.xdclass.project.pojo.entity;import lombok.*;import java.util.Date;
import java.util.List;@Data@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Video {private Integer id;private String title;private  String summary;private String coverImg;private  Integer price;private Date createTime;private double point;private List<Chapter> chapterList;
}

VideoBanner

package com.xdclass.project.pojo.entity;import lombok.*;import java.util.Date;@NoArgsConstructor
@ToString
@AllArgsConstructor
@Datapublic class VideoBanner {private Integer id;private String url;private String img;private Date createTime;private Integer weight;}

videoOrder

package com.xdclass.project.pojo.entity;import lombok.*;import java.util.Date;@Data@AllArgsConstructor
@NoArgsConstructor
@ToString
public class VideoOrder {private  Integer id ;private String outTradeNo;private Integer state;private Date createTime;private Integer totalFee;private String videoTitle;private String videoImg;private Integer videoId;private Integer userId;}

4.分别创建Controller层,mapper层,service层,分别创建其实现类和接口

5.在Controller包下创建VideoController类

创建Util包 编写JsonData实体类

package com.xdclass.project.Util;public class JsonData {private  Integer code ;private  Object data;private  String msg;public Integer getCode() {return code;}public void setCode(Integer code) {this.code = code;}public Object getData() {return data;}public void setData(Object data) {this.data = data;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}public static JsonData buildSuccess(Integer code, String msg){return  new JsonData(code,null,msg);}public static JsonData buildSuccess(){return new JsonData(0, null,null);}public  static JsonData buildSuccess(Object data){return  new JsonData(0,data,null);}public  static JsonData buildError(String msg){return  new JsonData(-1,null,msg);}public JsonData(Integer code, Object data, String msg) {this.code = code;this.data = data;this.msg = msg;}
}

在VideoContorller编写 查询视频列表,章节 ,视频详情等接口代码如下

package com.xdclass.project.controller;import com.xdclass.project.Util.JsonData;
import com.xdclass.project.pojo.entity.Video;
import com.xdclass.project.pojo.entity.VideoBanner;
import com.xdclass.project.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController
@RequestMapping("api/v1/pub/video")
public class VideoController {@Autowiredprivate VideoService videoService;@RequestMapping("list")public Object listVideo(){List<Video> videolist = videoService.listVideo();return JsonData.buildSuccess(videolist);}@GetMapping("list_banner")public JsonData indexbanner(){List<VideoBanner>  listbanner=  videoService.listBanner();return  JsonData.buildSuccess(listbanner);}@GetMapping("find_detail_by_id")public JsonData findDetailById(@RequestParam(value = "video_id" , required  = true) int videoId){Video video =  videoService.findDetailById(videoId);return  JsonData.buildSuccess(video);}
}

6.在service层中编写VideoContorller实现方法

ViodeService

package com.xdclass.project.service;import com.xdclass.project.pojo.entity.Video;
import com.xdclass.project.pojo.entity.VideoBanner;
import org.springframework.stereotype.Service;import java.util.List;public interface VideoService {List<Video> listVideo();List<VideoBanner> listBanner();/*** 查看视频详情* @param videoId* @return*/Video findDetailById(int videoId);
}

VideoServiceImpl

package com.xdclass.project.service.Impl;import com.xdclass.project.mapper.VideoMapper;
import com.xdclass.project.pojo.entity.Video;
import com.xdclass.project.pojo.entity.VideoBanner;
import com.xdclass.project.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class VideoServiceImpl implements VideoService {@Autowiredprivate VideoMapper videoMapper;public List<Video> listVideo() {return  videoMapper.listVideo();}@Overridepublic List<VideoBanner> listBanner() {return videoMapper.listBanner();}@Overridepublic Video findDetailById(int videoId) {return videoMapper.findDetailById(videoId);}
}

7.在mapper层中编写VideoController查询对接数据库的接口

package com.xdclass.project.mapper;import com.xdclass.project.pojo.entity.Video;
import com.xdclass.project.pojo.entity.VideoBanner;
import org.apache.ibatis.annotations.Param;import java.util.List;public interface VideoMapper {List<Video> listVideo();List<VideoBanner> listBanner();Video findDetailById(int videoId);Video findById(@Param("video_id") int videoId);
}

8.创建ViodeServiceMapper.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.xdclass.project.mapper.VideoMapper">
<select id="listVideo" resultType="Video">select * from video
</select><select id="listBanner" resultType="VideoBanner">select * from video_banner order by weight asc</select><resultMap id="VideoDetailResultMap" type="video"><id column="id" jdbcType="INTEGER" property="id"/><result column="title" jdbcType="VARCHAR" property="title"/><result column="summary" jdbcType="VARCHAR" property="summary"/><result column="cover_img" jdbcType="VARCHAR" property="coverImg"/><result column="price" jdbcType="INTEGER" property="price"/><result column="create_time" jdbcType="TIMESTAMP" property="createTime"/><result column="point" jdbcType="DOUBLE" property="point"/><collection property="chapterList" ofType="Chapter"><id column="chapter_id" jdbcType="INTEGER" property="id"/><result column="chapter_video_id" jdbcType="INTEGER" property="videoId"/><result column="chapter_title" jdbcType="VARCHAR" property="ordered"/><result column="chapter_create_time" jdbcType="TIMESTAMP" property="createTime"/><collection property="episodeList" ofType="Episode"><id column="episode_id" jdbcType="INTEGER" property="id"/><result column="episode_title" jdbcType="VARCHAR" property="title"/><result column="episode_num" jdbcType="INTEGER" property="title"/><result column="episode_ordered" jdbcType="INTEGER" property="title"/><result column="episode_play_url" jdbcType="VARCHAR" property="title"/><result column="episode_free" jdbcType="INTEGER" property="title"/><result column="episode_create_time" jdbcType="TIMESTAMP" property="createTime"/></collection></collection></resultMap><select id="findDetailById" resultMap="VideoDetailResultMap">SELECTv.id ,v.title,v.summary,v.cover_img,v.price,v.point,v.create_time,
c.id AS chapter_id ,c.title AS chapter_title ,c.ordered AS chapter_ordered ,
c.create_time AS chapter_create_time,
e.id AS episode_id,e.title AS episode_title ,e.num ,
e.ordered AS episode_ordered, e.create_time AS episode_create_time,
e.free,e.play_url
FROM video v
LEFT JOIN chapter c ON v.id=c.video_id
LEFT JOIN episode e ON c.id=e.chapter_id
WHERE v.id=#{video_id}
ORDER BY c.ordered,e.num ASC</select></mapper>

二、开发注册,登录,用户信息查询功能。

1.在request包下创建LoginRequest类

package com.xdclass.project.pojo.request;import lombok.*;@Data@AllArgsConstructor
@NoArgsConstructor
@ToString
public class LoginRequest {private String phone ;private String pwd ;
}

2.在Util包下创建CommenUtils工具类 用于MD5加密

package com.xdclass.project.Util;import java.security.MessageDigest;public class CommentUtils {public static String MD5(String data) {try {java.security.MessageDigest md =MessageDigest.getInstance("MD5");byte[] array = md.digest(data.getBytes("UTF-8"));StringBuilder sb = new StringBuilder();for (byte item : array) {sb.append(Integer.toHexString((item & 0xFF) |0x100).substring(1, 3));}return sb.toString().toUpperCase();} catch (Exception exception) {}return null;}}

3.在Util包下创建JWTUtils工具类 用于安全认证 ,令牌等用户信息安全问题

package com.xdclass.project.Util;import com.xdclass.project.pojo.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;import java.util.Date;public class JWTUtils {private static final long ExPIAE = 6000 * 60 * 60 * 24 * 7;private static final String SECRET = "project.net1688";private static final String TOKEN_PREFIX = "china";private static final String SUBJECT = "xdclass";public static String geneJsonWebToken(User user) {String token = Jwts.builder().setSubject(SUBJECT).claim("head_img", user.getHeadImg()).claim("id", user.getId()).claim("name", user.getName()).setIssuedAt(new Date()).setExpiration(new Date(System.currentTimeMillis() + ExPIAE)).signWith(SignatureAlgorithm.HS384, SECRET).compact();token = TOKEN_PREFIX + token;return token;}public static Claims checkJwT(String token) {try {Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token.replace(TOKEN_PREFIX, "")).getBody();return claims;} catch (Exception e) {return null;}}}

4.开发拦截器

配置拦截器的拦截路径 创建InterceptorConfig

package com.xdclass.project.config;import com.xdclass.project.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class InterceptorConfig implements WebMvcConfigurer {@BeanLoginInterceptor loginInterceptor(){return  new LoginInterceptor();}@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(loginInterceptor()).addPathPatterns("/api/v1/pri/*/*/**").excludePathPatterns("/api/v1/pri/user/Login","/api/v1/pri/user/register");WebMvcConfigurer.super.addInterceptors(registry);}
}

开发登录拦截器

package com.xdclass.project.interceptor;import com.fasterxml.jackson.databind.ObjectMapper;
import com.xdclass.project.Util.JWTUtils;
import com.xdclass.project.Util.JsonData;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;public class LoginInterceptor implements HandlerInterceptor {public static void sendJsonMassage(HttpServletResponse response, Object obj) {try {ObjectMapper jsons = new ObjectMapper();response.setContentType("application/json;charset=utf-8");PrintWriter writer = response.getWriter();writer.println(jsons.writeValueAsString(obj));writer.close();response.flushBuffer();} catch (IOException e) {e.printStackTrace();}}@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {String sessionToken = request.getHeader("token");if (sessionToken == null) {request.getParameter("token");}if (StringUtils.isNoneBlank(sessionToken)) {Claims claims = JWTUtils.checkJwT(sessionToken);if (claims == null) {sendJsonMassage(response, JsonData.buildError("登录过期,重新登陆"));}Integer id = (Integer) claims.get("id");String name = (String) claims.get("name");request.setAttribute("user_id", id);request.setAttribute("name", name);return true;}return false;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {}
}

5.创建UserController 编写注册,登录,用户信息查询功能。

package com.xdclass.project.controller;import com.xdclass.project.Util.JsonData;
import com.xdclass.project.pojo.entity.User;
import com.xdclass.project.pojo.request.LoginRequest;
import com.xdclass.project.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest;
import java.util.Map;@RestController
@RequestMapping("api/v1/pri/user")
public class UserController {@Autowiredprivate UserService userService;@RequestMapping("/register")public JsonData register(@RequestBody Map<String,String> userinfo){int rows = userService.save(userinfo);return  rows == 1?JsonData.buildSuccess():JsonData.buildError("注册失败");}@RequestMapping("Login")public JsonData login(@RequestBody LoginRequest loginRequest){String token = userService.findByPhone(loginRequest.getPhone(),loginRequest.getPwd() );return token == null?JsonData.buildError("登录失败"):JsonData.buildSuccess(token);}@GetMapping("find_by_token")public  JsonData findInfoByToken(HttpServletRequest request){int  userId  =  (Integer) request.getAttribute("user_id");User user = userService.findInfoBytoken(userId);if (user ==null){return JsonData.buildError("查询失败");}return JsonData.buildSuccess(user);}}

UserService

package com.xdclass.project.service;import com.xdclass.project.pojo.entity.User;
import org.apache.ibatis.annotations.Param;import java.util.Map;public interface UserService {int save(Map<String, String> userinfo);String findByPhone(String phone,  String pwd);User findInfoBytoken(int userId);
}

UserServiceImpl

package com.xdclass.project.service.Impl;import com.xdclass.project.Util.CommentUtils;
import com.xdclass.project.Util.JWTUtils;
import com.xdclass.project.mapper.UserMapper;
import com.xdclass.project.pojo.entity.User;
import com.xdclass.project.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.Date;
import java.util.Map;
import java.util.Random;@Service
public class UserServiceImpl implements UserService {//随机头像private static final String[] headImg = {"https://xd-video-pc-img.oss-cnbeijing.aliyuncs.com/xdclass_pro/default/head_img/12.jpeg","https://xd-video-pc-img.oss-cnbeijing.aliyuncs.com/xdclass_pro/default/head_img/11.jpeg","https://xd-video-pc-img.oss-cnbeijing.aliyuncs.com/xdclass_pro/default/head_img/13.jpeg","https://xd-video-pc-img.oss-cnbeijing.aliyuncs.com/xdclass_pro/default/head_img/14.jpeg","https://xd-video-pc-img.oss-cnbeijing.aliyuncs.com/xdclass_pro/default/head_img/15.jpeg"};@Autowiredprivate UserMapper userMapper;private String getRandomImg() {int size = headImg.length;Random random = new Random();int index = random.nextInt(size);return headImg[index];}@Overridepublic String findByPhone(String phone, String pwd) {User user = userMapper.findByPhone(phone, CommentUtils.MD5(pwd));if (user != null) {String token = JWTUtils.geneJsonWebToken(user);return token;} else {return null;}}@Overridepublic User findInfoBytoken(int userId) {User user = userMapper.findInfoBytoken(userId);user.setPwd("");return user;}//用户注册public int save(Map<String, String> userinfo) {User user1 = userMapper.findPhone("phone"); //在数据库中查找是否有相同的手机号if (user1 != null) {User user = ToUser(userinfo);return userMapper.save(user);}return -1;}//获取用户的信息 private User ToUser(Map<String, String> userinfo) {if (userinfo.containsKey("phone")&& userinfo.containsKey("pwd")&& userinfo.containsKey("name")) {User user = new User();user.setPhone(userinfo.get("phone"));user.setName(userinfo.get("name"));user.setCreateTime(new Date());user.setHeadImg("");String pwd = userinfo.get("pwd");user.setPwd(CommentUtils.MD5(pwd));return user;} else {return null;}}}

UserMapper

package com.xdclass.project.mapper;import com.xdclass.project.pojo.entity.User;
import org.apache.ibatis.annotations.Param;public interface UserMapper {int save(User user);User findByPhone(@Param("phone") String phone, @Param("pwd") String pwd);User findPhone(@Param("phone") String phone);User findInfoBytoken(@Param("user_id") Integer userId);
}

UserMapper.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.xdclass.project.mapper.UserMapper"><insert id="save" parameterType="User">
insert into user (name,pwd,head_img,phone,create_time)value (#{name,jdbcType=VARCHAR},#{pwd,jdbcType=VARCHAR},#{headImg,jdbcType=VARCHAR},#{phone,jdbcType=VARCHAR},#{createTime,jdbcType=TIMESTAMP})
</insert><select id="findInfoBytoken" resultType="User">select * from user where  id = #{user_id}</select><select id="findPhone" resultType="User">select * from  user  where  phone= #{phone}</select><select id="findByPhone"  resultType="User">select * from  user  where  phone = #{phone} and pwd =#{pwd}</select></mapper>

三,开发自定义异常,用户下单,下单后的章节信息

1.自定义异常的开发

创建XDException

package com.xdclass.project.exception;import lombok.AllArgsConstructor;
import lombok.Data;@Data
@AllArgsConstructor
public class XDException extends RuntimeException {private Integer code ;private String msg;
}

创建CustomExceptionHandler

package com.xdclass.project.exception;import com.xdclass.project.Util.JsonData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;@ControllerAdvice
public class CustomExceptionHandler {private final static Logger logger = LoggerFactory.getLogger(CustomExceptionHandler.class);@ExceptionHandler(value = java.lang.Exception.class)@ResponseBodyprivate JsonData handle(XDException e) {if (e instanceof XDException) {XDException xdException = (XDException) e;return JsonData.buildSuccess(xdException.getCode(), xdException.getMsg());} else {return JsonData.buildError("全局异常错误");}}
}

2.用户下单,下单后的章节信息的开发

VideoOrderContorller

package com.xdclass.project.controller;import com.xdclass.project.Util.JsonData;
import com.xdclass.project.pojo.entity.User;
import com.xdclass.project.pojo.entity.VideoOrder;
import com.xdclass.project.pojo.request.VideoOrderRequest;
import com.xdclass.project.service.VideoOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.net.httpserver.HttpsServerImpl;import javax.servlet.http.HttpServletRequest;
import java.util.List;@RestController
@RequestMapping("/1")
public class VideoOrderController {@Autowiredprivate VideoOrderService videoOrderService;@RequestMapping("/2")public JsonData saveOrder(@RequestBody VideoOrderRequest orderRequest, HttpServletRequest request){Integer userId = (Integer) request.getAttribute("user_id");int rows = videoOrderService.saveOrder(userId, orderRequest.getVideoId());return  rows == 0?JsonData.buildError("下单失败"):JsonData.buildSuccess();}@RequestMapping("videoOrderList")public JsonData listOrder(HttpServletRequest request){Integer userId = (Integer) request.getAttribute("user_id");List<VideoOrder> list =videoOrderService.findListOrder(userId);return JsonData.buildSuccess(list);}}

创建EpisodeMapper

package com.xdclass.project.mapper;import com.xdclass.project.pojo.entity.Episode;public interface EpisodeMapper {Episode findFirstEpisode(int videoId);
}

创建PlayRecordMapper

package com.xdclass.project.mapper;import com.xdclass.project.pojo.entity.playRecord;public interface PlayRecordMapper {void saveRecord(playRecord playRecord);
}

创建VideoOrderMapper

package com.xdclass.project.mapper;import com.xdclass.project.pojo.entity.Video;
import com.xdclass.project.pojo.entity.VideoOrder;
import org.apache.ibatis.annotations.Param;import java.util.List;public interface VideoOrdeorMapper {VideoOrder findInfo(@Param("user_id") int  userId, @Param("video_id")int videoId,@Param("state") int state);int saveOrder(VideoOrder videoOrder);List<VideoOrder> findListOrder(@Param("user_id") int userId);
}

VideoOrderService

package com.xdclass.project.service;import com.xdclass.project.pojo.entity.VideoOrder;import java.util.List;public interface VideoOrderService {int saveOrder(int userId,int videoId);List<VideoOrder> findListOrder(Integer userId);
}

VideoOrderServiceImpl

package com.xdclass.project.service.Impl;import com.xdclass.project.exception.XDException;
import com.xdclass.project.mapper.EpisodeMapper;
import com.xdclass.project.mapper.PlayRecordMapper;
import com.xdclass.project.mapper.VideoMapper;
import com.xdclass.project.mapper.VideoOrdeorMapper;
import com.xdclass.project.pojo.entity.Episode;
import com.xdclass.project.pojo.entity.Video;
import com.xdclass.project.pojo.entity.VideoOrder;
import com.xdclass.project.pojo.entity.playRecord;
import com.xdclass.project.service.VideoOrderService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import java.util.Date;
import java.util.List;
import java.util.UUID;@Service
public class VideoOrderServiceImpl implements VideoOrderService {@Autowiredprivate VideoOrdeorMapper videoOrdeorMapper;@Autowiredprivate VideoMapper videoMapper ;@Autowiredprivate EpisodeMapper episodeMapper ;@Autowiredprivate PlayRecordMapper playRecordMapper;@SneakyThrows@Transactionalpublic int saveOrder(int userId, int videoId) {VideoOrder  videoOrder =   videoOrdeorMapper.findInfo(userId,videoId,1);if (videoOrder !=null){return 0; }Video video =  videoMapper.findById(videoId);VideoOrder newVideoOrder = new VideoOrder();newVideoOrder.setTotalFee(video.getPrice());newVideoOrder.setVideoTitle(video.getTitle());newVideoOrder.setVideoImg(video.getCoverImg());newVideoOrder.setOutTradeNo(UUID.randomUUID().toString());newVideoOrder.setState(1);newVideoOrder.setCreateTime(new Date());newVideoOrder.setVideoId(videoId);int rows = videoOrdeorMapper.saveOrder(newVideoOrder);if (rows == 1){Episode episode = episodeMapper.findFirstEpisode(videoId);if (episode == null){throw new XDException(-1,"视频没有集信息,请运营人员检查");}else {playRecord  playRecord = new playRecord();playRecord.setCreateTime(new Date());playRecord.setUserId(userId);playRecord.setVideoId(videoId);playRecord.setEpisodeId(episode.getId());playRecordMapper.saveRecord(playRecord); }}return rows;}@Overridepublic List<VideoOrder> findListOrder(Integer userId) {return videoOrdeorMapper.findListOrder(userId);}
}

EpisodeMapper.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.xdclass.project.mapper.EpisodeMapper"><select id="findFirstEpisodeByVideoId" resultType="Episode">select * from episode where video_id =#{video_id} and  num =1</select></mapper>

PlayRecordMapper.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.xdclass.project.mapper.PlayRecordMapper"><insert id="saveRecord" keyProperty="id" keyColumn="id" useGeneratedKeys="true">insert  into play_record(user_id,video_id,current_num,episode_id,create_time)value (#{userId},#{valueId},#{currentNum},#{episodeId},#{createTime});</insert>
</mapper>

VideoOrderMapper.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.xdclass.project.mapper.VideoOrderMapper"><select id="findInfo" resultType="VideoOrder">select * from video_order where user_id=#{user_id} and video_id=#{video_id}and state =#{state}</select><insert id="saveOrder" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
insert  into   video_order  (out_trade_no,state,create_time,
total_fee,video_id,video_title,video_img,user_id)
value(#{outTradeNo,jdbcType=VARCHAR},#{state,jdbcType=INTEGER},#{createTime,jdbcType=TIMESTAMP},
#{totalFee,jdbcType=INTEGER},#{videoId,jdbcType=INTEGER},#{videoTitle,jdbcType=VARCHAR},
#{videoImg,jdbcType=VARCHAR},#{userId,jdbcType=INTEGER})</insert><select id="findListOrder" resultType="VideoOrder">select * from video_order where  user_id=#{user_id} order by create_time  desc</select></mapper>

四.pom.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.xdclass</groupId><artifactId>project</artifactId><version>0.0.1-SNAPSHOT</version><name>project</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><spring-boot.version>2.3.7.RELEASE</spring-boot.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.4</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.9</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.16.10</version></dependency><dependency><groupId>com.google.guava</groupId><artifactId>guava</artifactId><version>19.0</version></dependency><dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.7.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>${spring-boot.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.1</version><configuration><source>1.8</source><target>1.8</target><encoding>UTF-8</encoding></configuration></plugin><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>2.3.7.RELEASE</version><configuration><mainClass>com.xdclass.project.ProjectApplication</mainClass></configuration><executions><execution><id>repackage</id><goals><goal>repackage</goal></goals></execution></executions></plugin></plugins></build></project>

五.JDBC配置

server.port=8181spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/online_xdclass?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456#开启控制台 打印sql
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#下划线转驼峰配置
mybatis.configuration.map-underscore-to-camel-case=true#配置xml的结果别名
mybatis.type-aliases-package=com.xdclass.project.pojo.entitymybatis.mapper-locations=classpath:mapper/*xml

六.目录

总结

此项目是后端开发在开发项目中用到的技术Mysql, JavaSE,Maven,Spring,Mybatis,SpringBoot,还有一些工具类,用到Idea 软件开发 ,PostMan软件进行调试。

springboot 电商项目相关推荐

  1. SpringBoot电商项目之购物车下单(沙箱支付)

    目录 一.购物车结算前端功能实现 二.购物车结算后端功能实现 1.从session中获取购物车对象 2.筛选出要结算的订单项列表集合 3.订单页前台展示 三.结算页的下单前端 生成订单 1.前端相关处 ...

  2. java spu sku_SpringBoot电商项目实战 — 商品的SPU/SKU实现

    最近事情有点多,所以系列文章已停止好多天了.今天我们继续Springboot电商项目实战系列文章.到目前为止,整个项目的架构和基础服务已经全部实现,分布式锁也已经讲过了.那么,现在应该到数据库设计及代 ...

  3. Java项目:网上电商项目(前后端分离+java+vue+Springboot+ssm+mysql+maven+redis)

    源码获取:博客首页 "资源" 里下载! 一.项目简述 本系统功能包括: 一款基于Springboot+Vue的电商项目,前后端分离项目,前台后台都有,前台商品展示购买,购物车分类, ...

  4. 项目是采用目前比较流行的 SpringBoot/SpringCloudAlibaba构建新零售微服务电商项目

    简介: 技术架构 项目是采用目前比较流行的 SpringBoot/SpringCloudAlibaba构建新零售微服务电商项目,从项目中台架构技术选型.模块设计.基础设施的构建.分布式解决方 案.互联 ...

  5. 新零售微服务电商项目SpringBoot/SpringCloudAlibaba

    技术架构–项目地址-新零售微服务电商项目 项目是采用目前比较流行的 SpringBoot/SpringCloudAlibaba构建新零售微服务电商项目,从项目中台架构技术选型.模块设计.基础设施的构建 ...

  6. JS任务机制 - springboot实战电商项目mall4j

    springboot实战电商项目mall4j (https://gitee.com/gz-yami/mall4j) java商城系统源码 1.介绍 工作一段时间了,今天在这总结一下浏览器执行JS任务机 ...

  7. SpringBoot+SpringCloud+Mybatis+Vue 电商项目实战,附视频+源码+文档,包含所有主流技术栈。...

    大家好,我是树哥. 今天给大家分享一个电商项目--- 畅购商城.项目采用前后端分离的技术架构. 采用SpringBoot+SpringCloud+Mybatis+Vue为主要技术栈,包括了大型商城的主 ...

  8. SpringBoot+SpringCloud+Mybatis+Vue电商项目实战,附视频+源码+文档,包含所有主流技术栈...

    今天给大家分享一个电商项目--- 畅购商城.项目采用前后端分离的技术架构. 采用SpringBoot+SpringCloud+Mybatis+Vue为主要技术栈,包括了大型商城的主要功能.难点功能以及 ...

  9. 推荐几个9月爆火的 GitHub 电商项目 赶紧收藏

    原文链接:https://mp.weixin.qq.com/s/pBZR6n8gxl19LAIBsH6XPg 逛逛GitHub. 每天推荐一个好玩的 GitHub 开源项目. 01. 新蜂电商 第一个 ...

最新文章

  1. OSX Yosemite,pod install报错RPC failed; result=52,
  2. linux常用系统命令
  3. linux 阶段作业领导者,Linux入职基础-5.22_命令ps显示进程状态(应用实战6)
  4. Go sycn.Map知识点
  5. sql server 2008学习11 UDF用户自定义函数
  6. javaweb学习中的路径问题
  7. mysql导出选择两张表,Mysql导出(多张表)表结构及表数据 mysqldump用法
  8. discuz! 7.2 manyou插件暴路径Get Webshell 0day
  9. 2018年Java展望
  10. Python GStreamer Tutorial
  11. Jmeter(二十三)稳定性测试后的波形图
  12. DC888 : worklist slovers
  13. ubuntu20.04修改mac地址
  14. php配置 验证码无法显示,PHP验证码无法显示的原因及解决办法
  15. 不亏是阿里三面,ConcurrentHashMap多线程扩容机制被面试官装到了
  16. Oracle表空间时间点恢复技术TSPITR
  17. DPDK:UDP 协议栈的实现
  18. 遗传算法(确定性排挤)
  19. CISSP考试指南笔记:1.1安全目标
  20. 8.14-T1村通网(pupil)

热门文章

  1. 南风窗:知识分子的品质是什么
  2. C语言 编程判断花瓶是谁打碎的,C语言解决是谁打碎花瓶的问题
  3. JS中的for循环嵌套
  4. 关于代码评审CodeReview
  5. 关于OnOK()、OnCancel()、OnClose()、OnDestroy()之间的区别
  6. 非证明的推理 | 大师经典「AI核心算法」
  7. 毕设 - 用户登录 用cookie来实现会话跟踪
  8. Game Maker Studio 2表示进入/离开碰撞体
  9. 身份证和银行卡输入时根据规则分析
  10. 虚拟机与本地连接不上时,该怎么办