亲宝软件园·资讯

展开

Java实现迷你图书管理系统案例全程

Java Fans 人气:0

b872f203ebb24b888cc7e36c41fa60d6.jpeg

项目需求

为某图书馆开发一个迷你图书管理系统,实现图书的管理,包括如下功能:

(1)新增图书

(2)查看图书

(3)删除图书

(4)借出图书

(5)归还图书

(6)退出图书系统

覆盖知识

程序基本概念、数据类型、流程控制、顺序、选择 、循环、跳转语句、变量、类、方法、数据库、JDBC等相关知识

掌握数据库、JDBC、三层架构等相关知识。

掌握Druid连接池、Apache的DBUtils使用 。

开发思路

(1)明确需求

(2)编码顺序

1)、添加需要的jar包到项目中,将lib文件夹中的jar文件通过鼠标右单击选择Build Path的方式添加到你设置的eatJar文件目录里。

2)、创建database.properties文件,用来配置注册驱动和数据库连接对象的相关数据。

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/java221804
username=root
password=huanghuang
initialSize=10
maxActive=30
maxIdle=5
maxWait=3000

3)、添加需要的工具类DBUtils类

package cn.book.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.sql.DataSource;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
public class DBUtils {
	private static DruidDataSource druidDataSource;
	static {
		Properties properties = new Properties();
		try {
			InputStream is = DBUtils.class
					.getResourceAsStream("/database.properties");
			properties.load(is);
			druidDataSource = (DruidDataSource) DruidDataSourceFactory
					.createDataSource(properties);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static DataSource getDataSource(){
		return druidDataSource;
	}
}

4)、创建数据表:book表

CREATE DATABASE IF NOT EXISTS `java221804`;
CREATE TABLE IF NOT EXISTS book(
	`name` VARCHAR(20),
	`state` INT,
	`date` INT,
	`count` INT
);

5)、编写book类,包含get/set方法、有参/无参构造、toString方法等

package cn.book.entity;
import java.io.Serializable;
@SuppressWarnings("serial")
public class Book implements Serializable {
	//定义属性
	private String name;
	private int state;
	private int date;
	private int count;
	//添加无参构造
	public Book() {
		super();
	}
	//添加有参构造
	public Book(String name, int state, int date, int count) {
		super();
		this.name = name;
		this.state = state;
		this.date = date;
		this.count = count;
	}
	//添加get/set方法
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getState() {
		return state;
	}
	public void setState(int state) {
		this.state = state;
	}
	public int getDate() {
		return date;
	}
	public void setDate(int date) {
		this.date = date;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
	@Override
	public String toString() {
		return "Book [name=" + name + ", state=" + state + ", date=" + date
				+ ", count=" + count + "]";
	}
}

6)、数据访问层DAO层的接口和实现类的增删改查方法的编写

7)、服务层Service层的接口和实现类的增删改查方法的编写

8)、最后完成视图层View层测试类的编写

开发步骤

1、数据初始化​

2、BookDaoImpl类中的部分重要方法

创建 QueryRunner 对象

private QueryRunner queryRunner = new QueryRunner(DBUtils.getDataSource());

增加图书的方法

	public int insert(Book book) {
		String sql = "insert into book(name,state,date,count) values(?,?,?,?);";
		Object[] args = { book.getName(), book.getState(), book.getDate(),
				book.getCount() };
		try {
			return queryRunner.update(sql, args);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

更改图书信息的方法

	public int update(Book book) {
		String sql="update book set state=?,date=?,count=? where name=?; ";
		Object[] args={book.getState(),book.getDate(),book.getCount(),book.getName()};
		try {
			return queryRunner.update(sql, args);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

查询全部图书的方法

	public List<Book> selectAll() {
		String sql = "SELECT * FROM book;";
		try {
			return queryRunner.query(sql, new BeanListHandler<Book>(Book.class) );
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

欢迎使用迷你图书管理器方法

新增图书方法

查看图书方法

删除图书方法

借出图书方法

归还图书方法

退出图书方法

欢迎首界面:

	public static void useBookSystem() {
		// 输出欢迎菜单
		System.out.println("欢迎使用迷你图书管理器");
		System.out.println("-------------------------");
		System.out.println("1.新增图书");
		System.out.println("2.查看图书");
		System.out.println("3.删除图书");
		System.out.println("4.借出图书");
		System.out.println("5.归还图书");
		System.out.println("6.退出图书");
		System.out.println("-------------------------");
	}

全部代码展示

1、Book类

package cn.book.entity;
import java.io.Serializable;
@SuppressWarnings("serial")
public class Book implements Serializable {
	//定义属性
	private String name;
	private int state;
	private int date;
	private int count;
	//添加无参构造
	public Book() {
		super();
	}
	//添加有参构造
	public Book(String name, int state, int date, int count) {
		super();
		this.name = name;
		this.state = state;
		this.date = date;
		this.count = count;
	}
	//添加get/set方法
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getState() {
		return state;
	}
	public void setState(int state) {
		this.state = state;
	}
	public int getDate() {
		return date;
	}
	public void setDate(int date) {
		this.date = date;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
	@Override
	public String toString() {
		return "Book [name=" + name + ", state=" + state + ", date=" + date
				+ ", count=" + count + "]";
	}
}

2、DBUtils类

(使用连接池DruidDataSource、Apache的知识)

package cn.book.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.sql.DataSource;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
public class DBUtils {
	private static DruidDataSource druidDataSource;
	static {
		Properties properties = new Properties();
		try {
			InputStream is = DBUtils.class
					.getResourceAsStream("/database.properties");
			properties.load(is);
			druidDataSource = (DruidDataSource) DruidDataSourceFactory
					.createDataSource(properties);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static DataSource getDataSource(){
		return druidDataSource;
	}
}

3、数据访问层的BookDao接口

package cn.book.dao;
import java.util.List;
import cn.book.entity.Book;
public interface BookDao {
	// 增
	public int insert(Book book);
	// 删
	public int delete(String name);
	// 改
	public int update(Book book);
	// 查一个
	public Book select(String name);
	// 查全部
	public List<Book> selectAll();
}

4、数据访问层的BookDaoImpl类

package cn.book.dao.impl;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import cn.book.dao.BookDao;
import cn.book.entity.Book;
import cn.book.utils.DBUtils;
public class BookDaoImpl implements BookDao {
	private QueryRunner queryRunner = new QueryRunner(DBUtils.getDataSource());
	@Override
	public int insert(Book book) {
		String sql = "insert into book(name,state,date,count) values(?,?,?,?);";
		Object[] args = { book.getName(), book.getState(), book.getDate(),
				book.getCount() };
		try {
			return queryRunner.update(sql, args);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}
	@Override
	public int delete(String name) {
		String sql="delete from book where name=?;";
		try {
			return queryRunner.update(sql, name);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}
	@Override
	public int update(Book book) {
		String sql="update book set state=?,date=?,count=? where name=?; ";
		Object[] args={book.getState(),book.getDate(),book.getCount(),book.getName()};
		try {
			return queryRunner.update(sql, args);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}
	@Override
	public Book select(String name) {
		String sql = "select * from book where name=?;";
		try {
			return queryRunner.query(sql,new BeanHandler<Book>(Book.class), name);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	@Override
	public List<Book> selectAll() {
		String sql = "SELECT * FROM book;";
		try {
			return queryRunner.query(sql, new BeanListHandler<Book>(Book.class) );
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
}

5、服务层的BookService接口

package cn.book.service;
import java.util.List;
import cn.book.entity.Book;
public interface BookService {
	// 增
	public int insertBook(Book book);
	// 删
	public int deleteBook(String name);
	// 改
	public int updateBook(Book book);
	// 查一个
	public Book selectBook(String name);
	// 查全部
	public List<Book> selectAllBooks();
}

6、服务层的BookServiceImpl类

package cn.book.service.impl;
import java.util.List;
import cn.book.dao.impl.BookDaoImpl;
import cn.book.entity.Book;
import cn.book.service.BookService;
public class BookServiceImpl implements BookService {
	BookDaoImpl bookDaoImpl = new BookDaoImpl();
	@Override
	public int insertBook(Book book) {
		if (bookDaoImpl.select(book.getName()) == null) {
			return bookDaoImpl.insert(book);
		}
		return 0;
	}
	@Override
	public int deleteBook(String name) {
		if (bookDaoImpl.select(name) != null) {
			return bookDaoImpl.delete(name);
		}
		return 0;
	}
	@Override
	public int updateBook(Book book) {
		if (bookDaoImpl.select(book.getName()) != null) {
			return bookDaoImpl.update(book);
		}
		return 0;
	}
	@Override
	public Book selectBook(String name) {
		bookDaoImpl.select(name);
		return null;
	}
	@Override
	public List<Book> selectAllBooks() {
		List<Book> listBooks = bookDaoImpl.selectAll();
		return listBooks;
	}
}

7、视图层BookMgr测试类

package cn.book.view;
import java.util.List;
import java.util.Scanner;
import cn.book.entity.Book;
import cn.book.service.impl.BookServiceImpl;
public class BookMgr {
	// 定义一个静态的Scanner
	static Scanner inputsc = new Scanner(System.in);
	// 是否退出系统,false代表退出系统
	static boolean flag = true;
	static int num = -1;
	static BookServiceImpl bookServiceImpl = new BookServiceImpl();
	// 欢迎使用迷你图书管理器方法
	public static void useBookSystem() {
		// 输出欢迎菜单
		System.out.println("欢迎使用迷你图书管理器");
		System.out.println("-------------------------");
		System.out.println("1.新增图书");
		System.out.println("2.查看图书");
		System.out.println("3.删除图书");
		System.out.println("4.借出图书");
		System.out.println("5.归还图书");
		System.out.println("6.退出图书");
		System.out.println("-------------------------");
	}
	// 新增图书方法
	public static void addBook() {
		System.out.println("-->新增图书\n");
		System.out.println("请输入图书名称:");
		String bookName = inputsc.next();
		Book book = new Book(bookName, 0, 0, 0);
		// 向数据库添加图书
		int num = bookServiceImpl.insertBook(book);
		System.out.println();
		if (num != 0) {
			System.out.println("新增《" + bookName + "》成功!");
		} else {
			System.out.println("新增《" + bookName + "》失败!");
		}
		System.out.println("*****************************************");
	}
	// 查看图书方法
	public static void lookBook() {
		System.out.println("-->查看图书\n");
		System.out.println("序号\t状态\t名称\t借出日期\t借出次数");
		// 获取数据库全部图书
		List<Book> books = bookServiceImpl.selectAllBooks();
		for (int i = 0; i < books.size(); i++) {
			String BookState = (books.get(i).getState() == 0) ? "可借阅" : "已借出";
			String dateStr = (books.get(i).getDate() == 0) ? "" : (books.get(i)
					.getDate() + "日");
			System.out.println((i + 1) + "\t" + BookState + "\t"
					+ books.get(i).getName() + "\t" + dateStr + "\t"
					+ books.get(i).getCount() + "次");
		}
		System.out.println("*****************************************");
	}
	// 删除图书方法
	public static void delBook() {
		System.out.println("-->删除图书\n");
		System.out.println("请输入要删除图书的名称:");
		String deleteBook = inputsc.next();
		// 从数据库中查找此图书
		Book delBook = bookServiceImpl.selectBook(deleteBook);
		boolean flag3 = false;
		// 删除的图书存在、状态处于可借阅状态
		if (delBook.getName() != null && deleteBook.equals(delBook.getName())
				&& delBook.getState() == 0) {
			flag3 = true;
			int num = bookServiceImpl.deleteBook(delBook.getName());
			if (num != 0) {
				System.out.println("图书删除成功!");
			} else {
				System.out.println("图书删除失败!");
			}
		} else if (delBook.getName() != null
				&& deleteBook.equals(delBook.getName())
				&& delBook.getState() == 1) {
			flag3 = true;
			System.out.println("该图书已被借出,目前无法删除!");
		}
		if (!flag3) {
			System.out.println("没有找到匹配信息!");
		}
		System.out.println("*****************************************");
	}
	// 借出图书方法
	public static void lendBook() {
		System.out.println("-->借出图书\n");
		System.out.print("请输入图书名称:");
		String want = inputsc.next(); // 要借出的图书名称
		// 从数据库中查找此图书
		Book wantBook = bookServiceImpl.selectBook(want);
		if (wantBook == null) {
			System.out.println("没有找到匹配信息!");
		} else {
			if (want.equals(wantBook.getName()) && wantBook.getState() == 0) { // 找到匹配可借
				wantBook.setState(1); // 将此图书置于借出状态
				System.out.print("请输入借出日期:");
				int inputscData = inputsc.nextInt();
				wantBook.setDate(inputscData);
				while (wantBook.getDate() < 1 || wantBook.getDate() > 31) { // 当输入借出的日期不满足1-31时
					System.out.println("必须输入大于等于1且小于等于31的数字,请重新输入:");
					inputscData = inputsc.nextInt();
					wantBook.setDate(inputscData);
				}
				wantBook.setCount(wantBook.getCount() + 1);
				// 更新书本最新信息
				int num = bookServiceImpl.updateBook(wantBook);
				if (num != 0) {
					System.out.println("借出《" + want + "》成功!");
				} else {
					System.out.println("借出《" + want + "》失败!");
				}
			} else if (want.equals(wantBook.getName())
					&& wantBook.getState() == 1) { // 找到匹配已被借出
				System.out.println("《" + want + "》已被借出!");
			}
		}
		System.out.println("*****************************************");
	}
	// 归还图书方法
	public static void returnBook() {
		System.out.println("-->归还图书\n");
		int charge = 0; // 租金
		System.out.print("请输入归还图书名称:");
		String back = inputsc.next();
		// 从数据库中查找此图书
		Book backBook = bookServiceImpl.selectBook(back);
		if (backBook == null) {
			System.out.println("没有找到匹配信息!");
		} else {
			if (back.equals(backBook.getName()) && backBook.getDate() == 1) {// 找到匹配
				backBook.setDate(0); // 将借阅状态修改为可借阅
				System.out.print("请输入归还日期:");
				int redate = inputsc.nextInt();
				while (redate < backBook.getDate() || redate > 31) { //
					// 归还日期不能小于借出日期,也不能大于31
					if (redate < backBook.getDate()) {
						System.out.println("归还日期不能小于借出日期,请重新输入:");
					} else {
						System.out.println("一个月只有31天,请重新输入:");
					}
					redate = inputsc.nextInt();
				}
				charge = redate - backBook.getDate();
				// 更新书本最新信息
				int num = bookServiceImpl.updateBook(backBook);
				if (num != 0) {
					System.out.println("\n归还《" + back + "》成功!");
					System.out.println("借出日期为:" + (backBook.getDate() + 1)
							+ "日");
					System.out.println("归还日期为:" + redate + "日");
					System.out.println("应付租金(元):" + charge);
					backBook.setDate(0);
				} else {
					System.out.println("借出《" + back + "》失败!");
				}
			} else if (back.equals(backBook.getName())
					&& backBook.getState() == 0) {// 找到匹配但没有借出
				System.out.println("该图书没有被借出!无法进行归还操作。");
			}
		}
		System.out.println("*****************************************");
	}
	// 操作
	public static void runTest() {
		// 循环操作
		do {
			// 定义一个BookMethod操作类,将操作方法定义在BookMethod类中,然后调用
			// 欢迎菜单方法
			BookMgr.useBookSystem();
			System.out.println("请选择:");
			int choose = inputsc.nextInt();
			switch (choose) {
			case 1:
				// 新增图书
				BookMgr.addBook();
				break;
			case 2:
				// 查看图书
				BookMgr.lookBook();
				break;
			case 3:
				// 删除图书
				BookMgr.delBook();
				break;
			case 4:
				// 借出图书
				BookMgr.lendBook();
				break;
			case 5:
				// 归还图书
				BookMgr.returnBook();
				break;
			case 6:
				// 退出图书
				flag = false;
				break;
			default:
				flag = false;
				break;
			}
			if (flag) {
				System.out.println("输入0返回:");
				num = inputsc.nextInt();
			} else {
				break;
			}
		} while (num == 0);
		System.out.println("谢谢使用!");
	}
	public static void main(String[] args) {
		BookMgr.runTest();
	}
}

加载全部内容

相关教程
猜你喜欢
用户评论