【SSM】MyBatis(四.MyBatis在web中的应用)
创始人
2025-06-01 18:24:58

文章目录

  • 1.实现一个银行转账
  • 2 实现步骤
    • 2.1环境搭建
    • 2.2 准备页面
    • 2.3创建包
  • 3.完整代码
    • 3.1dao(数据持久层)
    • 3.2 service (业务处理层)
    • 3.3web(表现层)

1.实现一个银行转账

准备数据库和数据库中的数据:
在这里插入图片描述
在这里插入图片描述

2 实现步骤

2.1环境搭建

(1)IDEA中创建Maven WEB应用
在这里插入图片描述
在这里插入图片描述
(2)将web.xml配置为更高的版本
在这里插入图片描述
在这里插入图片描述
即将web.xml更换为:



 

(3)添加依赖

org.mybatismybatis3.5.10mysqlmysql-connector-java5.1.37ch.qos.logbacklogback-classic1.2.11javax.servletjavax.servlet-api4.0.1

(4)配置Tomcat服务器

在这里插入图片描述
在这里插入图片描述

(5)将之前的resources资源拷贝下来
在这里插入图片描述
在这里插入图片描述

(6)修改mybatis-config.xml为下面:





2.2 准备页面



银行账户转账


转出账户:
转入账户:
转出金额:

2.3创建包

在这里插入图片描述
pojo包中建Account

package com.sndu.bank.pojo;/*** 封装账户类** @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;}@Overridepublic String toString() {return "Account{" +"id=" + id +", actno='" + actno + '\'' +", balance=" + balance +'}';}
}

utils包中新建SqlSessionUtil.java

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工具类*/
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 com.sndu.bank.exceptions;/*** 余额不足异常*/
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.完整代码

在这里插入图片描述

3.1dao(数据持久层)

AccountDao.java

package com.sndu.bank.dao;import com.sndu.bank.pojo.Account;/*** 账户的Dao对象,负责表中t_act的CRUD* @author Beyong* @version 1.0* @since 1.0*/
public interface AccountDao {/*** 根据账户查询账户信息* @param actno 账号* @return 账户信息*/Account selectByActno(String actno);/*** 更新账户信息* @param act 要更新的账户* @return 1表示更新成功,其它表示更新失败*/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 {@Overridepublic Account selectByActno(String actno) {SqlSession sqlSession = SqlSessionUtil.openSession();Account account = (Account)sqlSession.selectOne("account.selectByActno", actno);return account;}@Overridepublic int updateByActno(Account act) {SqlSession sqlSession = SqlSessionUtil.openSession();int count = sqlSession.update("account.updateByActno", act);return count;}
}

3.2 service (业务处理层)

package com.sndu.bank.service;import com.sndu.bank.exceptions.MoneyNotEnoughException;
import com.sndu.bank.exceptions.TransferException;/*** 账户业务类* @author Beyong* @version 1.0* @since 1.0*/
public interface AccountService {/*** 转账* @param fromActno 转成账户* @param toActno 转让账户* @param money 转成金额*/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();@Overridepublic void transfer(String fromActno, String toActno, double money) throws MoneyNotEnoughException, TransferException {SqlSession sqlSession = SqlSessionUtil.openSession();//1.判断账户余额是否充足(select)Account fromAct = accountDao.selectByActno(fromActno);if(fromAct.getBalance() < money){//2.如果账户余额不足,通知用户throw  new MoneyNotEnoughException("对不起,余额不足");}//3.如果账户余额充足,转账,更新转出账户余额(update)//先更新内存java账户对象account余额Account toAct = accountDao.selectByActno(toActno);fromAct.setBalance(fromAct.getBalance() - money);toAct.setBalance(toAct.getBalance() + money);int count = accountDao.updateByActno(fromAct);//        //模拟空指针异常
//        String s = null;
//        s.toString();//4.更新转入账户余额count += accountDao.updateByActno(toAct);if(count != 2){throw new TransferException("转账异常");}//提交事务sqlSession.commit();//关闭事务SqlSessionUtil.close(sqlSession);}
}

3.3web(表现层)

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();@Overrideprotected 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"));//调用service方法完成转账(调用业务层)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");}}
}

相关内容

热门资讯

禁毒社工走进网吧,守护清朗网络... 转自:扬子晚报为进一步加强禁毒宣传教育力度,提升网吧从业人员的识毒,防毒,拒毒意识,牢筑娱乐场所禁毒...
微信回应存储空间占用变多:占用...   炒股就看金麒麟分析师研报,权威,专业,及时,全面,助您挖掘潜力主题机会! (来源:澎湃新闻)“...
千年之俗:古风中的徽州 《徽州风俗研究》,黄成林编著,安徽师范大学出版社,2025年12月版一采风化俗是中国古代国家治理的重...
日本年轻人滥用糖尿病药减肥,医... 转自:北京日报客户端新华社北京12月29日电日本媒体发现,一款本应用来治疗糖尿病的药物如今被日本年轻...
冈比亚青年学员为在华减贫培训创... 来源:中华人民共和国农业农村部网站2025年8月21日至9月3日,冈比亚性别、儿童与社会福利部官员穆...