springboot 电商项目

                                    

前言

一、视频查询

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=8181



spring.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.entity


mybatis.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
@AllArgsConstructor

public 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
@Data

public 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 {

    @Autowired
    private 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 {

    @Autowired
    private VideoMapper videoMapper;

    public List<Video> listVideo() {
        return  videoMapper.listVideo();
    }

    @Override
    public List<VideoBanner> listBanner() {
        return videoMapper.listBanner();
    }

    @Override
    public 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">
   SELECT
 v.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 {



    @Bean
    LoginInterceptor loginInterceptor(){
        return  new LoginInterceptor();
    }

    @Override
    public 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();
        }


    }

    @Override
    public 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;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public 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 {

    @Autowired
    private 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"
    };
    @Autowired
    private UserMapper userMapper;

    private String getRandomImg() {
        int size = headImg.length;
        Random random = new Random();
        int index = random.nextInt(size);
        return headImg[index];
    }

   

    @Override
    public 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;

        }
    }

    @Override
    public 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)
    @ResponseBody
    private 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 {

    @Autowired
    private 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 {

    @Autowired
    private VideoOrdeorMapper videoOrdeorMapper;
     @Autowired
     private VideoMapper videoMapper ;
     @Autowired
     private EpisodeMapper episodeMapper ;
     @Autowired
     private PlayRecordMapper playRecordMapper;

    @SneakyThrows
    @Transactional
     public 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;
    }

    @Override
    public 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=8181



spring.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.entity


mybatis.mapper-locations=classpath:mapper/*xml

六.目录

 总结

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
项目是采用目前比较流行的SpringBoot/SpringCloud构建微服务项目项目叫 《果然新鲜》,实现一套串联的微服务项目。完全符合一线城市微服务的需求,对学习微服务架构,有非常大的帮助,该项目涵盖从微服务需求讨论、数据库设计、技术选型、互联网安全架构、整合SpringCloud各自组件、分布式基础设施等实现一套完整的微服务解决方案。 项目使用分布式微服务框架,涉及后台管理员服务、地址服务、物流服务、广告服务、品服务、品类别服务、品牌服务、订单服务 、购物车服务、首页频道服务、公告服务、留言服务、搜索服务、会员服务等。  系统架构图   SpringBoot+SpringCloud+SSM构建微服务项目使用SpringCloud Eureka作为注册中心,实现服务治理使用Zuul网关框架管理服务请求入口使用Ribbon实现本地负载均衡器和Feign HTTP客户端调用工具使用Hystrix服务保护框架(服务降级、隔离、熔断、限流)使用消息总线Stream RabbitMQ和 Kafka微服务API接口安全控制和单点登录系统CAS+JWT+OAuth2.0分布式基础设施构建分布式任务调度平台XXL-JOB分布式日志采集系统ELK分布式事务解决方案LCN分布式锁解决方案Zookeeper、Redis分布式配置中心(携程Apollo)高并发分布式全局ID生成(雪花算法)分布式Session框架Spring-Session分布式服务追踪与调用链Zipkin项目运营与部署环境分布式设施环境,统一采用Docker安装使用jenkins+docker+k8s实现自动部署微服务API管理ApiSwagger使用GitLab代码管理(GitHub  GitEE)统一采用第三方云数据库使用七牛云服务器对静态资源实现加速 开发环境要求JDK统一要求:JDK1.8Maven统一管理依赖 统一采用Docker环境部署编码统一采用UTF-8开发工具IDEA 或者 Eclipse 

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值