Library management system based on spring MVC

        This is my own learning experience after learning the Spring framework and according to the reference and improvement of other people's projects, I have realized a relatively basic library management system. Well, I won't say much nonsense. Let's get to the point.

1, Project overview

Functional requirements description

Library management system is a typical information management system. Its development mainly includes the following parts: the establishment and maintenance of background database and the development of front-end application.
For the former, a database with strong data consistency and integrity and good data security should be established. For the latter, what is needed is that the application is fully functional and easy to use.

Design Overview

1. The interface design is simple and friendly (easy for human-computer interaction)
2. The information classification is clear and accurate (all books, book borrowing and user information)
3. Improve better query ability (support fuzzy query)
4. Support library staff to borrow and return books

Realize function

1. The librarian manages the books
2. Administrator's management of borrower (Reader) information
3. The administrator manages the return of books borrowed by borrowers
4. Administrator login management
5. User borrowing query, personal information query, borrowing information query, etc
6. Password change for administrator / user

Function display

Sign in

login interface

Operation as Administrator

The home page after logging in as an administrator, where you can carry out book related operations

The administrator manages readers

The administrator can view the borrowing and returning records of all users

User (Reader) identity operation

The home page after logging in as a user (Reader), where you can carry out book related operations

Users (Readers) modify personal account information

Users (Readers) view personal loan and return records

User \ administrator password modification

2, Detailed system design

1. Construction of large framework

To write a project well, the first and most important thing is to build the framework of the project. With a framework, writing a project will not be in a hurry, it will become planned and regular, and the efficiency can be improved.
According to the three-tier architecture of spring MVC, we can divide the project into these three parts:

  • Model is the part of an application that processes the application data logic. Usually, model objects are responsible for accessing data in the database.
  • A View is the part of an application that processes the display of data. Usually, a View is created based on model data.
  • The Controller is the part of the application that handles user interaction. Usually, the Controller is responsible for reading data from the view, controlling user input, and sending data to the model.

On top of these three models, it can be subdivided:

  • dao layer: this layer is the data persistence layer. The so-called data persistence requires dealing with the database. Therefore, this layer needs to do operations on the database, such as adding, deleting, changing and searching books.
  • controller layer: this layer is the control layer, which controls the data interaction and logical operations between the front-end interface and the background, such as reading data from the page and sending data. (specific business)
  • Entity layer: this layer is the entity layer, which places entities and their corresponding set and get methods. If you want to perform some operations (such as reading) on the database, you must first write the entity layer.
  • Service layer: this layer is the service layer, which is responsible for data interaction and logical operation (business between modules)

After the construction of the large framework is completed, the preparation for the project can be carried out below!

2. Preliminary preparations for the project

The preliminary preparations for the project include:

Related technologyname
front endjsp,css,html,JQuery,BootStrap
back-endSpringMVC,Mybatis
databaseMysql
development environment IDEA

The expected functions are:

rolefunction
Ordinary user (borrower)Book inquiry (view all books), personal information (view or modify personal information), borrowing and returning, password modification
administratorsLibrary management (view all books, add books), reader management (view all readers, add Readers), borrowing and returning management, and change password
Person not logged inLog in to the system and enter the administrator or ordinary user interface

The project document framework is as follows:

  1. book: there are controller, Dao, entity and service in it
  2. resources: put xml and other configuration files inside
  3. webapp: put things related to web pages, static (put statically loaded files, css,images,js), WEB-INF (jsp,web.xml files, etc.)
  4. pom.xml file: import related dependency packages through maven remote warehouse
  5. Mybatis mapping file: find the corresponding sql statement through mybatis mapping

The project structure is shown in the figure:

The preparatory work in the early stage of the project is basically completed. The following is the implementation of various logical methods in the project

3, Detailed implementation of each function

There are many chapters in this chapter. You can read it slowly or choose your favorite part. Don't say much and start the project!

1. Create spring configuration file

Because the project is based on the spring framework, the spring configuration file is needed to inject bean classes

<!-- Scan class package and label Spring Annotated classes are automatically converted to Bean´╝îSimultaneous completion Bean Injection of  -->
        <context:component-scan base-package="com.book.dao"/>
        <context:component-scan base-package="com.book.service"/>

    <!--  Define the data source of a database connection pool -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close"
          p:driverClassName="com.mysql.cj.jdbc.Driver"
          p:url="jdbc:mysql://localhost:3306/spring_book?useUnicode=true&amp;characterEncoding=UTF8"
            p:username="root"
          p:password="123456"/>
    <!-- JDBC Template Bean -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
          p:dataSource-ref="dataSource"/>

2. Configure mybatis

db.properties:

#mysql jdbc
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/library?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456

pom.xml

 <!--mybatis-spring Adapter -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
        <!-- mybatis ORM frame -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>
        <!--jdbc Connection pool-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.18</version>
        </dependency>
        <!--paging-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.2.0</version>
        </dependency>

3. Realize login service

First create the administrator entity class Admin and the common borrowing user entity class ReadCard
Implement getter and setter methods

private long admin_id;
    private String password;
    private String username;

    public long getAdminId() {
        return admin_id;
    }

    public void setAdminId(long admin_id) {
        this.admin_id = admin_id;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

Setters and getter s of ReadCard are omitted here, and the following are the same. Only the corresponding entity attributes are written

	private long reader_id;
    private String username;
    private String password;

Start writing Dao data access layer interface and implementation class:
Interface:

public interface AdminDao {
    int getMatchCount(final long admin_id, final String password);
    int resetPassword(final long admin_id, final String password);
    String getPassword(final long admin_id);
    String getUsername(final long admin_id);
}
public interface ReaderCardDao {
    int getIdMatchCount(final long reader_id, final String password);
    ReaderCard findReaderByReaderId(final long reader_id);
    int resetPassword(final long reader_id, final String newPassword);
    int addReaderCard(final ReaderInfo readerInfo, final String password);
    String getPassword(final long reader_id);
    int deleteReaderCard(final long reader_id);
}

Implementation class: take AdminDao interface AdminDaoImpl as an example

@Repository
public class AdminDaoImpl implements AdminDao {

    private final static String NAMESPACE = "com.book.dao.impl.AdminDaoImpl.";
    @Resource
    private SqlSessionTemplate sqlSessionTemplate;

    @Override
    public int getMatchCount(final long admin_id, final String password) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("admin_id", admin_id);
        paramMap.put("password", password);
        return sqlSessionTemplate.selectOne(NAMESPACE + "getMatchCount", paramMap);
    }

    @Override
    public int resetPassword(final long admin_id, final String password) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("admin_id", admin_id);
        paramMap.put("password", password);
        return sqlSessionTemplate.update(NAMESPACE + "resetPassword", paramMap);
    }

    @Override
    public String getPassword(final long admin_id) {
        return sqlSessionTemplate.selectOne(NAMESPACE + "getPassword", admin_id);
    }

    @Override
    public String getUsername(final long admin_id) {
        return sqlSessionTemplate.selectOne(NAMESPACE + "getUsername", admin_id);
    }

}

Start writing Service layer interface and implementation class:
LoginService definition method:

	boolean hasMatchReader(long readerId,String password);

    String getAdminUsername(long adminId);

    ReaderCard findReaderCardByReaderId(long readerId);

    boolean hasMatchAdmin(long adminId,String password);

    boolean adminRePassword(long adminId, String newPassword);

    String getAdminPassword(long adminId);

    boolean readerRePassword(long readerId, String newPassword);

    String getReaderPassword(long readerId);

Corresponding implementation class write logic method
Inject data interaction to access the database through the data interaction layer and realize the login function

@Service
public class LoginServiceImpl implements LoginService{

    @Autowired
    private ReaderCardDaoImpl readerCardDaoImpl;
    @Autowired
    private AdminDaoImpl adminDaoImpl;

    @Override
    public boolean hasMatchReader(long readerId, String password){
        return  readerCardDaoImpl.getIdMatchCount(readerId, password)>0;
    }

    @Override
    public String getAdminUsername(long adminId) {
        return adminDaoImpl.getUsername(adminId);
    }

    @Override
    public ReaderCard findReaderCardByReaderId(long readerId){
        return readerCardDaoImpl.findReaderByReaderId(readerId);
    }

    @Override
    public boolean hasMatchAdmin(long adminId, String password){
        return adminDaoImpl.getMatchCount(adminId, password) == 1;
    }

    @Override
    public boolean adminRePassword(long adminId, String newPassword){
        return adminDaoImpl.resetPassword(adminId,newPassword)>0;
    }
    @Override
    public String getAdminPassword(long adminId){
        return adminDaoImpl.getPassword(adminId);
    }

    @Override
    public boolean readerRePassword(long readerId, String newPassword) {
        return readerCardDaoImpl.resetPassword(readerId, newPassword) > 0;
    }

    @Override
    public String getReaderPassword(long readerId) {
        return readerCardDaoImpl.getPassword(readerId);
    }


}

4. Administrator business implementation

(1) Implementation of related services

Business related to login

@Autowired
    private ReaderCardDaoImpl readerCardDaoImpl;
    @Autowired
    private AdminDaoImpl adminDaoImpl;

    @Override
    public boolean hasMatchReader(long readerId, String password){
        return  readerCardDaoImpl.getIdMatchCount(readerId, password)>0;
    }

    @Override
    public String getAdminUsername(long adminId) {
        return adminDaoImpl.getUsername(adminId);
    }

    @Override
    public ReaderCard findReaderCardByReaderId(long readerId){
        return readerCardDaoImpl.findReaderByReaderId(readerId);
    }

    @Override
    public boolean hasMatchAdmin(long adminId, String password){
        return adminDaoImpl.getMatchCount(adminId, password) == 1;
    }

    @Override
    public boolean adminRePassword(long adminId, String newPassword){
        return adminDaoImpl.resetPassword(adminId,newPassword)>0;
    }
    @Override
    public String getAdminPassword(long adminId){
        return adminDaoImpl.getPassword(adminId);
    }

    @Override
    public boolean readerRePassword(long readerId, String newPassword) {
        return readerCardDaoImpl.resetPassword(readerId, newPassword) > 0;
    }

    @Override
    public String getReaderPassword(long readerId) {
        return readerCardDaoImpl.getPassword(readerId);
    }

Book related business

@Autowired
    private BookDaoImpl bookDaoImpl;

    @Override
    public PageInfo<Book> queryBook(String searchWord,int pageNum,int pageSize) {
        //paging
        PageHelper.startPage(pageNum,pageSize);
        ArrayList<Book> list = bookDaoImpl.queryBook(searchWord);
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;

    }

    @Override
    public PageInfo<Book> getAllBooks(int pageNum,int pageSize) {
        //paging
        PageHelper.startPage(pageNum,pageSize);
        ArrayList<Book> list = bookDaoImpl.getAllBooks();
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

    @Override
    public boolean matchBook(String searchWord) {
        return bookDaoImpl.matchBook(searchWord) > 0;
    }

    @Override
    public boolean addBook(Book book) {
        return bookDaoImpl.addBook(book) > 0;
    }

    @Override
    public Book getBook(Long bookId) {
        return bookDaoImpl.getBook(bookId);
    }

    @Override
    public boolean editBook(Book book) {
        return bookDaoImpl.editBook(book) > 0;
    }

    @Override
    public boolean deleteBook(Long bookId) {
        return bookDaoImpl.deleteBook(bookId) > 0;
    }

    @Override
    public ArrayList<Type> getAllTypes() {
        return bookDaoImpl.getAllTypes();
    }

    //Through book_id find the corresponding type, and then find the book_ Class number and category name corresponding to ID
    @Override
    public Type getTypesById(Long bookId) {
        return bookDaoImpl.getTypesById(bookId);
    }

(2) Data operation of related business

Administrator login

private final static String NAMESPACE = "com.book.dao.impl.AdminDaoImpl.";
    @Resource
    private SqlSessionTemplate sqlSessionTemplate;

    @Override
    public int getMatchCount(final long admin_id, final String password) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("admin_id", admin_id);
        paramMap.put("password", password);
        return sqlSessionTemplate.selectOne(NAMESPACE + "getMatchCount", paramMap);
    }

    @Override
    public int resetPassword(final long admin_id, final String password) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("admin_id", admin_id);
        paramMap.put("password", password);
        return sqlSessionTemplate.update(NAMESPACE + "resetPassword", paramMap);
    }

    @Override
    public String getPassword(final long admin_id) {
        return sqlSessionTemplate.selectOne(NAMESPACE + "getPassword", admin_id);
    }

    @Override
    public String getUsername(final long admin_id) {
        return sqlSessionTemplate.selectOne(NAMESPACE + "getUsername", admin_id);
    }

Library management

private final static String NAMESPACE = "com.book.dao.impl.BookDaoImpl.";
    @Resource
    private SqlSessionTemplate sqlSessionTemplate;

    @Override
    public int matchBook(final String searchWord) {
        String search = "%" + searchWord + "%";
        return sqlSessionTemplate.selectOne(NAMESPACE + "matchBook", search);
    }

    @Override
    public ArrayList<Book> queryBook(final String searchWord) {
        String search = "%" + searchWord + "%";
        List<Book> result = sqlSessionTemplate.selectList(NAMESPACE + "queryBook", search);
        return (ArrayList<Book>) result;
    }

    @Override
    public ArrayList<Book> getAllBooks() {
        List<Book> result = sqlSessionTemplate.selectList(NAMESPACE + "getAllBooks");
        return (ArrayList<Book>) result;
    }

    @Override
    public int addBook(final Book book) {
        return sqlSessionTemplate.insert(NAMESPACE + "addBook", book);
    }

    @Override
    public Book getBook(final long bookId) {
        return sqlSessionTemplate.selectOne(NAMESPACE + "getBook", bookId);
    }

    @Override
    public int editBook(final Book book) {
        return sqlSessionTemplate.update(NAMESPACE + "editBook", book);
    }

    @Override
    public int deleteBook(final long bookId) {
        return sqlSessionTemplate.delete(NAMESPACE + "deleteBook", bookId);
    }

    @Override
    public ArrayList<Type> getAllTypes() {
        List<Type> result = sqlSessionTemplate.selectList(NAMESPACE + "getAllTypes");
        return (ArrayList<Type>) result;
    }

    @Override
    public Type getTypesById(final long TypeId){
        return sqlSessionTemplate.selectOne(NAMESPACE + "getTypesById", TypeId);
    }

(3) mybatis database operation

admin.xml

<select id="getMatchCount" resultType="int">
        select count(*) from admin
        where admin_id = #{admin_id}
        and password = #{password}
    </select>
    <update id="resetPassword">
        update admin set password = #{password}
        where admin_id = #{admin_id}
    </update>
    <select id="getPassword" resultType="String" parameterType="long">
        select password from admin where admin_id = #{admin_id}
    </select>
    <select id="getUsername" resultType="String" parameterType="long">
        select username from admin where admin_id = #{admin_id}
    </select>

book.xml

<select id="getAllTypes" resultType="com.book.entity.Type">
        select * from class_info
    </select>
    <select id="getTypesById" resultType="com.book.entity.Type" parameterType="long">
        select c.class_id,c.class_name
        from book_info b inner join class_info c on b.class_id = c.class_id and b.book_id = #{book_id}
    </select>
    <insert id="addBook" parameterType="com.book.entity.Book">
        insert into book_info values
        (null, #{name}, #{author}, #{publish}, #{ISBN},
        #{introduction}, #{language}, #{price}, #{pub_date}, #{picture},
        #{class_id}, #{number})
    </insert>
    <update id="editBook" parameterType="com.book.entity.Book">
        update book_info set name=#{name}, author=#{author},
        publish=#{publish}, ISBN=#{ISBN}, introduction=#{introduction},
        language=#{language}, price=#{price}, pub_date=#{pub_date},picture=#{picture},
        class_id=#{class_id}, number=#{number} where book_id=#{book_id}
    </update>
    <select id="getAllBooks" resultType="com.book.entity.Book">
        select * from book_info
    </select>
    <select id="queryBook" resultType="com.book.entity.Book" parameterType="String">
        select * from book_info where name like #{search}
        or author like #{search} or introduction like #{search}
    </select>
    <select id="matchBook" resultType="int" parameterType="String">
        select count(*) from book_info where name like #{search}
        or author like #{search} or introduction like #{search}
    </select>
    <select id="getBook" resultType="com.book.entity.Book" parameterType="long">
        select * from book_info where book_id = #{book_id}
    </select>
    <delete id="deleteBook" parameterType="long">
        delete from book_info where book_id = #{book_id}
    </delete>

(4) Interaction of related businesses

Interactive operation of login service

//Responsible for processing loginCheck.html requests
    //The request parameter will be automatically bound to the input parameter of the corresponding method according to the default contract of the parameter name
    @RequestMapping(value = "/api/loginCheck", method = RequestMethod.POST)
    public @ResponseBody
    Object loginCheck(HttpServletRequest request) {
        long id = Long.parseLong(request.getParameter("id"));
        String passwd = request.getParameter("passwd");
        boolean isReader = loginServiceImpl.hasMatchReader(id, passwd);
        boolean isAdmin = loginServiceImpl.hasMatchAdmin(id, passwd);
        HashMap<String, String> res = new HashMap<>();
        if (isAdmin) {
            Admin admin = new Admin();
            admin.setAdminId(id);
            admin.setPassword(passwd);
            String username = loginServiceImpl.getAdminUsername(id);
            admin.setUsername(username);
            request.getSession().setAttribute("admin", admin);
            res.put("stateCode", "1");
            res.put("msg", "Administrator login succeeded!");
        } else if (isReader) {
            ReaderCard readerCard = loginServiceImpl.findReaderCardByReaderId(id);
            request.getSession().setAttribute("readercard", readerCard);
            res.put("stateCode", "2");
            res.put("msg", "Readers log in successfully!");
        } else {
            res.put("stateCode", "0");
            res.put("msg", "Wrong account or password!");
        }
        return res;
    }

    @RequestMapping("/admin_main.html")
    public ModelAndView toAdminMain(HttpServletResponse response) {
        return new ModelAndView("admin_main");
    }

    @RequestMapping("/reader_main.html")
    public ModelAndView toReaderMain(HttpServletResponse response) {
        return new ModelAndView("reader_main");
    }

    @RequestMapping("/admin_repasswd.html")
    public ModelAndView reAdminPasswd() {
        return new ModelAndView("admin_repasswd");
    }

Interactive operation of book business

@RequestMapping("/querybook.html")
    public ModelAndView queryBookDo(String searchWord,@RequestParam(required = false,defaultValue = "1")int pageNum,@RequestParam(required = false,defaultValue = "10")int pageSize) {
        if (bookServiceImpl.matchBook(searchWord)) {
            PageInfo<Book> pageInfo = bookServiceImpl.queryBook(searchWord,pageNum,pageSize);
            ModelAndView modelAndView = new ModelAndView("admin_books");
            modelAndView.addObject("pageInfo", pageInfo);
            return modelAndView;
        } else {
            return new ModelAndView("admin_books", "error", "No matching books");
        }
    }

    @RequestMapping("/reader_querybook_do.html")
    public ModelAndView readerQueryBookDo(String searchWord,@RequestParam(required = false,defaultValue = "1")int pageNum,@RequestParam(required = false,defaultValue = "10")int pageSize) {
        if (bookServiceImpl.matchBook(searchWord)) {
            PageInfo<Book> pageInfo = bookServiceImpl.queryBook(searchWord,pageNum,pageSize);
            ModelAndView modelAndView = new ModelAndView("reader_books");
            modelAndView.addObject("pageInfo", pageInfo);
            return modelAndView;
        } else {
            return new ModelAndView("reader_books", "error", "No matching books");
        }
    }

    @RequestMapping("/admin_books.html")
    public ModelAndView adminBooks(@RequestParam(required = false,defaultValue = "1")int pageNum,@RequestParam(required = false,defaultValue = "10")int pageSize) {
        PageInfo<Book> pageInfo = bookServiceImpl.getAllBooks(pageNum,pageSize);
        ModelAndView modelAndView = new ModelAndView("admin_books");
        modelAndView.addObject("pageInfo", pageInfo);
        return modelAndView;
    }

    @RequestMapping("/book_add.html")
    public ModelAndView addBook() {
        ArrayList<Type> types = bookServiceImpl.getAllTypes();
        ModelAndView modelAndView = new ModelAndView("admin_book_add");
        modelAndView.addObject("types",types);
        return modelAndView;
    }

5. User (Reader) service implementation

(1) Implementation of related services

Borrowing related business

@Autowired
    private LendDaoImpl lendDaoImpl;

    @Override
    public boolean returnBook(long bookId, long readerId){
        return lendDaoImpl.returnBookOne(bookId, readerId)>0 && lendDaoImpl.returnBookTwo(bookId)>0;
    }

    @Override
    public boolean lendBook(long bookId, long readerId, String name){
        return lendDaoImpl.lendBookOne(bookId,readerId,name)>0 && lendDaoImpl.lendBookTwo(bookId)>0;
    }

    @Override
    public PageInfo<Lend> lendList(int pageNum,int pageSize){
        //paging
        PageHelper.startPage(pageNum,pageSize);
        ArrayList<Lend> list = lendDaoImpl.lendList();
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }
    @Override
    public PageInfo<Lend> myLendList(long readerId,int pageNum,int pageSize){
        //paging
        PageHelper.startPage(pageNum,pageSize);
        ArrayList<Lend> list = lendDaoImpl.myLendList(readerId);
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

    @Override
    public int deleteLend(long serNum) {
        return lendDaoImpl.deleteLend(serNum);
    }

Reader related business

@Autowired
    private ReaderInfoDaoImpl readerInfoDaoImpl;

    @Override
    public PageInfo<ReaderInfo> readerInfos(int pageNum,int pageSize) {
        //paging
        PageHelper.startPage(pageNum,pageSize);
        ArrayList<ReaderInfo> list = readerInfoDaoImpl.getAllReaderInfo();
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

    @Override
    public boolean deleteReaderInfo(long readerId) {
        return readerInfoDaoImpl.deleteReaderInfo(readerId) > 0;
    }

    @Override
    public ReaderInfo getReaderInfo(long readerId) {
        return readerInfoDaoImpl.findReaderInfoByReaderId(readerId);
    }

    @Override
    public boolean editReaderInfo(ReaderInfo readerInfo) {
        return readerInfoDaoImpl.editReaderInfo(readerInfo) > 0;
    }

    @Override
    public boolean editReaderCard(ReaderInfo readerInfo) {
        return readerInfoDaoImpl.editReaderCard(readerInfo) > 0;
    }

    @Override
    public long addReaderInfo(ReaderInfo readerInfo) {
        return readerInfoDaoImpl.addReaderInfo(readerInfo);
    }

(2) Data operation of related business

Borrow books

@Resource
    private SqlSessionTemplate sqlSessionTemplate;

    private final static String NAMESPACE = "com.book.dao.impl.LendDaoImpl.";

    @Override
    public int returnBookOne(final long book_id, long reader_id) {
        Map<String, Object> map = new HashMap<>();
        map.put("book_id", book_id);
        map.put("reader_id", reader_id);
        return sqlSessionTemplate.update(NAMESPACE + "returnBookOne", map);
    }

    @Override
    public int returnBookTwo(final long book_id) {
        return sqlSessionTemplate.update(NAMESPACE + "returnBookTwo", book_id);
    }

    @Override
    public int lendBookOne(final long book_id, final long reader_id,final String name) {
        Map<String, Object> map = new HashMap<>();
        map.put("book_id", book_id);
        map.put("reader_id", reader_id);
        map.put("name",name);
        return sqlSessionTemplate.insert(NAMESPACE + "lendBookOne", map);
    }

    @Override
    public int lendBookTwo(final long book_id) {
        return sqlSessionTemplate.update(NAMESPACE + "lendBookTwo", book_id);
    }

    @Override
    public ArrayList<Lend> lendList() {
        List<Lend> result = sqlSessionTemplate.selectList(NAMESPACE + "lendList");
        return (ArrayList<Lend>) result;
    }

    @Override
    public ArrayList<Lend> myLendList(final long reader_id) {
        List<Lend> result = sqlSessionTemplate.selectList(NAMESPACE + "myLendList", reader_id);
        return (ArrayList<Lend>) result;
    }

    @Override
    public int deleteLend(final long ser_num) {
        return sqlSessionTemplate.delete(NAMESPACE + "deleteLend", ser_num);
    }

Reader information management

private final static String NAMESPACE = "com.book.dao.impl.ReaderInfoDaoImpl.";
    @Resource
    private SqlSessionTemplate sqlSessionTemplate;

    @Override
    public ArrayList<ReaderInfo> getAllReaderInfo() {
        List<ReaderInfo> result = sqlSessionTemplate.selectList(NAMESPACE + "getAllReaderInfo");
        return (ArrayList<ReaderInfo>) result;
    }

    @Override
    public ReaderInfo findReaderInfoByReaderId(final long reader_id) {
        return sqlSessionTemplate.selectOne(NAMESPACE + "findReaderInfoByReaderId", reader_id);
    }

    @Override
    public int deleteReaderInfo(final long reader_id) {
        return sqlSessionTemplate.delete(NAMESPACE + "deleteReaderInfo", reader_id);
    }

    @Override
    public int editReaderInfo(final ReaderInfo readerInfo) {
        return sqlSessionTemplate.update(NAMESPACE + "editReaderInfo", readerInfo);
    }

    @Override
    public int editReaderCard(final ReaderInfo readerInfo) {
        return sqlSessionTemplate.update(NAMESPACE + "editReaderCard", readerInfo);
    }

    @Override
    public final long addReaderInfo(final ReaderInfo readerInfo) {
        if (sqlSessionTemplate.insert(NAMESPACE + "addReaderInfo", readerInfo) > 0) {
            return sqlSessionTemplate.selectOne(NAMESPACE + "getReaderId", readerInfo);
        } else {
            return -1;
        }
    }

(3) mybatis database operation

lend.xml

<update id="returnBookOne">
        update lend_list set back_date = sysdate() where book_id = #{book_id}
        and reader_id = #{reader_id} and back_date is null
    </update>
    <update id="returnBookTwo" parameterType="long">
        update book_info set number = number + 1 where book_id = #{book_id}
    </update>
    <insert id="lendBookOne">
        insert into lend_list values
        (null , #{book_id} , #{reader_id} , sysdate() , null, #{name})
    </insert>
    <update id="lendBookTwo" parameterType="long">
        update book_info set number = number - 1 where book_id = #{book_id}
    </update>
    <select id="lendList" resultType="com.book.entity.Lend">
        select * from lend_list
    </select>
    <select id="myLendList" resultType="com.book.entity.Lend" parameterType="long">
        select * from lend_list where reader_id = #{reader_id}
    </select>
    <delete id="deleteLend" parameterType="long">
        delete from lend_list where ser_num = #{ser_num}
    </delete>

readerInfo.xml

<select id="getAllReaderInfo" resultType="com.book.entity.ReaderInfo">
        select * from reader_info
    </select>
    <select id="findReaderInfoByReaderId" resultType="com.book.entity.ReaderInfo" parameterType="long">
        select * from reader_info where reader_id = #{reader_id}
    </select>
    <delete id="deleteReaderInfo" parameterType="long">
        delete from reader_info where reader_id = #{reader_id}
    </delete>
    <update id="editReaderInfo" parameterType="com.book.entity.ReaderInfo">
        update reader_info set name = #{name} , sex = #{sex},
        birth = #{birth} ,address = #{address} ,phone = #{phone}
        where reader_id = #{reader_id}
    </update>
    <update id="editReaderCard" parameterType="com.book.entity.ReaderInfo">
        update reader_card set username = #{name}
        where reader_id = #{reader_id}
    </update>
    <insert id="addReaderInfo" parameterType="com.book.entity.ReaderInfo">
        insert into reader_info values
        (null, #{name},#{sex},#{birth},#{address},#{phone})
    </insert>
    <select id="getReaderId" resultType="long" parameterType="com.book.entity.ReaderInfo">
        select reader_id from reader_info where
        name = #{name} and sex = #{sex} and
        birth = #{birth} and address = #{address}
        and phone = #{phone}
    </select>

(4) Interaction of related businesses

Interactive operation of borrowing business

@Autowired
    private BookServiceImpl bookServiceImpl;

    @RequestMapping("/deletebook.html")
    public String deleteBook(HttpServletRequest request, RedirectAttributes redirectAttributes) {
        long bookId = Long.parseLong(request.getParameter("bookId"));
        if (bookServiceImpl.deleteBook(bookId)) {
            redirectAttributes.addFlashAttribute("succ", "Books deleted successfully!");
        } else {
            redirectAttributes.addFlashAttribute("error", "Book deletion failed!");
        }
        return "redirect:/admin_books.html";
    }

    @RequestMapping("/lendlist.html")
    public ModelAndView lendList(HttpServletRequest request,@RequestParam(required = false,defaultValue = "1")int pageNum, @RequestParam(required = false,defaultValue = "10")int pageSize) {
        ModelAndView modelAndView = new ModelAndView("admin_lend_list");
        modelAndView.addObject("pageInfo", lendServiceImpl.lendList(pageNum,pageSize));
        return modelAndView;
    }

    @RequestMapping("/mylend.html")
    public ModelAndView myLend(HttpServletRequest request, @RequestParam(required = false,defaultValue = "1")int pageNum, @RequestParam(required = false,defaultValue = "10")int pageSize) {
        ReaderCard readerCard = (ReaderCard) request.getSession().getAttribute("readercard");
        ModelAndView modelAndView = new ModelAndView("reader_lend_list");
        modelAndView.addObject("pageInfo", lendServiceImpl.myLendList(readerCard.getReaderId(),pageNum,pageSize));
        return modelAndView;
    }

    @RequestMapping("/deletelend.html")
    public String deleteLend(HttpServletRequest request, RedirectAttributes redirectAttributes) {
        long serNum = Long.parseLong(request.getParameter("serNum"));
        if (lendServiceImpl.deleteLend(serNum) > 0) {
            redirectAttributes.addFlashAttribute("succ", "Record deleted successfully!");
        } else {
            redirectAttributes.addFlashAttribute("error", "Record deletion failed!");
        }
        return "redirect:/lendlist.html";
    }

    @RequestMapping("/lendbook.html")
    public String bookLend(HttpServletRequest request, RedirectAttributes redirectAttributes) {
        long bookId = Long.parseLong(request.getParameter("bookId"));
        long readerId = ((ReaderCard) request.getSession().getAttribute("readercard")).getReaderId();
        String name = request.getParameter("name");
        if (lendServiceImpl.lendBook(bookId, readerId, name)) {
            redirectAttributes.addFlashAttribute("succ", "Book borrowing succeeded!");
        } else {
            redirectAttributes.addFlashAttribute("succ", "Book borrowing succeeded!");
        }
        return "redirect:/reader_books.html";
    }

Reader business interaction

@Autowired
    private ReaderInfoServiceImpl readerInfoServiceImpl;

    @Autowired
    private LoginServiceImpl loginServiceImpl;

    @Autowired
    private ReaderCardServiceImpl readerCardServiceImpl;

    private ReaderInfo getReaderInfo(long readerId, String name, String sex, String birth, String address, String phone) {
        ReaderInfo readerInfo = new ReaderInfo();
        Date date = new Date();
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            date = df.parse(birth);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        readerInfo.setAddress(address);
        readerInfo.setName(name);
        readerInfo.setReaderId(readerId);
        readerInfo.setPhone(phone);
        readerInfo.setSex(sex);
        readerInfo.setBirth(date);
        return readerInfo;
    }

    @RequestMapping("allreaders.html")
    public ModelAndView allBooks(@RequestParam(required = false,defaultValue = "1")int pageNum,@RequestParam(required = false,defaultValue = "10")int pageSize) {
        PageInfo<ReaderInfo> pageInfo = readerInfoServiceImpl.readerInfos(pageNum,pageSize);
        ModelAndView modelAndView = new ModelAndView("admin_readers");
        modelAndView.addObject("pageInfo", pageInfo);
        return modelAndView;
    }

    @RequestMapping("reader_delete.html")
    public String readerDelete(HttpServletRequest request, RedirectAttributes redirectAttributes) {
        long readerId = Long.parseLong(request.getParameter("readerId"));
        if (readerInfoServiceImpl.deleteReaderInfo(readerId) && readerCardServiceImpl.deleteReaderCard(readerId)) {
            redirectAttributes.addFlashAttribute("succ", "Delete succeeded!");
        } else {
            redirectAttributes.addFlashAttribute("error", "Deletion failed!");
        }
        return "redirect:/allreaders.html";
    }

    @RequestMapping("/reader_info.html")
    public ModelAndView toReaderInfo(HttpServletRequest request) {
        ReaderCard readerCard = (ReaderCard) request.getSession().getAttribute("readercard");
        ReaderInfo readerInfo = readerInfoServiceImpl.getReaderInfo(readerCard.getReaderId());
        ModelAndView modelAndView = new ModelAndView("reader_info");
        modelAndView.addObject("readerinfo", readerInfo);
        return modelAndView;
    }

    @RequestMapping("reader_edit.html")
    public ModelAndView readerInfoEdit(HttpServletRequest request) {
        long readerId = Long.parseLong(request.getParameter("readerId"));
        ReaderInfo readerInfo = readerInfoServiceImpl.getReaderInfo(readerId);
        ModelAndView modelAndView = new ModelAndView("admin_reader_edit");
        modelAndView.addObject("readerInfo", readerInfo);
        return modelAndView;
    }

    @RequestMapping("reader_edit_do.html")
    public String readerInfoEditDo(HttpServletRequest request, String name, String sex, String birth, String address, String phone, RedirectAttributes redirectAttributes) {
        long readerId = Long.parseLong(request.getParameter("readerId"));
        ReaderInfo readerInfo = getReaderInfo(readerId, name, sex, birth, address, phone);
        if (readerInfoServiceImpl.editReaderInfo(readerInfo) && readerInfoServiceImpl.editReaderCard(readerInfo)) {
            redirectAttributes.addFlashAttribute("succ", "Reader information modified successfully!");
        } else {
            redirectAttributes.addFlashAttribute("error", "Reader information modification failed!");
        }
        return "redirect:/allreaders.html";
    }

    @RequestMapping("reader_add.html")
    public ModelAndView readerInfoAdd() {
        return new ModelAndView("admin_reader_add");
    }

    @RequestMapping("reader_add_do.html")
    public String readerInfoAddDo(String name, String sex, String birth, String address, String phone, String password, RedirectAttributes redirectAttributes) {
        ReaderInfo readerInfo = getReaderInfo(0, name, sex, birth, address, phone);
        long readerId = readerInfoServiceImpl.addReaderInfo(readerInfo);
        readerInfo.setReaderId(readerId);
        if (readerId > 0 && readerCardServiceImpl.addReaderCard(readerInfo, password)) {
            redirectAttributes.addFlashAttribute("succ", "Reader information added successfully!");
        } else {
            redirectAttributes.addFlashAttribute("succ", "Failed to add reader information!");
        }
        return "redirect:/allreaders.html";
    }

    @RequestMapping("reader_info_edit.html")
    public ModelAndView readerInfoEditReader(HttpServletRequest request) {
        ReaderCard readerCard = (ReaderCard) request.getSession().getAttribute("readercard");
        ReaderInfo readerInfo = readerInfoServiceImpl.getReaderInfo(readerCard.getReaderId());
        ModelAndView modelAndView = new ModelAndView("reader_info_edit");
        modelAndView.addObject("readerinfo", readerInfo);
        return modelAndView;
    }

    @RequestMapping("reader_edit_do_r.html")
    public String readerInfoEditDoReader(HttpServletRequest request, String name, String sex, String birth, String address, String phone, RedirectAttributes redirectAttributes) {
        ReaderCard readerCard = (ReaderCard) request.getSession().getAttribute("readercard");
        ReaderInfo readerInfo = getReaderInfo(readerCard.getReaderId(), name, sex, birth, address, phone);
        if (readerInfoServiceImpl.editReaderInfo(readerInfo) && readerInfoServiceImpl.editReaderCard(readerInfo)) {
            ReaderCard readerCardNew = loginServiceImpl.findReaderCardByReaderId(readerCard.getReaderId());
            request.getSession().setAttribute("readercard", readerCardNew);
            redirectAttributes.addFlashAttribute("succ", "Information modified successfully!");
        } else {
            redirectAttributes.addFlashAttribute("error", "Information modification failed!");
        }
        return "redirect:/reader_info.html";
    }

Tags: Java Mybatis Spring Back-end

Posted on Thu, 04 Nov 2021 01:07:27 -0400 by mattfoster