运行结果以及包图:
这里要插入两个文件:
文件名和后缀为:database.properties,
内容为:
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/petShop //数据库名字 user=epet //数据库用户名 password=0000 //数据库用户密码
还有一个是Java驱动mysql-connector-java-5.1.0-bin.jar,百度可下载。
用例1:数据库设计
1、数据库设计(这里就给数据和代码)
创表和插入数据这里给出代码:
DROP DATABASE IF EXISTS petShop; CREATE DATABASE petShop; USE petShop; /*创建表*/ CREATE TABLE `petStore`( id INT AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` CHAR(10) NULL, `password` CHAR(10) NULL, `balance` INT(4) NULL )ENGINE=INNODB DEFAULT CHARSET=utf8; CREATE TABLE `petOwner`( id INT(4) AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` CHAR(10) NULL, `password` CHAR(10) NULL, `money` INT(4) NULL )ENGINE=INNODB DEFAULT CHARSET=utf8; CREATE TABLE `pet`( id INT(4) AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` CHAR(10) NOT NULL, `typeName` CHAR(10) NULL, `health` INT(4) NULL, `love` INT(4) NULL, `birthday` TIMESTAMP NULL, `owner_id` INT(4) NULL, `store_id` INT(4) NULL )ENGINE=INNODB DEFAULT CHARSET=utf8; CREATE TABLE `account`( `id` INT(4) AUTO_INCREMENT NOT NULL PRIMARY KEY, `deal_type` INT(4) NULL, `pet_id` INT(4) NULL, `seller_id` INT(4) NULL, `buyer_id` INT(4) NULL, `price` INT(4) NULL, `deal_time` TIMESTAMP NULL )ENGINE=INNODB DEFAULT CHARSET=utf8; /*创建外键*/ ALTER TABLE `account` ADD CONSTRAINT fk_account_pet FOREIGN KEY(pet_id) REFERENCES `pet` (`id`); ALTER TABLE `account` ADD CONSTRAINT fk_account_petOwner FOREIGN KEY(seller_id) REFERENCES `petOwner` (`id`); ALTER TABLE `pet` ADD CONSTRAINT fk_pet_petOwner FOREIGN KEY(owner_id) REFERENCES `petOwner` (`id`) ; ALTER TABLE `pet` ADD CONSTRAINT fk_pet_petStore FOREIGN KEY(store_id) REFERENCES petStore (`id`); /*插入数据*/ INSERT INTO `petowner` (id, `name`, `passWord`, `money`) VALUES (1, '小明', '123456', 178); INSERT INTO `petowner` (id, `name`, `passWord`, `money`) VALUES (2, '小强 ', '123456', 498); INSERT INTO `petstore` (id, `name`, `passWord`,`balance` )VALUES (1, '北京信息中心', '123456 ', 624); INSERT INTO `petstore` (id, `name`, `passWord`,`balance` ) VALUES (2, '重庆观音桥 ', '123456 ', 800); INSERT `pet` (`id`, `name`,`typeName`, `health`, `love`, `birthday`, `owner_id`, `store_id`) VALUES (1, '花花 ', 'dog', 1, 50, '2015-08-20', 1, 1); INSERT `pet` (`id`, `name`,`typeName`, `health`, `love`, `birthday`, `owner_id`, `store_id`) VALUES (2, '贝贝', 'penguin', 1, 60, '2015-08-20', NULL, 2); INSERT `pet` (`id`, `name`,`typeName`, `health`, `love`, `birthday`, `owner_id`, `store_id`) VALUES (3, '成成','dog', 1, 60, '2015-09-10', NULL, 1); INSERT `pet` (`id`, `name`,`typeName`, `health`, `love`, `birthday`, `owner_id`, `store_id`) VALUES (4, '露露','bird', 1, 70, '2016-01-10', NULL, 1); INSERT `pet` (`id`, `name`,`typeName`, `health`, `love`, `birthday`, `owner_id`, `store_id`) VALUES (5, '老虎','tiger', 1, 2, '2016-02-10', 2, 1); INSERT `pet` (`id`, `name`,`typeName`, `health`, `love`, `birthday`, `owner_id`, `store_id`) VALUES (6, '老虎','tiger', 1, 2, '2016-3-15', NULL, 1); INSERT `pet` (`id`, `name`,`typeName`, `health`, `love`, `birthday`, `owner_id`, `store_id`) VALUES (7, '老虎','tiger', 1, 11, '2016-2-15', NULL, 1); INSERT `pet` (`id`, `name`,`typeName`, `health`, `love`, `birthday`, `owner_id`, `store_id`) VALUES (8, '狮子','lion', 1, 2, '2016-4-15', NULL, 2); INSERT `account` (`id`, `deal_type`,`pet_id`, `seller_id`, `buyer_id`, `price`,`deal_time`) VALUES (2, 1, 4, 1, 1, 5, '2016-08-20'); INSERT `account` (`id`, `deal_type`,`pet_id`, `seller_id`, `buyer_id`, `price`,`deal_time`) VALUES (3, 1, 3, 1, 1, 5,'2016-08-20'); INSERT `account` (`id`, `deal_type`,`pet_id`, `seller_id`, `buyer_id`, `price`,`deal_time`) VALUES (4, 1, 3, 1, 1, 5, '2016-09-10'); INSERT `account` (`id`, `deal_type`,`pet_id`, `seller_id`, `buyer_id`, `price`,`deal_time`) VALUES (5, 2, 2, 2, 1, 3, '2016-09-10'); INSERT `account` (`id`, `deal_type`,`pet_id`, `seller_id`, `buyer_id`, `price`,`deal_time`) VALUES (6, 2, 3, 1, 1, 3, '2016-10-15'); /*创建本地用户epet,密码0000*/ GRANT ALL ON petShop.* TO `epet`@`localhost` IDENTIFIED BY '0000'
用例2-用例6:(建议看上图,包名类名和我一样,以免报错)
BaseDao操作基类:
package cnm.lh.dao; import java.io.IOException; import java.io.InputStream; import java.sql.*; import java.util.Properties; import cnm.lh.dao.BaseDao; /** * 数据库操作基类 */ public class BaseDao { public static String DRIVER; // 数据库驱动 public static String URL ; // url public static String DBNAME; // 数据库用户名 public static String DBPASS; // 数据库密码 Connection conn = null;// 数据连接对象 static{//静态代码块,在类加载的时候执行 init(); } /** * 初始化连接参数,从配置文件里获得 */ public static void init(){ Properties params=new Properties(); String configFile = "database.properties";//配置文件路径 //加载配置文件到输入流中 InputStream is=BaseDao.class.getClassLoader().getResourceAsStream(configFile); try { //从输入流中读取属性列表 params.load(is); } catch (IOException e) { e.printStackTrace(); } //根据指定的获取对应的值 DRIVER=params.getProperty("driver"); URL=params.getProperty("url"); DBNAME=params.getProperty("user"); DBPASS=params.getProperty("password"); } /** * 得到数据库连接 * * @throws ClassNotFoundException * @throws SQLException * @return 数据库连接 */ public Connection getConn() throws ClassNotFoundException, SQLException { Connection conn = null; try { Class.forName(DRIVER); // 注册驱动 conn = DriverManager.getConnection(URL, DBNAME, DBPASS); // 获得数据库连接 } catch (SQLException e) { e.printStackTrace(); } return conn; // 返回连接 } /** * 释放资源 * * @param conn * 数据库连接 * @param pstmt * PreparedStatement对象 * @param rs * 结果集 */ public void closeAll(Connection conn, PreparedStatement pstmt, ResultSet rs) { /* 如果rs不空,关闭rs */ if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } /* 如果pstmt不空,关闭pstmt */ if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } /* 如果conn不空,关闭conn */ if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } /** * 执行SQL语句,可以进行增、删、改的操作,不能执行查询 * * @param sql * 预编译的 SQL 语句 * @param param * 预编译的 SQL 语句中的‘?’参数的字符串数组 * @return 影响的条数 */ public int executeSQL(String preparedSql, Object[] param) { Connection conn = null; PreparedStatement pstmt = null; int num = 0; /* 处理SQL,执行SQL */ try { conn = getConn(); // 得到数据库连接 pstmt = conn.prepareStatement(preparedSql); // 得到PreparedStatement对象 if (param != null) { for (int i = 0; i < param.length; i++) { pstmt.setObject(i + 1, param[i]); // 为预编译sql设置参数 } } // System.out.println(preparedSql); num = pstmt.executeUpdate(); // 执行SQL语句 } catch (ClassNotFoundException e) { e.printStackTrace(); // 处理ClassNotFoundException异常 } catch (SQLException e) { e.printStackTrace(); // 处理SQLException异常 } finally { this.closeAll(conn, pstmt, null); } return num; } }
AccountDao类:
package cnm.lh.dao; import java.util.List; import cnm.lh.entity.Account; public interface AccountDao { /** * 更新台帐信息 */ public abstract int updateAccount(String sql, Object[] param); /** * 根据查询条件查询出宠物商店帐单 */ public abstract List<Account> getPetStoreAccount(String sql, String[] param); }
PetDao类:
package cnm.lh.dao; import java.util.List; import cnm.lh.entity.Pet; public interface PetDao { /** * 查询所有宠物信息 */ public abstract List<Pet> getAllPet(); /** * 根据已知宠物的信息查询宠物信息 */ public abstract List<Pet> selectPet(String sql, String[] param); /** * 更新宠物信息 */ public abstract int updatePet(String sql, Object[] param); }
PetOwnerDao类:
package cnm.lh.dao; import java.util.List; import cnm.lh.entity.PetOwner; public interface PetOwnerDao { /** * 查询所有宠物主人信息 */ public abstract List<PetOwner> getAllOwner(); /** * 更新宠物主人信息 */ public abstract int updateOwner(String sql, String[] param); /** * 根据查询条件查询宠物主人信息 */ public abstract PetOwner selectOwner(String sql, String[] param); }
PetStoreDao类:
package cnm.lh.dao; import java.util.List; import cnm.lh.entity.PetStore; public interface PetStoreDao { /** * 查询出所有宠物商店 */ public abstract List<PetStore> getAllStore(); /** * 根据查询条件查询出宠物商店 */ public abstract PetStore getPetStore(String sql, String[] param); /** * 更新宠物商店信息 */ public abstract int updateStore(String sql, Object[] param); }
AccountDaoImpl操作基类:
/** * */ package cnm.lh.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import cnm.lh.dao.AccountDao; import cnm.lh.dao.BaseDao; import cnm.lh.entity.Account; /** * 宠物商店台账信息数据库操作类 */ public class AccountDaoImpl extends BaseDao implements AccountDao { private Connection conn = null; // 保存数据库连接 private PreparedStatement pstmt = null; // 用于执行SQL语句 private ResultSet rs = null; // 用户保存查询结果集 /* (non-Javadoc) * @see cn.jbit.epetShop.dao.impl.AccountDao#updateAccount(java.lang.String, java.lang.Object[]) */ public int updateAccount(String sql, Object[] param) { int count = super.executeSQL(sql, param); return count; } /* (non-Javadoc) * @see cn.jbit.epetShop.dao.impl.AccountDao#getPetStoreAccount(java.lang.String, java.lang.String[]) */ public List<Account> getPetStoreAccount(String sql, String[] param) { List<Account> accountList = new ArrayList<Account>(); try { conn = getConn(); // 得到数据库连接 pstmt = conn.prepareStatement(sql); // 得到PreparedStatement对象 if (param != null) { for (int i = 0; i < param.length; i++) { pstmt.setString(i + 1, param[i]); // 为预编译sql设置参数 } } rs = pstmt.executeQuery(); // 执行SQL语句 Account account = null; while (rs.next()) { account = new Account(); account.setId(rs.getInt(1)); account.setDealType(rs.getInt(2)); account.setPetId(rs.getInt(3)); account.setSellerId(rs.getInt(4)); account.setBuyerId(rs.getInt(5)); account.setPrice(rs.getDouble(6)); account.setDealTime(rs.getDate(7)); accountList.add(account); } } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { super.closeAll(conn, pstmt, rs); } return accountList; } }
PetDaoImpl操作基类:
/** * */ package cnm.lh.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import cnm.lh.dao.BaseDao; import cnm.lh.dao.PetDao; import cnm.lh.entity.Pet; /** * 宠物数据库操作类 */ public class PetDaoImpl extends BaseDao implements PetDao { private Connection conn = null; // 保存数据库连接 private PreparedStatement pstmt = null; // 用于执行SQL语句 private ResultSet rs = null; // 用户保存查询结果集 /* (non-Javadoc) * @see cn.jbit.epetShop.dao.impl.PetDao#getAllPet() */ public List<Pet> getAllPet() { List<Pet> petList = new ArrayList<Pet>(); try { String preparedSql = "select id,name,typeName,health,love,birthday,owner_id,store_id from pet "; conn = getConn(); // 得到数据库连接 pstmt = conn.prepareStatement(preparedSql); // 得到PreparedStatement对象 rs = pstmt.executeQuery(); // 执行SQL语句 while (rs.next()) { Pet pet = new Pet(); pet.setId(rs.getInt(1)); pet.setName(rs.getString(2)); pet.setTypeName(rs.getString(3)); pet.setHealth(rs.getInt(4)); pet.setLove(rs.getInt(5)); pet.setBirthday(rs.getDate(6)); pet.setOwnerId(rs.getInt(7)); pet.setStoreId(rs.getInt(8)); petList.add(pet); } } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { super.closeAll(conn, pstmt, rs); } return petList; } /* (non-Javadoc) * @see cn.jbit.epetShop.dao.impl.PetDao#selectPet(java.lang.String, java.lang.String[]) */ public List<Pet> selectPet(String sql, String[] param) { List<Pet> petList = new ArrayList<Pet>(); try { conn = getConn(); // 得到数据库连接 pstmt = conn.prepareStatement(sql); // 得到PreparedStatement对象 if (param != null) { for (int i = 0; i < param.length; i++) { pstmt.setString(i + 1, param[i]); // 为预编译sql设置参数 } } rs = pstmt.executeQuery(); // 执行SQL语句 while (rs.next()) { Pet pet = new Pet(); pet.setId(rs.getInt(1)); pet.setName(rs.getString(2)); pet.setTypeName(rs.getString(3)); pet.setHealth(rs.getInt(4)); pet.setLove(rs.getInt(5)); pet.setBirthday(rs.getDate(6)); pet.setOwnerId(rs.getInt(7)); pet.setStoreId(rs.getInt(8)); petList.add(pet); } } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { super.closeAll(conn, pstmt, rs); } return petList; } /* * (non-Javadoc) * * @see cn.jbit.epetShop.dao.impl.PetDao#updatePet(java.lang.String, * java.lang.Object[]) */ public int updatePet(String sql, Object[] param) { int count = super.executeSQL(sql, param); return count; } }
PetOwnerDaoImpl操作基类:
/** * */ package cnm.lh.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import cnm.lh.dao.BaseDao; import cnm.lh.dao.PetOwnerDao; import cnm.lh.entity.PetOwner; /** *宠物主人数据库操作类 */ public class PetOwnerDaoImpl extends BaseDao implements PetOwnerDao { private Connection conn = null; // 保存数据库连接 private PreparedStatement pstmt = null; // 用于执行SQL语句 private ResultSet rs = null; // 用户保存查询结果集 /* (non-Javadoc) * @see cn.jbit.epetShop.dao.impl.PetOwnerDao#getAllOwner() */ public List<PetOwner> getAllOwner() { List<PetOwner> ownerList = new ArrayList<PetOwner>(); try { String preparedSql = "select * from petowner "; conn = getConn(); // 得到数据库连接 pstmt = conn.prepareStatement(preparedSql); // 得到PreparedStatement对象 rs = pstmt.executeQuery(); // 执行SQL语句 while (rs.next()) { PetOwner petOwner = new PetOwner(); petOwner.setId(rs.getInt(1)); petOwner.setName(rs.getString(2)); petOwner.setPassword(rs.getString(3)); petOwner.setMoney(rs.getDouble(4)); ownerList.add(petOwner); } } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { super.closeAll(conn, pstmt, rs); } return ownerList; } /* (non-Javadoc) * @see cn.jbit.epetShop.dao.impl.PetOwnerDao#updateOwner(java.lang.String, java.lang.String[]) */ public int updateOwner(String sql, String[] param) { int count = super.executeSQL(sql, param); return count; } /* (non-Javadoc) * @see cn.jbit.epetShop.dao.impl.PetOwnerDao#selectOwner(java.lang.String, java.lang.String[]) */ public PetOwner selectOwner(String sql, String[] param) { PetOwner owner = null; try { conn = getConn(); // 得到数据库连接 pstmt = conn.prepareStatement(sql); // 得到PreparedStatement对象 if (param != null) { for (int i = 0; i < param.length; i++) { pstmt.setString(i + 1, param[i]); // 为预编译sql设置参数 } } rs = pstmt.executeQuery(); // 执行SQL语句 while (rs.next()) { owner = new PetOwner(); owner.setId(rs.getInt(1)); owner.setName(rs.getString(2)); owner.setPassword(rs.getString(3)); owner.setMoney(rs.getDouble(4)); } } catch (Exception e) { e.printStackTrace(); } finally { super.closeAll(conn, pstmt, rs); } return owner; } }
PetStoreDaoImpl操作基类:
/** * */ package cnm.lh.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import cnm.lh.dao.BaseDao; import cnm.lh.dao.PetStoreDao; import cnm.lh.entity.PetStore; /** *宠物商店数据库操作类 */ public class PetStoreDaoImpl extends BaseDao implements PetStoreDao { private Connection conn = null; // 保存数据库连接 private PreparedStatement pstmt = null; // 用于执行SQL语句 private ResultSet rs = null; // 用户保存查询结果集 /* (non-Javadoc) * @see cn.jbit.epetShop.dao.impl.PetStoreDao#getAllStore() */ public List<PetStore> getAllStore() { List<PetStore> storeList = new ArrayList<PetStore>(); try { String preparedSql = "select * from petstore "; conn = getConn(); // 得到数据库连接 pstmt = conn.prepareStatement(preparedSql); // 得到PreparedStatement对象 rs = pstmt.executeQuery(); // 执行SQL语句 while (rs.next()) { PetStore petStore = new PetStore(); petStore.setId(rs.getInt(1)); petStore.setName(rs.getString(2)); petStore.setPassword(rs.getString(3)); petStore.setBalance(rs.getDouble(4)); storeList.add(petStore); } } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { super.closeAll(conn, pstmt, rs); } return storeList; } /* (non-Javadoc) * @see cn.jbit.epetShop.dao.impl.PetStoreDao#getPetStore(java.lang.String, java.lang.String[]) */ public PetStore getPetStore(String sql, String[] param) { PetStore petStore = null; try { conn = getConn(); // 得到数据库连接 pstmt = conn.prepareStatement(sql); // 得到PreparedStatement对象 if (param != null) { for (int i = 0; i < param.length; i++) { pstmt.setString(i + 1, param[i]); // 为预编译sql设置参数 } } rs = pstmt.executeQuery(); // 执行SQL语句 while (rs.next()) { petStore = new PetStore(); petStore.setId(rs.getInt(1)); petStore.setName(rs.getString(2)); petStore.setPassword(rs.getString(3)); petStore.setBalance(rs.getDouble(4)); } } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { super.closeAll(conn, pstmt, rs); } return petStore; } /* (non-Javadoc) * @see cn.jbit.epetShop.dao.impl.PetStoreDao#updateStore(java.lang.String, java.lang.Object[]) */ public int updateStore(String sql, Object[] param) { int count = super.executeSQL(sql, param); return count; } }
Account类:
/** * */ package cnm.lh.entity; import java.util.Date; /** * @author 宠物商店台帐类 * */ public class Account { /** * 帐单标识符 */ private long id; /** * 交易类型,1--代表商店卖给宠物主人 2--代表宠物主人卖给商店 3---宠物主人之间交易 */ private int dealType; /** * 宠物标识符 */ private long petId; /** * 卖家标识符 */ private long sellerId; /** * 买家标识符 */ private long buyerId; /** * 交易价格 */ private double price; /** * 交易时间 */ private Date dealTime; /** * @return the buyerId */ public long getBuyerId() { return buyerId; } /** * @param buyerId * the buyerId to set */ public void setBuyerId(long buyerId) { this.buyerId = buyerId; } /** * @return the dealTime */ public Date getDealTime() { return dealTime; } /** * @param dealTime * the dealTime to set */ public void setDealTime(Date dealTime) { this.dealTime = dealTime; } /** * @return the dealType */ public int getDealType() { return dealType; } /** * @param dealType * the dealType to set */ public void setDealType(int dealType) { this.dealType = dealType; } /** * @return the id */ public long getId() { return id; } /** * @param id * the id to set */ public void setId(long id) { this.id = id; } /** * @return the petId */ public long getPetId() { return petId; } /** * @param petId * the petId to set */ public void setPetId(long petId) { this.petId = petId; } /** * @return the price */ public double getPrice() { return price; } /** * @param price * the price to set */ public void setPrice(double price) { this.price = price; } /** * @return the sellerId */ public long getSellerId() { return sellerId; } /** * @param sellerId * the sellerId to set */ public void setSellerId(long sellerId) { this.sellerId = sellerId; } }
Pet实体类:
/** * */ package cnm.lh.entity; import java.util.Date; /** * 宠物实体类 * */ public class Pet { /* * 宠物标识符 */ private long id; /** * 宠物名称 */ private String name; /** * 宠物类别 */ private String typeName; /** * 宠物健康指数 */ private int health; /** * 宠物爱心 */ private int love; /** * 宠物生日 */ private Date birthday; /** * 宠物所属宠物主人标识符 */ private int ownerId; /** * 宠物所属宠物商店标识符 */ private long storeId; /** * @return the ownerId */ public int getOwnerId() { return ownerId; } /** * @param ownerId * the ownerId to set */ public void setOwnerId(int ownerId) { this.ownerId = ownerId; } /** * @return the birthdate */ public Date getBirthday() { return birthday; } /** * @return the storeId */ public long getStoreId() { return storeId; } /** * @param storeId * the storeId to set */ public void setStoreId(long storeId) { this.storeId = storeId; } /** * @param birthdate * the birthday to set */ public void setBirthday(Date birthday) { this.birthday = birthday; } /** * @return the health */ public int getHealth() { return health; } /** * @param health * the health to set */ public void setHealth(int health) { this.health = health; } /** * @return the id */ public long getId() { return id; } /** * @param id * the id to set */ public void setId(long id) { this.id = id; } /** * @return the love */ public int getLove() { return love; } /** * @param love * the love to set */ public void setLove(int love) { this.love = love; } /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @return the typeName */ public String getTypeName() { return typeName; } /** * @param typeName * the typeName to set */ public void setTypeName(String typeName) { this.typeName = typeName; } }
PetOwner实体类:
package cnm.lh.entity;
/** * 宠物主人实体类 * */ public class PetOwner { /** * 宠物主人标识符 */ private int id;
/** * 宠物主人名称 */ private String name;
/** * 宠物主人密码 */ private String password;
/** * 宠物主人元宝数 */ private double money;
/** * @return the money */ public double getMoney() { return money; }
/** * @param money * the money to set */ public void setMoney(double money) { this.money = money; }
/** * @return the id */ public int getId() { return id; }
/** * @param id * the id to set */ public void setId(int id) { this.id = id; }
/** * @return the name */ public String getName() { return name; }
/** * @param name * the name to set */ public void setName(String name) { this.name = name; }
/** * @return the password */ public String getPassword() { return password; }
/** * @param password * the password to set */ public void setPassword(String password) { this.password = password; } }
PetStore实体类:
/** * */ package cnm.lh.entity;
/** * 宠物商店实体类 * */ public class PetStore { /** * 宠物商店id */ private long id;
/** * 宠物商店名称 */ private String name;
/** * 宠物商店密码 */ private String password;
/** * 宠物商店资金 */ private double balance;
/** * @return the id */ public long getId() { return id; }
/** * @param id * the id to set */ public void setId(long id) { this.id = id; }
/** * @return the name */ public String getName() { return name; }
/** * @param name * the name to set */ public void setName(String name) { this.name = name; }
/** * @return the password */ public String getPassword() { return password; }
/** * @param password * the password to set */ public void setPassword(String password) { this.password = password; }
/** * @return the balance 得到宠物商店结余 */ public double getBalance() { return balance; }
/** * @param balance * the balance to set */ public void setBalance(double balance) { this.balance = balance; }
}
Accountable接口:
/** * */ package cnm.lh.service; import java.util.List; import cnm.lh.entity.Account; import cnm.lh.entity.Pet; import cnm.lh.entity.PetOwner; /** * @author 宠物商店台账接口 */ public interface Accountable { /** * 查询宠物商店台帐信息 */ public List<Account> account(long storeId); /** * 修改宠物商店台帐信息 */ public int modifyAccount(Pet pet, PetOwner owner); }
Breadable接口:
/** * */ package cnm.lh.service; import cnm.lh.entity.Pet; /** * @author 宠物培育接口 * */ public interface Breadable { /** * 宠物繁殖 */ public Pet bread(String pet); }
Buyable接口:
/** * */ package cnm.lh.service; import cnm.lh.entity.Pet; /** * @author 买宠物接口 */ public interface Buyable { /** * 宠物主人购买库存宠物 */ public void buy(Pet pet); }
PetFactory接口:
/** * */ package cnm.lh.service; import cnm.lh.entity.Pet; /** * 宠物工厂接口 */ public interface PetFactory { /** * 培育新品种宠物 */ public Pet breadNewPet(String[] petParam); }
PetOwnerService接口:
/** * */ package cnm.lh.service; import java.util.List; import cnm.lh.entity.Pet; import cnm.lh.entity.PetOwner; /** * @author 宠物主人接口 * */ public interface PetOwnerService extends Sellable, Buyable { /** * 宠物主人登录 */ public PetOwner login(); /** * 根据宠物主人标识符(id)获得到该宠物主人所有宠物信息 */ public List<Pet> getMyPet(int ownerId); }
PetStoreFactory接口:
/** * */ package cnm.lh.service; /** * @author 宠物商店工厂接口 */ public interface PetStoreFactory { /** * 创建宠物商店方法 */ public void createPetStore(); }
PetStoreService接口:
/** * */ package cnm.lh.service; import java.util.List; import cnm.lh.entity.Pet; import cnm.lh.entity.PetOwner; import cnm.lh.entity.PetStore; /** * @author 宠物商店接口 */ public interface PetStoreService extends Accountable, Breadable, Buyable, Sellable { /** * 查询出所有库存宠物 */ public List<Pet> getPetsInstock(long storeId); /** * 查询出所有新培育的宠物 */ public List<Pet> getPetsBread(); /** * 查询出所有新培育的宠物 */ public double charge(Pet pet); /** * 根据宠物主人信息修改宠物信息 */ public int modifyPet(Pet pet, PetOwner petOwner, PetStore store); /** * 修改宠物主人信息 */ public int modifyOwner(PetOwner owner, Pet pet, int type); /** * 根据宠物商店标识符查询宠物商店 */ public PetStore getPetStore(long id); /** * 修改宠物商店信息 */ public int modifyStore(Pet pet, int type); /** * 宠物商店登录 */ public PetStore login(); /** * 查询出所有宠物主人正在出售的宠物 */ public List<Pet> getPetSelling(); }
Sellable接口:
/** * */ package cnm.lh.service; import cnm.lh.entity.Pet; /** *宠物卖接口 */ public interface Sellable { /** * 卖宠物 */ public void sell(Pet pet); }
PetFactoryImpl实现类:
/** * */ package cnm.lh.service.impl; import cnm.lh.entity.Pet; import cnm.lh.service.PetFactory; /** * 宠物工厂实现类 */ public class PetFactoryImpl implements PetFactory { /** * 宠物工程培育新品种宠物 */ public Pet breadNewPet(String[] petParam) { Pet pet = new Pet(); pet.setName(petParam[0]); pet.setTypeName(petParam[1]); pet.setHealth(Integer.parseInt(petParam[2])); pet.setLove(Integer.parseInt(petParam[3])); pet.setStoreId(Integer.parseInt(petParam[4])); return pet; } }
PetOwnerServiceImpl实现类:
/** * */ package cnm.lh.service.impl; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Scanner; import cnm.lh.dao.AccountDao; import cnm.lh.dao.PetDao; import cnm.lh.dao.PetOwnerDao; import cnm.lh.dao.impl.AccountDaoImpl; import cnm.lh.dao.impl.PetDaoImpl; import cnm.lh.dao.impl.PetOwnerDaoImpl; import cnm.lh.dao.impl.PetStoreDaoImpl; import cnm.lh.entity.Pet; import cnm.lh.entity.PetOwner; import cnm.lh.entity.PetStore; import cnm.lh.service.PetOwnerService; import cnm.lh.service.PetStoreService; /** * @author 宠物主人实现类 */ public class PetOwnerServiceImpl implements PetOwnerService { /** * 宠物主人购买库存宠物,根据页面获得到的序号,来实际调用购买库存宠物或者购买新培育的宠物 */ public void buy(Pet pet) { String sql = "select * from petowner where id=?"; String param[] = { String.valueOf(pet.getOwnerId()) }; PetOwnerDao ownerDao = new PetOwnerDaoImpl(); PetOwner owner = ownerDao.selectOwner(sql, param); PetStoreService petStore = new PetStoreServiceImpl(); int updatePet = petStore.modifyPet(pet, owner, null);// 更新宠物信息 if (updatePet > 0) {// 更新宠物主人的信息 int updateOwner = petStore.modifyOwner(owner, pet, 0); if (updateOwner > 0) {// 更新宠物商店的信息 int updateStore = petStore.modifyStore(pet, 1); if (updateStore > 0) {// 更新宠物商店台帐信息 int insertAccount = petStore.modifyAccount(pet, owner); if (insertAccount > 0) { System.out.println("台帐正确插入一条信息"); } } } } } /** * 宠物主人向宠物商店卖出自己宠物 */ public void sell(Pet pet) { PetDaoImpl petDao = new PetDaoImpl(); PetOwnerDaoImpl ownerDao = new PetOwnerDaoImpl(); String updatesql = "update pet set owner_id = null where id=?"; Object[] param = { pet.getId() }; int updatePet = petDao.executeSQL(updatesql, param);// 更新宠物信息 if (updatePet > 0) {// 更新宠物主人的信息 String ownersql = "select * from petowner where id=?"; String ownerparam[] = { String.valueOf(pet.getOwnerId()) }; PetOwner owner = ownerDao.selectOwner(ownersql, ownerparam); String updateOwnerSql = "update petowner set money=? where id=?"; Object[] ownerParam = { (owner.getMoney() + 3), owner.getId() }; int updateOwner = ownerDao.executeSQL(updateOwnerSql, ownerParam); if (updateOwner > 0) {// 更新宠物商店的信息 PetStoreServiceImpl store = new PetStoreServiceImpl(); PetStore petStore = store.getPetStore(pet.getStoreId()); String updateStore = "update petstore set balance=? where id=?"; Object[] storeParam = { (petStore.getBalance() - 3), petStore.getId() }; PetStoreDaoImpl storeDao = new PetStoreDaoImpl(); int updatestore = storeDao.executeSQL(updateStore, storeParam); if (updatestore > 0) {// 更新宠物商店台帐信息 String insertsql = "insert into account(deal_type,pet_id,seller_id,buyer_id,price,deal_time) values (?, ?, ?, ?, ?, ?)"; String date = new SimpleDateFormat("yyyy-MM-dd") .format(new Date()); Object[] accountParam = { 2, pet.getId(), owner.getId(), pet.getStoreId(), 3, date }; AccountDao accountDao = new AccountDaoImpl(); int insertAccount = accountDao.updateAccount(insertsql, accountParam); if (insertAccount > 0) { System.out.println("台帐正确插入一条信息"); } } } } } /** * 宠物主人登录 */ public PetOwner login() { Scanner input = new Scanner(System.in); // 1、输入主人姓名 System.out.println("请先登录,请您输入主人的名字:"); String ownerName = input.nextLine().trim(); System.out.println("请您输入主人的密码:"); String ownerPassword = input.nextLine().trim(); PetOwnerDao ownerDao = new PetOwnerDaoImpl(); String sql = "select * from petowner where name=? and password=?"; String[] param = { ownerName, ownerPassword }; PetOwner owner = ownerDao.selectOwner(sql, param); if (null != owner) { System.out.println("-------恭喜您成功登录-------"); System.out.println("-------您的基本信息:-------"); System.out.println("名字:" + owner.getName()); System.out.println("元宝数:" + owner.getMoney()); } return owner; } /** * * 根据宠物主人标识符(id)获得到该宠物主人所有宠物信息 */ public List<Pet> getMyPet(int ownerId) { List<Pet> petList = new ArrayList<Pet>(); String sql = "select * from pet where owner_id=?"; String[] param = { String.valueOf(ownerId) }; PetDao petDao = new PetDaoImpl(); petList = petDao.selectPet(sql, param); return petList; } }
PetStoreFactoryImpl实现类:
/** * */ package cnm.lh.service.impl; import java.util.Scanner; import cnm.lh.dao.PetStoreDao; import cnm.lh.dao.impl.PetStoreDaoImpl; import cnm.lh.service.PetStoreFactory; /** * @author 宠物商店工程实现类 */ public class PetStoreFactoryImpl implements PetStoreFactory { /** * 创建宠物商店 */ public void createPetStore() { Scanner input = new Scanner(System.in); System.out.println("请在下面输入宠物商店属性:"); System.out.println("请输入宠物商店名字:"); String storeName = input.nextLine(); System.out.println("请输入宠物商店的密码(英文加数字):"); String storePassword = input.nextLine(); System.out.println("请输入宠物商店的资金(整数):"); String petBalance = input.nextLine(); String sql = "insert into petstore(`name`,`password`,balance) values(?,?,?)"; Object[] param = { storeName, storePassword, petBalance }; PetStoreDao storeDao = new PetStoreDaoImpl(); int count = storeDao.updateStore(sql, param); if (count > 0) { System.out.println("成功创建了一个宠物商店,商店名字叫" + storeName); } } }
PetStoreServiceImpl实现类:
/** * */ package cnm.lh.service.impl; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Scanner; import cnm.lh.dao.AccountDao; import cnm.lh.dao.PetDao; import cnm.lh.dao.PetOwnerDao; import cnm.lh.dao.PetStoreDao; import cnm.lh.dao.impl.AccountDaoImpl; import cnm.lh.dao.impl.PetDaoImpl; import cnm.lh.dao.impl.PetOwnerDaoImpl; import cnm.lh.dao.impl.PetStoreDaoImpl; import cnm.lh.entity.Account; import cnm.lh.entity.Pet; import cnm.lh.entity.PetOwner; import cnm.lh.entity.PetStore; import cnm.lh.service.PetFactory; import cnm.lh.service.PetStoreService; /** * 宠物商店实现类 */ public class PetStoreServiceImpl implements PetStoreService { /** * 为宠物定价 */ public double charge(Pet pet) { // 编写定价规则 Date date = new Date(); double price = 0; int age = date.getYear() - pet.getBirthday().getYear(); if (age > 5) { price = 3; } else { price = 5; } return price; } /** * 查询出所有库存宠物 */ public List<Pet> getPetsInstock(long storeId) { PetDao petDao = new PetDaoImpl(); String[] param = { String.valueOf(storeId) }; String sql = ""; // 当storeId不为0时,要执行查询指定商店库存宠物 if(storeId!=0){ sql = "select * from pet where owner_id is null and store_id=?"; } // 当storeId为0时,要执行查询所有商店的库存宠物 if (0 == storeId) { sql = "select * from pet where owner_id is null"; param = null; } List<Pet> petList = petDao.selectPet(sql, param); return petList; } /** * 查询出所有新培育的宠物 */ public List<Pet> getPetsBread() { PetDao petDao = new PetDaoImpl(); String sql = "select * from pet where owner_id is null and typename not in (?,?)"; String[] petParam = { "dog", "penguin" }; List<Pet> petList = petDao.selectPet(sql, petParam); return petList; } /** * 查询宠物商店账目 */ public List<Account> account(long storeId) { String sql = "select * from account where deal_type=? and seller_id=? union select * from account where deal_type=? and buyer_id=?"; String[] param = { "1", String.valueOf(storeId), "2", String.valueOf(storeId) }; AccountDao accountDao = new AccountDaoImpl(); List<Account> list = accountDao.getPetStoreAccount(sql, param); return list; } /** * 培育宠物 */ public Pet bread(String petType) { Scanner input = new Scanner(System.in); System.out.println("请在下面输入宠物属性:"); System.out.println("请输入宠物名字:"); String petName = input.nextLine(); System.out.println("请输入宠物健康指数(整数):"); String petHealth = input.nextLine(); System.out.println("请输入宠物爱心指数(整数):"); String petLove = input.nextLine(); System.out.println("请输入宠物所属宠物商店的标识符(整数):"); String StoreId = input.nextLine(); String[] petParam = { petName, petType, petHealth, petLove, StoreId }; PetFactory petFactory = new PetFactoryImpl(); Pet pet = petFactory.breadNewPet(petParam); SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd"); String petBirthday = simpleDate.format(new Date()); String sql = "insert into pet(`name`,typeName,health,love,birthday,store_id) values(?,?,?,?,?,?)"; Object[] param = { pet.getName(), pet.getTypeName(), pet.getHealth(), pet.getLove(), petBirthday, pet.getStoreId() }; PetDao petDao = new PetDaoImpl(); int count = petDao.updatePet(sql, param); if (count > 0) { System.out.println("成功创建了一只" + pet.getTypeName() + "宠物"); } return pet; } /** * 购买宠物 */ public void buy(Pet pet) { String sql = "select * from petStore where id=?"; String paramStore[] = { String.valueOf(pet.getStoreId()) }; PetStoreDao storeDao = new PetStoreDaoImpl(); PetStore store = storeDao.getPetStore(sql, paramStore); PetOwnerDao ownerDao = new PetOwnerDaoImpl(); sql = "select * from petOwner where id = ?"; String paramOwner[] = { String.valueOf(pet.getOwnerId()) }; PetOwner owner = ownerDao.selectOwner(sql, paramOwner); int updatePet = modifyPet(pet, null, store);// 更新宠物信息 if (updatePet > 0) {// 更新宠物主人的信息 int updateOwner = modifyOwner(owner, pet, 1); if (updateOwner > 0) {// 更新宠物商店的信息 int updateStore = modifyStore(pet, 0); if (updateStore > 0) {// 更新宠物商店台帐信息 int insertAccount = modifyAccount(pet, owner); if (insertAccount > 0) { System.out.println("台帐正确插入一条信息"); } } } } else { System.out.println("修改宠物信息失败"); } } /** * 卖宠物 */ public void sell(Pet pet) { PetDaoImpl petDao = new PetDaoImpl(); PetStoreDaoImpl storeDao = new PetStoreDaoImpl(); PetOwnerDaoImpl ownerDao = new PetOwnerDaoImpl(); PetStoreService petStore = new PetStoreServiceImpl(); String updatesql = "update pet set store_id = null ,owner_id=? where id=?"; Object[] param = { pet.getOwnerId(), pet.getId() }; int updatePet = petDao.executeSQL(updatesql, param);// 更新宠物信息 if (updatePet > 0) {// 更新宠物主人的信息 String ownersql = "select * from petowner where id=?"; String ownerparam[] = { String.valueOf(pet.getOwnerId()) }; PetOwner owner = ownerDao.selectOwner(ownersql, ownerparam); String updateOwnerSql = "update petowner set money=? where id=?"; double count = petStore.charge(pet); Object[] ownerParam = { (owner.getMoney() - count), owner.getId() }; int updateOwner = ownerDao.executeSQL(updateOwnerSql, ownerParam); if (updateOwner > 0) {// 更新宠物商店的信息 PetStore store = petStore.getPetStore(pet.getStoreId()); String updateStore = "update petstore set balance=? where id=?"; Object[] storeParam = { (store.getBalance() + count), store.getId() }; int updatestore = storeDao.executeSQL(updateStore, storeParam); if (updatestore > 0) {// 更新宠物商店台帐信息 String insertsql = "insert into account(deal_type,pet_id,seller_id,buyer_id,price,deal_time) values (?, ?, ?, ?, ?, ?)"; String date = new SimpleDateFormat("yyyy-MM-dd") .format(new Date()); Object[] accountParam = {1, pet.getId(), owner.getId(),pet.getStoreId(),count, date }; AccountDao accountDao = new AccountDaoImpl(); int insertAccount = accountDao.updateAccount(insertsql, accountParam); if (insertAccount > 0) { System.out.println("台帐正确插入一条信息"); } } } } } /** * 根据宠物商店标识符查询宠物商店 */ public PetStore getPetStore(long id) { String sql = "select * from petstore where id=" + id; PetStoreDao storeDao = new PetStoreDaoImpl(); PetStore petStore = storeDao.getPetStore(sql, null); return petStore; } /** * 根据宠物主人信息修改宠物信息 根据PetOwnerEntity和PetStoreEntity的值判断是宠物主人买宠物或者宠物商店买宠物 * PetOwnerEntity=null是宠物商店买宠物,PetStoreEntity=null是宠物主人买宠物 */ public int modifyPet(Pet pet, PetOwner owner, PetStore store) { String updatesql = null; long id = 0; if (null == store) { updatesql = "update pet set owner_id=? where id=?"; id = owner.getId(); } else if (null == owner) { updatesql = "update pet set store_id=?,owner_id=null where id=?"; id = store.getId(); } Object[] param = { id, pet.getId() }; PetDaoImpl petDao = new PetDaoImpl(); int updatePet = petDao.executeSQL(updatesql, param);// 更新宠物信息 return updatePet; } /** * 修改宠物主人信息 type=0是宠物主人买宠物,type=1是宠物商店买宠物 */ public int modifyOwner(PetOwner owner, Pet pet, int type) { PetOwnerDaoImpl ownerDao = new PetOwnerDaoImpl(); String updateOwnerSql = "update petowner set money=? where id=?"; double price = this.charge(pet); double count = 0; if (0 == type) { count = (owner.getMoney() - price); } if (1 == type) { count = (owner.getMoney() + price); } Object[] ownerParam = { count, owner.getId() }; int updateOwner = ownerDao.executeSQL(updateOwnerSql, ownerParam); return updateOwner; } /** * 修改宠物商店信息 type=0是宠物主人买宠物,type=1是宠物商店买宠物 */ public int modifyStore(Pet pet, int type) { PetStoreService store = new PetStoreServiceImpl(); PetStore petStore = store.getPetStore(pet.getStoreId()); String updateStore = "update petstore set balance=? where id=?"; double price = this.charge(pet); double count = 0; if (0 == type) { count = (petStore.getBalance() - price); } if (1 == type) { count = (petStore.getBalance() + price); } Object[] storeParam = { count, petStore.getId() }; PetStoreDaoImpl storeDao = new PetStoreDaoImpl(); int updatestore = storeDao.executeSQL(updateStore, storeParam); return updatestore; } /** * 修改宠物商店台帐信息 */ public int modifyAccount(Pet pet, PetOwner owner) { String insertsql = "insert into account(deal_type,pet_id,seller_id,buyer_id,price,deal_time) values (?, ?, ?, ?, ?,?)"; String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); double price = this.charge(pet); Object[] accountParam = { 1, pet.getId(), pet.getStoreId(),owner.getId(), price, date }; AccountDao accountDao = new AccountDaoImpl(); int insertAccount = accountDao.updateAccount(insertsql, accountParam); return insertAccount; } /** * 宠物商店登录 */ public PetStore login() { Scanner input = new Scanner(System.in); PetStore petStore = null; // 1、输入宠物商店名字 boolean type = true; while (type) { System.out.println("请先登录,请输入宠物商店名字:"); String storeName = input.nextLine().trim(); System.out.println("请输入宠物商店的密码:"); String storePassword = input.nextLine().trim(); PetStoreDao storeDao = new PetStoreDaoImpl(); String sql = "select * from petstore where name=? and password=?"; String[] param = { storeName, storePassword }; petStore = storeDao.getPetStore(sql, param); if (null != petStore) { System.out.println("-------恭喜成功登录-------"); System.out.println("-------宠物商店的基本信息:-------"); System.out.println("名字:" + petStore.getName()); System.out.println("元宝数:" + petStore.getBalance()); type = false; } else { System.out.println("登录失败,请确认您的用户名和密码是否正确,重新登录"); type = true; } } return petStore; } @Override /** * 查询出所有宠物主人正在出售的宠物 */ public List<Pet> getPetSelling() { PetDao petDao = new PetDaoImpl(); String sql = "select * from pet where owner_id is not null"; String[] petParam = null; List<Pet> petList = petDao.selectPet(sql, petParam); return petList; } }
Main测试类:
/** * */ package cnm.lh.test; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import cnm.lh.dao.PetDao; import cnm.lh.dao.PetOwnerDao; import cnm.lh.dao.PetStoreDao; import cnm.lh.dao.impl.PetDaoImpl; import cnm.lh.dao.impl.PetOwnerDaoImpl; import cnm.lh.dao.impl.PetStoreDaoImpl; import cnm.lh.entity.Account; import cnm.lh.entity.Pet; import cnm.lh.entity.PetOwner; import cnm.lh.entity.PetStore; import cnm.lh.service.PetOwnerService; import cnm.lh.service.PetStoreFactory; import cnm.lh.service.PetStoreService; import cnm.lh.service.impl.PetOwnerServiceImpl; import cnm.lh.service.impl.PetStoreFactoryImpl; import cnm.lh.service.impl.PetStoreServiceImpl; /** * 入口类 * */ public class Main { /** * @param args * void 系统入口方法 */ public static void main(String[] args) { Main.startPetShop(); } /** * 系统启动 */ public static void startPetShop() { System.out.println(" 宠物商店启动"); System.out.println("Wonderland醒来,所有宠物从MySQL中醒来"); System.out .println("****************************************************"); PetDao petDao = new PetDaoImpl(); List<Pet> petList = petDao.getAllPet(); System.out.println("序号\t" + "宠物名称\t"); for (int i = 0; i < petList.size(); i++) { Pet pet = petList.get(i); System.out.println((i + 1)+"\t"+ pet.getName()+"\t"); } System.out .println("****************************************************"); System.out.print("\n"); System.out.println("所有宠物主人从MySQL中醒来"); PetOwnerDao ownerDao = new PetOwnerDaoImpl(); List<PetOwner> ownerList = ownerDao.getAllOwner(); System.out .println("****************************************************"); System.out.println("序号\t" + "主人姓名\t" ); for (int i = 0; i < ownerList.size(); i++) { PetOwner owner = ownerList.get(i); System.out.println((i + 1) +"\t"+ owner.getName()+"\t"); } System.out .println("****************************************************"); System.out.print("\n"); System.out.println("所有宠物商店从MySQL中醒来"); System.out .println("****************************************************"); PetStoreDao storeDao = new PetStoreDaoImpl(); List<PetStore> storeList = storeDao.getAllStore(); System.out.println("序号\t" + "宠物商店名称\t"); for (int i=0;i<storeList.size();i++) { PetStore store = storeList.get(i); System.out.println((i + 1) +"\t"+ store.getName()+"\t"); } System.out .println("****************************************************"); System.out.print("\n"); Scanner input = new Scanner(System.in); System.out.println("请选择输入登录模式,输入1为宠物主人登录,输入2为宠物商店登录"); boolean type = true; String num; while (type) { num = input.next(); if ("1".equals(num)) { Main.ownerLogin(); type = false; } else if ("2".equals(num)) { Main.storeLogin(); type = false; } else { System.out.println("输入有误,请按照指定规则输入"); System.out.println("请选择登录模式,输入1为宠物主人登录,输入2为宠物商店登录"); type = true; } } } /** * 宠物主人登录方法 */ public static PetOwner ownerLogin() { Scanner input = new Scanner(System.in); PetOwnerServiceImpl petOwner = new PetOwnerServiceImpl(); PetOwner Owner = petOwner.login(); boolean reg = true; while (reg) { if (null == Owner) { System.out.println("登录失败,请确认您的用户名和密码后重新输入"); Owner = petOwner.login(); reg = true; } else { reg = false; System.out.println("登录成功,您可以购买和卖出宠物,如果您想购买宠物请输入1,如果想卖出宠物请输入2"); System.out.println("1:购买宠物"); System.out.println("2:卖出宠物"); boolean type = true; while (type) { int num = input.nextInt(); if (1 == num) { Main.ownerBuy(Owner); type = false; } else if (2 == num) { Main.ownerSell(Owner); type = false; } else { System.out.println("输入有误,请重新输入"); type = true; } } } } return Owner; } /** * 宠物商店登录方法 */ public static PetStore storeLogin() { Scanner input = new Scanner(System.in); PetStoreService petStore = new PetStoreServiceImpl(); PetStore store = petStore.login(); 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("7:开宠物商店"); System.out.println("请根据需要执行的操作,选择序号输入,退出请输入0"); boolean type = true; while (type) { int num = input.nextInt(); switch (num) { case 0: System.out.println("退出成功"); type = false; break; case 1: Main.storeBuy(store); type = false; break; case 2: Main.storeSell(store); type = false; break; case 3: Main.storeBread(); type = false; break; case 4: Main.queryPetStock(store.getId()); type = false; break; case 5: Main.queryStoreBalance(store); type = false; break; case 6: Main.getAccount(store.getId()); type = false; break; case 7: Main.createPetStore(); type = false; break; default: System.out.println("输入有误,请重新输入"); type = true; break; } } return store; } /** * 查询商店结余 */ public static void queryStoreBalance(PetStore petStore) { double balance = petStore.getBalance(); System.out.println(petStore.getName() + "宠物商店的结余为:" + balance); } /** * 查询待售宠物 */ public static void queryPetStock(long storeId) { PetStoreService petStore = new PetStoreServiceImpl(); Pet pet = null; List<Pet> petList = petStore.getPetsInstock(storeId); System.out.println("序号\t" + "宠物名称\t" + " 类型\t" ); for (int i = 0; i < petList.size(); i++) { pet = petList.get(i); System.out.println((i + 1) +"\t"+ pet.getName()+"\t"+ pet.getTypeName()+"\t"); } } /** * 宠物商店购买宠物 */ public static void storeBuy(PetStore store) { Scanner input = new Scanner(System.in); PetStoreService petStore = new PetStoreServiceImpl(); Pet pet = null; List<Pet> petList = petStore.getPetSelling(); System.out.println("-------以下是宠物主人正在出售的宠物-------"); System.out.println("序号\t" + "宠物名称\t" + " 类型\t" + "\t元宝数\t"); for (int i = 0; i < petList.size(); i++) { pet = petList.get(i); double price = petStore.charge(pet);// 获得到宠物的价格 System.out.println((i + 1)+"\t"+ pet.getName()+"\t"+ pet.getTypeName() +"\t"+ price+"\t" ); } System.out.println("-------请选择要购买哪个一个宠物,并输入选择项的序号-------"); int num = input.nextInt(); pet = petList.get(num - 1); petStore.buy(pet); } /** * 宠物商店出售宠物 */ public static void storeSell(PetStore store) { Scanner input = new Scanner(System.in); PetStoreService petStore = new PetStoreServiceImpl(); Pet pet = null; List<Pet> petList = petStore.getPetsInstock(store.getId()); System.out.println("-------以下是宠物商店正在出售的宠物-------"); System.out.println("序号\t" + "宠物名称\t" + "类型\t"); for (int i = 0; i < petList.size(); i++) { pet = petList.get(i); System.out.println((i + 1) +"\t"+ pet.getName() +"\t"+ pet.getTypeName()+"\t"); } System.out.println("---------请选择要购买的宠物序号--------"); boolean type = true; while (type) { int num = input.nextInt(); if ((num - 1) < petList.size() && (num - 1) >= 0) { pet = petList.get(num - 1); System.out.println("------要卖出的宠物信息如下------"); System.out.println("宠物名字叫:" + pet.getName() + " 宠物类别是:" + pet.getTypeName()); System.out.println("请确认是否卖出,y代表卖出,n代表不卖"); String code = input.next(); if (null != code) { if ("y".equals(code)) { System.out .println("------下面是现有宠物主人买家,请选择您要卖给买家序号------"); List<PetOwner> ownerList = new ArrayList<PetOwner>(); PetOwnerDao ownerDao = new PetOwnerDaoImpl(); ownerList = ownerDao.getAllOwner(); PetOwner petOwner = null; System.out.println("序号\t" + "宠物主人姓名\t"); for (int i = 0; i < ownerList.size(); i++) { petOwner = ownerList.get(i); System.out.println((i + 1) +"\t"+ petOwner.getName()+"\t"); } num = input.nextInt(); if ((num - 1) < ownerList.size() && (num - 1) >= 0) { petOwner = ownerList.get(num - 1); } pet.setOwnerId(petOwner.getId()); petStore.sell(pet); } else if ("n".equals(type)) { System.out .println("--------您选择放弃本次交易,希望您再次光顾----------"); } else { System.out.println("--------您的输入有误----------"); } } type = true; } else { System.out.println("输入有误,请按照序号重新输入"); type = false; } type = false;// 标识符更改为false,退出系统 } } /** * 宠物商店培育宠物 */ public static void storeBread() { PetStoreService petStore = new PetStoreServiceImpl(); Scanner input = new Scanner(System.in); System.out.println("请输入要培育宠物的类型"); String petType = input.next(); petStore.bread(petType); } /** * 创建宠物商店 */ public static void createPetStore() { PetStoreFactory storeFactory = new PetStoreFactoryImpl(); storeFactory.createPetStore(); } /** * 宠物主人购买宠物 */ public static void ownerBuy(PetOwner owner) { Scanner input = new Scanner(System.in); System.out.println("-------请输入选择要购买范围:只输入选择项的序号--------"); System.out.println("1:购买库存宠物"); System.out.println("2:购买新培育宠物"); PetStoreService petStore = new PetStoreServiceImpl(); PetOwnerService petOwner = new PetOwnerServiceImpl(); Pet pet = null; int num = input.nextInt(); List<Pet> petList = null; // num为1时购买库存宠物 boolean type = true; while (type) { if (num == 1) { petList = petStore.getPetsInstock(0); System.out.println("-------以下是库存宠物-------"); System.out.println("序号\t" + "宠物名称\t" + "类型\t"+ "\t元宝数\t"); for (int i = 0; i < petList.size(); i++) { pet = petList.get(i); double price = petStore.charge(pet);// 获得到宠物的价格 System.out.println((i + 1) +"\t"+ pet.getName() +"\t"+ pet.getTypeName() +"\t"+ price+"\t"); } System.out.println("-------请选择要购买哪个一个宠物,并输入选择项的序号-------"); num = input.nextInt(); pet = petList.get(num - 1); pet.setOwnerId(owner.getId()); petOwner.buy(pet); type = false; // num为2时购买新培育宠物 } else if (num == 2) { System.out.println("-------以下是库存宠物-------"); System.out.println("序号\t" + "宠物名称\t"+ "类型\t" + "\t元宝数\t"); petList = petStore.getPetsBread(); for (int i = 0; i < petList.size(); i++) { pet = petList.get(i); double price = petStore.charge(pet);// 获得到宠物的价格 System.out.println((i + 1)+"\t"+ pet.getName() +"\t"+ pet.getTypeName() +"\t"+ price+"\t"); } System.out.println("-------请选择要购买哪个一个宠物,并输入选择项的序号-------"); String count = input.next(); if (count.matches("[0-9]*")) { num = Integer.parseInt(count); pet = petList.get(num - 1); pet.setOwnerId(owner.getId()); petOwner.buy(pet); } type = false; } else { System.out.println("您的输入有误,请安提示输入"); type = true; } } } /** * 宠物主人向宠物商店出售自己宠物 */ public static void ownerSell(PetOwner petOwner) { Scanner input = new Scanner(System.in); PetOwnerService owner = new PetOwnerServiceImpl(); System.out.println("---------我的宠物列表--------"); List<Pet> petList = owner.getMyPet(petOwner.getId()); System.out.println("序号\t" + "宠物名称\t" + "类型\t"); for (int i = 0; i < petList.size(); i++) { Pet pet = petList.get(i); System.out.println((i + 1)+"\t"+ pet.getName()+"\t"+ pet.getTypeName()+"\t"); } System.out.println("---------请选择要出售的宠物序号--------"); boolean type = true; while (type) { int num = input.nextInt(); if ((num - 1) < petList.size() && (num - 1) >= 0) { Pet pet = petList.get(num - 1); System.out.println("------您要卖出的宠物信息如下------"); System.out.println("宠物名字叫:" + pet.getName() + " 宠物类别是:" + pet.getTypeName()); System.out.println("请确认是否卖出,y代表卖出,n代表不卖"); String code = input.next(); if (null != code) { if ("y".equals(code)) { System.out.println("------下面是现有宠物商店,请选择您要卖给买家序号------"); List<PetStore> storeList = new ArrayList<PetStore>(); PetStoreDao storeDao = new PetStoreDaoImpl(); storeList = storeDao.getAllStore(); PetStore petStore = null; System.out.println("序号\t" + "宠物商店名字\t"); for (int i = 0; i < storeList.size(); i++) { petStore = storeList.get(i); System.out.println((i + 1) +"\t"+ petStore.getName()+"\t"); } num = input.nextInt(); if ((num - 1) < storeList.size() && (num - 1) >= 0) { petStore = storeList.get(num - 1); } pet.setStoreId(petStore.getId()); owner.sell(pet); } else if ("n".equals(type)) { System.out .println("--------您选择放弃本次交易,希望您再次光顾----------"); } else { System.out.println("--------您的输入有误----------"); } } type = true; } else { System.out.println("输入有误,请按照序号重新输入"); type = false; } type = false;// 标识符更改为false,退出系统 } } /** * 查看商店帐目 */ public static void getAccount(long storeId) { PetStoreService store = new PetStoreServiceImpl(); List<Account> list = store.account(storeId); for (int i = 0; i < list.size(); i++) { Account account = list.get(i); String type = null; if (1 == account.getDealType()) { type = "商店卖给宠物主人"; } else if (2 == account.getDealType()) { type = "宠物主人卖给商店"; } else { type = "宠物主人之间交易"; } System.out.println("第" + (i + 1) + "笔交易,交易类型为:" + type + ",交易金额是:" + account.getPrice() + "个元宝"); } } }