java+mybatis实现一个简单的银行系统,实现存取款与账户查询
先创建数据库和表,使用的是MySQL数据库。
create database mybatis; use mybatis; CREATE TABLE `accountdo` ( `id` varchar(255) NOT NULL COMMENT '账户', `name` varchar(255) DEFAULT NULL COMMENT '用户姓名', `sex` varchar(255) DEFAULT NULL COMMENT '性别', `tele` varchar(255) DEFAULT NULL COMMENT '电话', `address` varchar(255) DEFAULT NULL COMMENT '住址', `balance` double DEFAULT NULL COMMENT '账户余额', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
新建一个Java项目,项目下新建一个lib文件夹,放入mysql-connector-java和mybatis的jar包,build path一下。如果是建的maven项目,在pom.xml加一下坐标即可。
src目录下创建一个conf.xml和一个db.properties
db.properties的内容如下:
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis name=root password=root
password填写自己的密码。
编写一个mybatis工具类,代码如下:
package utils; import java.io.InputStream; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MyBatisUtil { /** * 获取SqlSessionFactory * @return SqlSessionFactory */ public static SqlSessionFactory getSqlSessionFactory() { String resource = "conf.xml"; InputStream is = MyBatisUtil.class.getClassLoader().getResourceAsStream(resource); SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is); return factory; } /** * 获取SqlSession * @return SqlSession */ public static SqlSession getSqlSession() { return getSqlSessionFactory().openSession(); } /** * 获取SqlSession * @param isAutoCommit * true 表示创建的SqlSession对象在执行完SQL之后会自动提交事务 * false 表示创建的SqlSession对象在执行完SQL之后不会自动提交事务,这时就需要我们手动调用sqlSession.commit()提交事务 * @return SqlSession */ public static SqlSession getSqlSession(boolean isAutoCommit) { return getSqlSessionFactory().openSession(isAutoCommit); } }
编写账户实体类,将setId方法改为private,代码如下:
package bank.d; /** * 账户实体类 * * @author xmj * */ public class AccountDO { private String id;// 账户的号码 private String name;// 账户姓名 private String sex;// 性别 private String tele;// 电话 private String address;// 地址 private double balance = 0;// 账户的余额,默认为0 public String getId() { return id; } @SuppressWarnings("unused") private void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getTele() { return tele; } public void setTele(String tele) { this.tele = tele; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } @Override public String toString() { return "\n账号:" + id + " \n姓名:" + name + "\n余额:" + balance; } }
定义sql映射的接口,代码如下:
package bank.i; import java.util.List; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import bank.d.AccountDO; public interface IAccountMapper { // 使用@Insert注解指明add方法要执行的SQL @Insert("insert into AccountDO(id, name,sex,tele,address,balance) values(concat('BANK',DATE_FORMAT(now(),'%Y%m%d%H%i%s'),floor(1000+rand()*8999)), #{name}, #{sex}, #{tele}, #{address}, #{balance})") public int add(AccountDO user); // 使用@Delete注解指明deleteById方法要执行的SQL @Delete("delete from AccountDO where id=#{id}") public int deleteById(String id); // 使用@Update注解指明update方法要执行的SQL @Update("update AccountDO set name=#{name},sex=#{sex} ,tele=#{tele},address=#{address},balance=#{balance} where id=#{id}") public int update(AccountDO user); // 使用@Select注解指明getById方法要执行的SQL @Select("select * from AccountDO where id=#{id}") public AccountDO getById(String id); // 使用@Select注解指明getAll方法要执行的SQL @Select("select * from AccountDO") public List<AccountDO> getAll(); }
在conf.xml文件中注册这个映射接口,代码如下:
<?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> <!-- 引用db.properties配置文件 --> <properties resource="db.properties" /> <!-- development : 开发模式 work : 工作模式 --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <!-- 配置数据库连接信息 --> <dataSource type="POOLED"> <property name="driver" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${name}" /> <property name="password" value="${password}" /> </dataSource> </environment> </environments> <mappers> <!-- 注册IAccountMapper映射接口 --> <mapper class="bank.i.IAccountMapper" /> </mappers> </configuration>
编写一个实现类,封装上面的映射接口里的方法,代码如下:
package bank.s; import java.util.List; import org.apache.ibatis.session.SqlSession; import bank.d.AccountDO; import bank.i.IAccountMapper; import utils.MyBatisUtil; public class AccountMapperImpl { /** * 判断字符串是否为空 * * @param str * @return */ public static boolean isEmpty(String str) { if (str == null || "".equals(str)) return true; return false; } /** * 添加用户 * * @param aggdo */ public static void add(AccountDO aggdo) { if (aggdo == null) return; SqlSession sqlSession = MyBatisUtil.getSqlSession(true); IAccountMapper mapper = sqlSession.getMapper(IAccountMapper.class); int add = mapper.add(aggdo); sqlSession.close(); System.out.println("有【" + add + "】条数据发生了改变"); } /** * 修改 * * @param aggdo */ public static void update(AccountDO aggdo) { if (aggdo == null) return; SqlSession sqlSession = MyBatisUtil.getSqlSession(true); IAccountMapper mapper = sqlSession.getMapper(IAccountMapper.class); @SuppressWarnings("unused") int add = mapper.update(aggdo); // System.out.println("有【" + add + "】条数据发生了改变"); sqlSession.close(); } /** * 修改用户余额 * * @param balance * @param id */ public static void updateBalance(double balance, String id) { if (isEmpty(id)) return; AccountDO user = getById(id); if (user == null) { System.out.println("无法通过【" + id + "】查到该用户信息"); return; } user.setBalance(balance); SqlSession sqlSession = MyBatisUtil.getSqlSession(true); IAccountMapper mapper = sqlSession.getMapper(IAccountMapper.class); @SuppressWarnings("unused") int add = mapper.update(user); sqlSession.close(); // System.out.println("有【" + add + "】条数据发生了改变"); } /** * 通过账号查询用户信息 * * @param id * @return */ public static AccountDO getById(String id) { if (isEmpty(id)) return null; SqlSession sqlSession = MyBatisUtil.getSqlSession(); IAccountMapper mapper = sqlSession.getMapper(IAccountMapper.class); AccountDO lstUsers = mapper.getById(id); sqlSession.close(); return lstUsers; } /** * 获取所有用户信息 * * @return */ public static List<AccountDO> getAll() { SqlSession sqlSession = MyBatisUtil.getSqlSession(); IAccountMapper mapper = sqlSession.getMapper(IAccountMapper.class); List<AccountDO> lstUsers = mapper.getAll(); sqlSession.close(); return lstUsers; } }
编写银行系统类,实现对账户的查询和存取款操作,代码如下:
package bank.bp; import java.util.Scanner; import bank.d.AccountDO; import bank.s.AccountMapperImpl; /** * 银行系统 * * @author xmj * */ public class BankSystem { private AccountDO user;// 当前账户 private double balance;// 余额 /** * 银行操作系统。原存取款都对数据库的数据进行修改,现改成退出系统时才对数据库进行修改 */ public void system(String id) { this.user = AccountMapperImpl.getById(id); if (user == null) { System.out.println("无【" + id + "】此账户"); return; } this.balance = user.getBalance(); double unchang = balance;// 用户刚登陆系统时账户的余额,用来与操作后的balance比较,看余额是否发生改变 System.out.println("------银行账户操作系统-------- "); System.out.println("----------1取款操作------------"); System.out.println("----------2存款操作------------"); System.out.println("----------3账户信息------------"); System.out.println("----------4退出系统------------"); boolean go_on = true; while (go_on) { @SuppressWarnings("resource") Scanner num = new Scanner(System.in); System.out.println("请输入您的选择:"); int choice = num.nextInt(); switch (choice) { case 1: System.out.println("-----正在进行【取款】操作------"); this.withDrawal(); break; case 2: System.out.println("-----正在进行【存款】操作------"); this.deposit(); break; case 3: System.out.println("-----账户信息------"); this.info(); break; case 4: if (unchang != balance) AccountMapperImpl.updateBalance(balance, user.getId()); System.out.println("------退出系统,欢迎下次光临------"); go_on = false; break; default: System.out.println("您的选择有误!"); break; } } } /** * 账户信息 */ private void info() { System.out.println("账号:" + user.getId() + "\n姓名:" + user.getName() + "\n余额:" + this.balance); } /** * 存款 */ private void deposit() { @SuppressWarnings("resource") Scanner balance1 = new Scanner(System.in); System.out.println("请输入您要存入的金额:"); double money = balance1.nextDouble(); balance = balance + money; // AccountMapperImpl.updateBalance(balance, user.getId()); System.out.println("余额:" + balance); } /** * 取款 */ private void withDrawal() { @SuppressWarnings("resource") Scanner balance1 = new Scanner(System.in); System.out.println("请输入您要提取的金额:"); double money = balance1.nextDouble(); if (money > balance) System.out.println("您的余额不足"); else { balance = (balance - money); // AccountMapperImpl.updateBalance(balance, user.getId()); } System.out.println("余额:" + balance); } }
编写测试类,代码如下:
package bank; import bank.bp.BankSystem; import bank.d.AccountDO; import bank.s.AccountMapperImpl; public class BankTest { public static void main(String[] args) { BankSystem s = new BankSystem(); s.system("BANK202103151039575919"); // add(); } public static void add() { AccountDO a = new AccountDO(); a.setName("小马驹"); a.setSex("男"); a.setTele("12345678901"); a.setAddress("北京市"); AccountMapperImpl.add(a); } }
整个项目的结构如图:
第一次写博客。。。