[SSM] MyBatis (4. Application of MyBatis in the web)

Article directory

  • 1. Implement a bank transfer
  • 2 Implementation steps
    • 2.1 Environment Construction
    • 2.2 Prepare the page
    • 2.3 Create package
  • 3. Complete code
    • 3.1dao (data persistence layer)
    • 3.2 service (business processing layer)
    • 3.3web (presentation layer)

1. Implement a bank transfer

Prepare the database and the data in the database:

2 Implementation steps

2.1 Environment construction

(1) Create Maven WEB application in IDEA


(2) Configure web.xml to a higher version


That is to replace web.xml with:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0"
         metadata-complete="true">
</web-app>

(3) Add dependencies

<dependencies>
    <!--mybatis dependency-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.10</version>
    </dependency>
    <!--mysql driver dependency-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.37</version>
    </dependency>
    <!--logback dependency-->
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.2.11</version>
    </dependency>
    <!--servlet dependency-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
    </dependency>
 </dependencies>

(4) Configure the Tomcat server


(5) Copy the previous resources resource

(6) Modify mybatis-config.xml as follows:

<?xml version="1.0" encoding="UTF-8" ?>
<! DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties resource="jdbc.properties"/>
    <environments default="sdnuDB">
        <environment id="sdnuDB">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="AccountMapper.xml"/>
    </mappers>
</configuration>

2.2 Prepare page

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Bank account transfer</title>
</head>
<body>
<form action="/bank/transfer" method="post">
    Transfer-out account: <input type="text" name="fromActno"><br>
    Transfer to account: <input type="text" name="toActno"><br>
    Amount transferred out: <input type="text" name="money"><br>
    <input type="submit" value="transfer">
</form>
</body>
</html>

2.3 Create package


Create an Account in the pojo package

package com.sndu.bank.pojo;

/**
 * Package account class
 *
 * @author Beyong
 * @version 1.0
 * @since 1.0
 */
public class Account {<!-- -->
    private Long id;
    private String actno;
    private double balance;

    public Account() {<!-- -->
    }

    public Account(Long id, String actno, Double balance) {<!-- -->
        this.id = id;
        this.actno = actno;
        this. balance = balance;
    }

    public Long getId() {<!-- -->
        return id;
    }

    public void setId(Long id) {<!-- -->
        this.id = id;
    }

    public String getActno() {<!-- -->
        return actno;
    }

    public void setActno(String actno) {<!-- -->
        this.actno = actno;
    }

    public Double getBalance() {<!-- -->
        return balance;
    }

    public void setBalance(Double balance) {<!-- -->
        this. balance = balance;
    }

    @Override
    public String toString() {<!-- -->
        return "Account{" +
                "id=" + id +
                ", actno='" + actno + '\'' +
                ", balance=" + balance +
                '}';
    }
}

Create a new SqlSessionUtil.java in the utils package

package com.sndu.bank.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

/**
 * mybatis tool class
 */
public class SqlSessionUtil {<!-- -->
    private static SqlSessionFactory sqlSessionFactory;
    private SqlSessionUtil(){<!-- -->}
    static {<!-- -->
        try {<!-- -->
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
        } catch (IOException e) {<!-- -->
            throw new RuntimeException(e);
        }

    }
    public static SqlSession openSession(){<!-- -->
        return sqlSessionFactory. openSession();
    }
}

exception package

package com.sndu.bank.exceptions;

/**
 * Insufficient balance exception
 */
public class MoneyNotEnoughException extends Exception{<!-- -->
    public MoneyNotEnoughException() {<!-- -->
    }
    public MoneyNotEnoughException(String msg) {<!-- -->
        super(msg);
    }
}

package com.sndu.bank.exceptions;

public class TransferException extends Exception{<!-- -->
    public TransferException() {<!-- -->
    }

    public TransferException(String message) {<!-- -->
        super(message);
    }
}

3. Complete code

3.1dao (data persistence layer)

AccountDao.java

package com.sndu.bank.dao;

import com.sndu.bank.pojo.Account;

/**
 * The Dao object of the account, responsible for the CRUD of t_act in the table
 * @author Beyong
 * @version 1.0
 * @since 1.0
 */
public interface AccountDao {<!-- -->
    /**
     * Query account information according to the account
     * @param actno account number
     * @return account information
     */
    Account selectByActno(String actno);

    /**
     * Update account information
     * @param act the account to update
     * @return 1 means the update is successful, other means the update failed
     */
    int updateByActno(Account act);
}

AccountDaoImpl.java

package com.sndu.bank.dao.impl;

import com.sndu.bank.dao.AccountDao;
import com.sndu.bank.pojo.Account;
import com.sndu.bank.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

public class AccountDaoImpl implements AccountDao {<!-- -->
    @Override
    public Account selectByActno(String actno) {<!-- -->
        SqlSession sqlSession = SqlSessionUtil. openSession();
        Account account = (Account)sqlSession.selectOne("account.selectByActno", actno);
        return account;
    }

    @Override
    public int updateByActno(Account act) {<!-- -->
        SqlSession sqlSession = SqlSessionUtil. openSession();
        int count = sqlSession. update("account. updateByActno", act);
        return count;
    }
}

3.2 service (business processing layer)

package com.sndu.bank.service;

import com.sndu.bank.exceptions.MoneyNotEnoughException;
import com.sndu.bank.exceptions.TransferException;

/**
 * Account business class
 * @author Beyong
 * @version 1.0
 * @since 1.0
 */
public interface AccountService {<!-- -->
    /**
     * transfer
     * @param fromActno into account
     * @param toActno transfer account
     * @param money converted into amount
     */
    void transfer(String fromActno, String toActno, double money) throws MoneyNotEnoughException, TransferException;
}

package com.sndu.bank.service.impl;

import com.sndu.bank.dao.AccountDao;
import com.sndu.bank.dao.impl.AccountDaoImpl;
import com.sndu.bank.exceptions.MoneyNotEnoughException;
import com.sndu.bank.exceptions.TransferException;
import com.sndu.bank.pojo.Account;
import com.sndu.bank.service.AccountService;
import com.sndu.bank.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

public class AccountServiceImpl implements AccountService {<!-- -->
    private AccountDao accountDao = new AccountDaoImpl();
    @Override
    public void transfer(String fromActno, String toActno, double money) throws MoneyNotEnoughException, TransferException {<!-- -->
        SqlSession sqlSession = SqlSessionUtil. openSession();
        //1. Determine whether the account balance is sufficient (select)
        Account fromAct = accountDao. selectByActno(fromActno);
        if(fromAct.getBalance() < money){<!-- -->
            //2. If the account balance is insufficient, notify the user
            throw new MoneyNotEnoughException("Sorry, the balance is insufficient");
        }
        //3. If the account balance is sufficient, transfer and update the transferred account balance (update)
        //First update the account balance of the memory java account object
        Account toAct = accountDao. selectByActno(toActno);
        fromAct.setBalance(fromAct.getBalance() - money);
        toAct.setBalance(toAct.getBalance() + money);
        int count = accountDao. updateByActno(fromAct);

// //Simulate null pointer exception
// String s = null;
// s.toString();

        //4. Update the balance of the transferred account
        count + = accountDao. updateByActno(toAct);
        if(count != 2){<!-- -->
            throw new TransferException("Transfer exception");
        }

        //commit transaction
        sqlSession.commit();
        //Close the transaction
        SqlSessionUtil.close(sqlSession);
    }
}

3.3web (presentation layer)

package com.sndu.bank.web;

import com.sndu.bank.exceptions.MoneyNotEnoughException;
import com.sndu.bank.exceptions.TransferException;
import com.sndu.bank.service.AccountService;
import com.sndu.bank.service.impl.AccountServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/transfer")
public class AccountServlet extends HttpServlet {<!-- -->
    private AccountService accountService = new AccountServiceImpl();
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {<!-- -->
        String fromActno = request. getParameter("fromActno");
        String toActno = request. getParameter("toActno");
        double money = Double. parseDouble(request. getParameter("money"));
        //Call the service method to complete the transfer (call the business layer)
        try {<!-- -->
            accountService. transfer(fromActno, toActno, money);
            response.sendRedirect(request.getContextPath() + "/success.html");
        } catch (MoneyNotEnoughException e) {<!-- -->
            response.sendRedirect(request.getContextPath() + "/error1.html");
        } catch (TransferException e) {<!-- -->
            response.sendRedirect(request.getContextPath() + "/error2.html");
        } catch (Exception e){<!-- -->
            response.sendRedirect(request.getContextPath() + "/error2.html");
        }
    }
}