SSM简单图书项目的后端代码

        基于之前的环境搭建,继续创建后端中的主要代码。

        由于具体执行过程应该由前端发请求➡️Contoller➡️Service➡️Mapper,那我们可以根据前端需求,先写Mapper层,再写Service层,最后写Controller层。

一、注册

        1.1 注册Mapper层

        先在mapper包下创建RegisterMapper的接口

        在注册时,前端会向后端传三个参数-----String username、String password以及头像图片MultipartFile avatarImg,那么后端可以先对username进行判断,判断数据库中是否已存在该username,若存在,则提示前端注册失败,若不存在,则调用对应方法进行注册。由于Users类中有username、password以及avatarImg成员变量,所以可以用Users来进行封装(其中,对于头像图片MultipartFile avatarImg的处理,我们使用别的接口来处理)。

        其中的代码为(本项目Mapper层结合注解和xml文件来访问数据库)

package com.xxx.mapper;

import com.xxx.pojo.Users;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

public interface RegisterMapper {

    //根据用户名查找用户,看用户名是否已经存在
    @Select("select * from users where username=#{username}")
    public Users selectByName(@Param("username") String username);

    //注册---只能注册普通用户
    public void register(Users users);

}

        对于xml文件来访问数据库,需要在resources包下创建与java包下的mapper接口对应的文件路径的接口名

        RegisterMapper.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.xxx.mapper.RegisterMapper">
    <insert id="register" parameterType="users">
        <selectKey keyColumn="id" keyProperty="id" resultType="int" order="AFTER">
            SELECT LAST_INSERT_ID();
        </selectKey>
        insert into users (username, password) values (#{username},#{password})
    </insert>
</mapper>

        其中的<selectKey>是为了后续在插入时获取对应的id

        1.2 注册Service层

        首先,在service包下创建对应的注册Service接口,以及在service包下创建一个img包用来存放每个Serivce接口对应的实现类

        RegisterService的代码

package com.xxx.service;

import org.springframework.web.multipart.MultipartFile;

public interface RegisterService {

    public boolean register(String username, String password, MultipartFile avatarImg);
}

        ResgisterServiceImp的代码

package com.xxx.service.imp;

import com.xxx.mapper.RegisterMapper;
import com.xxx.pojo.Users;
import com.xxx.service.RegisterService;
import com.xxx.service.UserProfileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class RegisterServiceImp implements RegisterService {

    @Autowired
    private RegisterMapper registerMapper;

    @Autowired
    private BookshelfServiceImp bookshelfServiceImp;

    @Autowired
    private UserProfileService userProfileService;

    @Override
    public boolean register(String username, String password, MultipartFile avatarImg) {
        Users users = registerMapper.selectByName(username);
        if (users == null) {
            users = new Users();
            users.setUsername(username);
            users.setPassword(password);
            registerMapper.register(users);
            if (avatarImg != null){
                userProfileService.updateAvatarImg(avatarImg, users.getId());
            }
            //注册新用户后,需要在bookshelf中创建这新用户对应所有书籍的记录
            bookshelfServiceImp.insertBookshelfForUid(users.getId());
            return true;
        }
        return false;
    }
}

        其中的userProfileService.updateAvatarImg()是用来处理MultipartFile avatarImg,将其图片存到指定位置,并将路径存到对应用户的数据库信息中;bookshelfServiceImp.insertBookshelfForUid()则是在创建新用户后,相当于给新用户建立一个对应的书架。

        1.3 注册Controller层

        首先在controller包下创建RegisterController类

        RegisterController代码

package com.ljj.controller;

import com.xxx.service.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class RegisterController {

    @Autowired
    private RegisterService registerService;

    @PostMapping("/register")
    public String register(
            @RequestParam(value = "username") String username,
            @RequestParam(value = "password") String password,
            @RequestParam(value = "avatarImg", required = false)MultipartFile avatarImg) {
        boolean flag = registerService.register(username, password,avatarImg);
        if (flag){
            return "success";
        }
        return "error";
    }

}

二、登录

        2.1 登录Mapper层

        首先在mapper包下创建LoginMapper接口

        LoginMapper的代码

package com.xxx.mapper;

import com.xxx.pojo.Users;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

public interface LoginMapper {

    //登录----管理员
    @Select("select * from users where username=#{username} and password=#{password} and identity=1")
    public Users loginAdmin(@Param("username") String username,@Param("password") String password);

    //登录----普通用户
    @Select("select * from users where username=#{username} and password=#{password}")
    public Users loginUsers(@Param("username") String username,@Param("password") String password);

}

          (因为这两个方法要执行的sql语句不复杂,所以不对LoginMapper创建额外的xml文件)

        2.2 登录的Service层

        首先在service包在创建LoginService接口和对应的LoginServiceImp实体类

        LoginService代码 

package com.xxx.service;

import com.xxx.pojo.Users;

public interface LoginService {

    public Users loginAdmin(String username, String password);

    public Users loginUser(String username, String password);

}

        LoginServiceImp代码

package com.xxx.service.imp;

import com.xxx.mapper.LoginMapper;
import com.xxx.pojo.Users;
import com.xxx.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImp implements LoginService {

    @Autowired
    private LoginMapper loginMapper;

    @Override
    public Users loginAdmin(String username, String password) {
        return loginMapper.loginAdmin(username, password);
    }

    @Override
    public Users loginUser(String username, String password) {
        return loginMapper.loginUsers(username, password);
    }
}

        2.3 登录的Controller层

        首先在controller包下创建LoginController类

        LoginController的代码

package com.xxx.controller;

import com.xxx.pojo.Users;
import com.xxx.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {
    @Autowired
    private LoginService loginService;

    @GetMapping("/login/{identity}/{username}/{password}")
    public Users login(@PathVariable Integer identity, @PathVariable String username, @PathVariable String password){
        Users users;
        if (identity == 1){
            users = loginService.loginAdmin(username, password);
        }else {
            users = loginService.loginUser(username, password);
        }
        return users;
    }
}

三、Books模块

        (该模块中,我的Controller层的命名与Servcie和Mapper没有统一,虽然不影响代码的运行,但是不建议这样做!!需要注意⚠️⚠️)

        3.1 Mapper层

        首先在mapper包下创建BooksMapper接口

        BooksMapper的代码

package com.xxx.mapper;

import com.xxx.pojo.Books;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Map;

public interface BooksMapper {
    //查询指定用户的首页书籍显示
    public List<Books> selectBooksByUId(Integer uid);

    //查看指定书籍id的书名、作者、内容
    @Select("select bookname,author,filePath from books where id=#{id}")
    public Books lookBookById(Integer id);

    //查询数据库中含有的所有书籍类型
    @Select("select distinct type from books")
    public List<String> selectAllBookType();

    //更改书籍的状态---xml
    public void changeBookStatus(Map<String,Object> map);

    //批量更改书籍的状态---xml
    public void batchChangeBookStatus(Map<String,Object> map);

    //根据书名、作者、类型查找书籍--xml
    public List<Books> selectBookByNameAndAuthorAndType(Map<String,Object> map);

    //根据id删除书籍----管理员特有
    @Delete("delete from books where id=#{id}")
    public int deleteBookById(int id);

    //根据id批量删除书籍----管理员特有---xml
    public void batchDeleteBookById(Integer[] ids);

    //增加书籍-----管理员特有----xml
    public int insertBook(Books books);

    //修改书籍----管理员特有-----xml
    public int updateBook(Books book);
}

        再在resources/com/xxx/mapper中创建对应的BooksMapper.xml文件(这个文件的命名必须要与mapper层中的BooksMapper接口保持一致)

        BooksMapper.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.xxx.mapper.BooksMapper">

    <!--查询指定用户的首页书籍显示-->
    <select id="selectBooksByUId" parameterType="int">
        select b.*,bs.status from books b
            left join bookshelf bs on b.id=bs.bid
                where bs.uid=#{uid}
    </select>

    <!--更改书籍状态-->
    <update id="changeBookStatus" parameterType="map">
        update bookshelf
        <set>
            <if test="books.status==1">
                status=0
            </if>
            <if test="books.status==0">
                status=1
            </if>
        </set>
        where uid=#{uid} and bid=#{books.id}
    </update>

    <!--批量更改书籍的状态-->
    <update id="batchChangeBookStatus" parameterType="map">
        update bookshelf
        <set>
            status = case
                when status=1 then 0
                when status=0 then 1
            end
        </set>
        where uid=#{uid} and bid in
        <foreach collection="ids" item="item" separator="," open="(" close=")">
            #{item}
        </foreach>
    </update>

    <!--批量删除书籍-->
    <delete id="batchDeleteBookById">
        delete from books where id in
        <foreach collection="array" open="(" item="id" separator="," close=")">
            #{id}
        </foreach>
    </delete>

    <!--根据书名、作者、类型查找书籍-->
    <select id="selectBookByNameAndAuthorAndType" parameterType="map">
        select * from books b
            left join bookshelf bs on b.id=bs.bid
        <where>
            bs.uid=#{uid}
            <if test="books.bookname != null">
                and b.bookname like concat('%',#{books.bookname},'%')
            </if>
            <if test="books.author != null">
                and b.author like concat('%',#{books.author},'%')
            </if>
            <if test="books.type != null">
                and b.type = #{books.type}
            </if>
        </where>
    </select>

    <!--增加书籍-&#45;&#45;&#45;&#45;管理员特有-->
    <insert id="insertBook" parameterType="books">
        <selectKey keyColumn="id" keyProperty="id" resultType="int" order="AFTER">
            SELECT LAST_INSERT_ID();
        </selectKey>
        insert into books
        <trim prefix="(" suffixOverrides="," suffix=")">
            <if test="bid != null">
                bid,
            </if>
            <if test="bookname != null">
                bookname,
            </if>
            <if test="author != null">
                author,
            </if>
            <if test="type != null">
                type,
            </if>
            <if test="filePath != null">
                filePath,
            </if>
        </trim>
        <trim prefix="values (" suffixOverrides="," suffix=")">
            <if test="bid != null">
                #{bid},
            </if>
            <if test="bookname != null">
                #{bookname},
            </if>
            <if test="author != null">
                #{author},
            </if>
            <if test="type != null">
                #{type},
            </if>
            <if test="filePath != null">
                #{filePath}
            </if>
        </trim>
    </insert>

    <!--修改书籍&#45;&#45;&#45;&#45;管理员特有-->
    <update id="updateBook" parameterType="books">
        update books
        <set>
            <if test="bid != null">
                bid = #{bid},
            </if>
            <if test="bookname != null">
                bookname = #{bookname},
            </if>
            <if test="author != null">
                author = #{author},
            </if>
            <if test="type != null">
                type = #{type},
            </if>
            <if test="filePath != null">
                filePath = #{filePath}
            </if>
        </set>
        where id = #{id}
    </update>

</mapper>

         3.2 Service层

        也是先建包

        BooksService代码

package com.xxx.service;

import com.xxx.pojo.Books;
import com.xxx.pojo.LookBook;

import java.util.List;
import java.util.Map;

public interface BooksService {

    //查看指定书籍id内容
    public LookBook lookBookById(Integer id);

    //查询数据库中含有的所有书籍类型
    public List<String> selectAllBookType();

    //更改书籍的状态
    public void changeBookStatus(Integer uid,Integer id,Short status);

    //批量更改书籍的状态---xml
    public void batchChangeBookStatus(Integer uid, Integer[] ids);


    //根据书名和类型查找书籍
    public List<Books> selectBookByNameAndAuthorAndType(Integer uid,String bookname,String author,String type);

    //根据id删除书籍----管理员特有
    public int deleteBookById(int id);

    //根据id批量删除书籍----管理员特有
    public void batchDeleteBookById(Integer[] ids);

    //增加书籍-----管理员特有
    public void insertBook(Map<String,String> map);

    //修改书籍----管理员特有
    public int updateBook(Map<String,String> map);

}

         BooksServiceImp代码

package com.xxx.service.imp;

import com.xxx.mapper.BooksMapper;
import com.xxx.pojo.Books;
import com.xxx.pojo.LookBook;
import com.xxx.service.BooksService;
import com.xxx.service.BookshelfService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BooksServiceImp implements BooksService {

    @Autowired
    private BooksMapper booksMapper;
    @Autowired
    private BookshelfService bookshelfService;

    @Override
    public LookBook lookBookById(Integer id) {
        Books books = booksMapper.lookBookById(id);
        LookBook lookBook = new LookBook();
        if (books.getFilePath() != null){
            StringBuffer sb = new StringBuffer();
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(books.getFilePath()), "UTF-8"));
                String line;
                while ((line = reader.readLine()) != null){
                    sb.append(line).append("\n");
                }
                lookBook.setContent(sb.toString());
            }  catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        lookBook.setBookname(books.getBookname());
        lookBook.setAuthor(books.getAuthor());
        return lookBook;

    }

    @Override
    public List<String> selectAllBookType() {
        return booksMapper.selectAllBookType();
    }

    @Override
    public void changeBookStatus(Integer uid,Integer id, Short status) {
        Books books = new Books();
        books.setId(id);
        books.setStatus(status);
        Map<String,Object> map = new HashMap<>();
        map.put("uid",uid);
        map.put("books",books);
        System.out.println(map);
        booksMapper.changeBookStatus(map);
    }

    @Override
    public void batchChangeBookStatus(Integer uid, Integer[] ids) {
        Map<String,Object> map = new HashMap<>();
        map.put("uid",uid);
        map.put("ids",ids);
        booksMapper.batchChangeBookStatus(map);
    }

    @Override
    public List<Books> selectBookByNameAndAuthorAndType(Integer uid,String bookname,String author, String type) {
        Books books = new Books();
        if (!bookname.isEmpty()){
            books.setBookname(bookname);
        }
        if (!author.isEmpty()){
            books.setAuthor(author);
        }
        if (!type.isEmpty()){
            books.setType(type);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("uid",uid);
        map.put("books",books);
        System.out.println(map);
        return booksMapper.selectBookByNameAndAuthorAndType(map);
    }

    @Override
    public int deleteBookById(int id) {
        return booksMapper.deleteBookById(id);
    }

    @Override
    public void batchDeleteBookById(Integer[] ids) {
        booksMapper.batchDeleteBookById(ids);
    }

    @Override
    public void insertBook(Map<String,String> map) {
        Books books = new Books();
        try {
            BeanUtils.populate(books,map);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        booksMapper.insertBook(books);
        System.out.println(books);
        //在books中新建书籍后,需要在bookshelf中新建书籍
        bookshelfService.insertBookshelfForBid(books.getId());
    }

    @Override
    public int updateBook(Map<String,String> map) {
        Books books = new Books();
        try {
            BeanUtils.populate(books,map);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        return booksMapper.updateBook(books);
    }
}

        3.3 Controller层

        也是要先在controller包下创建LibraryController类(这里的Controller类没有与Service和Mapper起名保持一致,应该也起名叫BooksController)

        LibraryController代码

package com.xxx.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xxx.pojo.Books;
import com.xxx.pojo.LookBook;
import com.xxx.service.BooksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/library")
public class LibraryController {

    @Autowired
    private BooksService booksService;

    @GetMapping(value = "/lookBookById")
    public LookBook lookBookById(@RequestParam(value = "id") Integer id) {
        return booksService.lookBookById(id);
    }

    @GetMapping("/selectAllBookType")
    public List<String> selectAllBookType() {
        return booksService.selectAllBookType();
    }

    @GetMapping("/selectPagedBooks")
    public Map<String, Object> selectPagedBooks(
            @RequestParam(value = "uid") Integer uid,
            @RequestParam(value = "page",defaultValue = "1") Integer page,
            @RequestParam(value = "size",defaultValue = "5") Integer size,
            @RequestParam(value = "bookname") String bookname,
            @RequestParam(value = "author") String author,
            @RequestParam(value = "type") String type
            ) {
        PageHelper.startPage(page,size);
        List<Books> list = booksService.selectBookByNameAndAuthorAndType(uid,bookname,author,type);
        PageInfo<Books> booksPageInfo = new PageInfo<Books>(list);
        List<Books> booksPageInfoList = booksPageInfo.getList();
        Map<String,Object> map = new HashMap<>();
        map.put("booksList",booksPageInfoList);
        map.put("total",booksPageInfo.getTotal());
        return map;
    }

    @GetMapping("/changeBookStatus/{uid}/{id}/{status}")
    public void changeBookStatus(@PathVariable Integer uid,@PathVariable Integer id,@PathVariable Short status) {
        System.out.println(status);
        booksService.changeBookStatus(uid,id, status);
    }

    @GetMapping("/batchChangeBookStatus")
    public void batchChangeBookStatus(
            @RequestParam(value = "uid") Integer uid,
            @RequestParam(value = "ids") Integer[] ids
    ) {
        booksService.batchChangeBookStatus(uid,ids);
    }





}

四、用户信息模块

        (目前只做了头像修改的功能)

        4.1 用户信息Mapper层

          在mapper包下创建UserProfileMapper接口

         UserProfileMapper代码

package com.xxx.mapper;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;

public interface UserProfileMapper {

    //修改用户头像
    @Update("update users set avatarImg=#{avatarImg} where id=#{uid}")
    public void updateAvatarImg(@Param("avatarImg") String avatarImg, @Param("uid") Integer uid);

}

        4.2 用户信息Service层

        先建类

        UserProfileService代码

package com.xxx.service;

import org.springframework.web.multipart.MultipartFile;

public interface UserProfileService {

    //修改用户头像
    public String updateAvatarImg(MultipartFile avatarImg, Integer uid);

}

        UserProfileServiceImp代码

package com.xxx.service.imp;

import com.xxx.mapper.UserProfileMapper;
import com.xxx.service.UserProfileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Service
public class UserProfileServiceImp implements UserProfileService {

    @Autowired
    private UserProfileMapper userProfileMapper;

    @Override
    public String updateAvatarImg(MultipartFile avatarImg, Integer uid) {
        String avatarImgOriginalFilename = "user" + uid + "_" + avatarImg.getOriginalFilename();
        userProfileMapper.updateAvatarImg(avatarImgOriginalFilename, uid);
        try {
            String pathname = "F:\\dongfang\\总代码\\vue-project\\library-project\\public\\avatarImg\\" + avatarImgOriginalFilename;
            //将文件数据复制到指定位置
            avatarImg.transferTo(new File(pathname));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return avatarImgOriginalFilename;
    }
}

        4.3 用户信息Controller层

        新建类

        UserProfileController代码

package com.xxx.controller;

import com.xxx.service.UserProfileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/userProfile")
public class UserProfileController {

    @Autowired
    private UserProfileService userProfileService;

    @PostMapping("/updateAvatarImg")
    public String updateAvatarImg(
            @RequestParam(value = "avatarImg")MultipartFile avatarImg,
            @RequestParam(value = "uid") Integer uid){
        return userProfileService.updateAvatarImg(avatarImg,uid);
    }

}

五、书架模块

        5.1 书架Mapper层

         

        BookshelfMapper代码

 

package com.xxx.mapper;

import com.xxx.pojo.Books;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;
import java.util.Map;

public interface BookshelfMapper {

    //新建书籍在booksmapper执行插入后执行---管理员特有
    public int insertBookshelfForBid(Integer bid);

    //在创建新用户后执行
    public void insertBookshelfForUid(Integer uid);

    //查询指定用户书架中的书籍----xml
    public List<Books> selectBookshelfByUId(Integer uid);

    //查询指定用户书架中的书籍数量
    @Select("select count(*) from bookshelf where uid=#{uid} and status=1")
    public int selectBookshelfCountByUid(Integer uid);

    //根据书名、作者、类型查找当前用户书库中的书籍----xml
    public List<Books> selectBookshelfByUidAndNameAndAuthorAndType(Map<String,Object> map);

    //查询该用户书库中含有的所有书籍类型-----xml
    public List<String> selectAllBooksTypeByUid(Integer uid);

    //将书籍移除书架
    @Update("update bookshelf set status=0 where uid=#{uid} and bid=#{bid}")
    public void removeBook(@Param("uid") Integer uid,@Param("bid") Integer bid);

}

        对应的xml文件 

        BookshelfMapper.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.xxx.mapper.BookshelfMapper">

    <!--新建书籍在booksmapper执行插入后执行-->
    <insert id="insertBookshelfForBid" parameterType="int">
        insert into bookshelf (uid,bid)
        select id,#{bid} from users
    </insert>

    <!--新建用户后执行-->
    <insert id="insertBookshelfForUid" parameterType="int">
        insert into bookshelf (uid,bid)
        select #{uid},id from books
    </insert>

    <!--查询指定用户的书架中的所有书籍类型-->
    <select id="selectAllBooksTypeByUid" parameterType="int">
        select distinct b.type from books b
            left join bookshelf bs on b.id=bs.bid
                where bs.uid=#{uid} and bs.status=1
    </select>

    <!--查询指定用户书架中的书籍-->
    <select id="selectBookshelfByUId" parameterType="int">
        select b.* from books b
            left join bookshelf bs on b.id=bs.bid
                   where bs.uid=#{uid} and bs.status=1
    </select>

    <!--根据书名、作者、类型查找当前用户书库中的书籍-->
    <select id="selectBookshelfByUidAndNameAndAuthorAndType" parameterType="map">
        select * from books b
        left join bookshelf bs on b.id=bs.bid
        <where>
            bs.uid=#{uid} and bs.status=1
            <if test="books.bookname != null">
                and b.bookname like concat('%',#{books.bookname},'%')
            </if>
            <if test="books.author != null">
                and b.author like concat('%',#{books.author},'%')
            </if>
            <if test="books.type != null">
                and b.type = #{books.type}
            </if>
        </where>
    </select>

</mapper>

        5.2 书架Service层

        

         BookshelfService代码

package com.xxx.service;

import com.xxx.pojo.Books;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;
import java.util.Map;

public interface BookshelfService {

    //新建书籍在booksmapper执行插入后执行---管理员特有
    public void insertBookshelfForBid(Integer bid);

    //在创建新用户后执行
    public void insertBookshelfForUid(Integer uid);

    //查询指定用户书库中含有的所有书籍类型
    public List<String> selectAllBooksTypeByUid(Integer uid);

    //查询指定用户书架中的书籍数量
    public int selectBookshelfCountByUid(Integer uid);

    //查询指定用户书架中的书籍
    public List<Books> selectBookshelfByUId(Integer uid);

    //根据书名、作者、类型查找当前用户书库中的书籍----xml
    public List<Books> selectBookshelfByUidAndNameAndAuthorAndType(Integer uid,String bookname,String author,String type);

    //将书籍移除书架
    public void removeBook(Integer uid,Integer bid);

}

        BookshelfServiceImp代码

package com.xxx.service.imp;

import com.xxx.mapper.BookshelfMapper;
import com.xxx.pojo.Books;
import com.xxx.service.BookshelfService;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BookshelfServiceImp implements BookshelfService {

    @Autowired
    private BookshelfMapper bookshelfMapper;

    @Override
    public void insertBookshelfForBid(Integer bid) {
        bookshelfMapper.insertBookshelfForBid(bid);
    }

    @Override
    public void insertBookshelfForUid(Integer uid) {
        bookshelfMapper.insertBookshelfForUid(uid);
    }

    @Override
    public List<String> selectAllBooksTypeByUid(Integer uid) {
        return bookshelfMapper.selectAllBooksTypeByUid(uid);
    }

    @Override
    public int selectBookshelfCountByUid(Integer uid) {
        return bookshelfMapper.selectBookshelfCountByUid(uid);
    }

    @Override
    public List<Books> selectBookshelfByUId(Integer uid) {
        return bookshelfMapper.selectBookshelfByUId(uid);
    }

    @Override
    public List<Books> selectBookshelfByUidAndNameAndAuthorAndType(Integer uid, String bookname,String author,String type) {
        if (bookname.isEmpty()){
            bookname = null;
        }
        if (author.isEmpty()){
            author = null;
        }
        if (type.isEmpty()){
            type = null;
        }
        Books books = new Books();
        books.setBookname(bookname);
        books.setAuthor(author);
        books.setType(type);
        Map<String,Object> map = new HashMap<>();
        map.put("uid",uid);
        map.put("books",books);
        return bookshelfMapper.selectBookshelfByUidAndNameAndAuthorAndType(map);
    }

    @Override
    public void removeBook(Integer uid, Integer bid) {
        bookshelfMapper.removeBook(uid,bid);
    }


}

        5.3 书架Controller层

        BookshelfController代码

package com.xxx.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xxx.pojo.Books;
import com.xxx.service.BookshelfService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/bookshelf")
public class BookshelfController {

    @Autowired
    private BookshelfService bookshelfService;

    @GetMapping("/selectAllBooksTypeByUid")
    public List<String> selectAllBooksTypeByUid(@RequestParam(value = "uid") Integer uid) {
        return bookshelfService.selectAllBooksTypeByUid(uid);
    }

    @GetMapping("/selectBookshelfCountByUid")
    public int selectBookshelfCountByUid(@RequestParam(value = "uid") Integer uid) {
        return bookshelfService.selectBookshelfCountByUid(uid);
    }

    @GetMapping("/selectBookshelfByUidAndNameAndAuthorAndType")
    public Map<String, Object> selectBookshelfByUidAndNameAndAuthorAndType(
            @RequestParam(value = "uid") Integer uid,
            @RequestParam(value = "page",defaultValue = "1") Integer page,
            @RequestParam(value = "size",defaultValue = "5") Integer size,
            @RequestParam(value = "bookname") String bookname,
            @RequestParam(value = "author") String author,
            @RequestParam(value = "type") String type
            ) {

        PageHelper.startPage(page,size);
        List<Books> list = bookshelfService.selectBookshelfByUidAndNameAndAuthorAndType(uid, bookname, author, type);
        PageInfo<Books> booksPageInfo = new PageInfo<Books>(list);
        Map<String,Object> map = new HashMap<>();
        map.put("booksList",list);
        map.put("total",booksPageInfo.getTotal());
        return map;
    }

    @GetMapping("/removeBook")
    public void removeBook(@RequestParam(value = "uid") Integer uid,@RequestParam(value = "bid") Integer bid) {
        bookshelfService.removeBook(uid, bid);
    }

}

六、管理员模块

        这个项目,我把管理员的mapper和service统一写在books中,所以管理员模块只有Controller层(不建议这样写,应该分开来,每个模块对应要有mapper层、service层、controller层)

        AdminController代码

package com.ljj.controller;

import com.ljj.service.BooksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private BooksService booksService;

    @GetMapping("/deleteBookById/{id}")
    public void deleteBookById(@PathVariable int id){
        booksService.deleteBookById(id);
    }

    @GetMapping("/batchDeleteBookById")
    public void batchDeleteBookById(@RequestParam(value = "ids") Integer[] ids) {
        booksService.batchDeleteBookById(ids);
    }

    @PostMapping("/insertBook")
    public void insertBook(@RequestParam("file") MultipartFile file, @RequestParam Map<String,String> map) {
        try {
            System.out.println(file.getName());
            String pathname = "F:\\dongfang\\总代码\\SSM\\SSM_Library\\src\\main\\resources\\file\\"
                    + map.get("id") + "_" + file.getOriginalFilename();
            //将文件数据复制到指定位置
            file.transferTo(new File(pathname));
            map.put("filePath", pathname);
            booksService.insertBook(map);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/updateBook")
    public void updateBook(@RequestParam("file") MultipartFile file,@RequestParam Map<String,String> map){
        try {
            System.out.println(file.getName());
            String pathname = "F:\\dongfang\\总代码\\SSM\\SSM_Library\\src\\main\\resources\\file\\"
                    + map.get("id") + "_" + file.getOriginalFilename();
            //将文件数据复制到指定位置
            file.transferTo(new File(pathname));
            map.put("filePath", pathname);
            booksService.updateBook(map);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值