首页 > 编程语言 >Java基础项目:超市管理项目

Java基础项目:超市管理项目

时间:2022-12-23 15:22:08浏览次数:43  
标签:Java 项目 int System 超市 println return public out

JavaSE项目:超市管理系统项目:

上面项目所用的表结构:
image
image
image
image
image

实体类:

@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Cart {
    private Integer gdId;
    private BigDecimal gdPrice;
    private Integer userId;
    private BigDecimal userBalance;
    private Integer gdNum;

    @Override
    public String toString() {
        return "Cart{" +
                "gdId=" + gdId +
                ", gdPrice=" + gdPrice +
                ", userId=" + userId +
                ", gdNum=" + gdNum +
                '}';
    }
}
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Goods {
    private Integer gdId;
    private Integer typeId;
    private String gdName;
    private BigDecimal gdPrice;
    private Integer gdStore;

    @Override
    public String toString() {
        return "Goods{" +
                "gdId=" + gdId +
                ", typeId=" + typeId +
                ", gdName='" + gdName + '\'' +
                ", gdPrice=" + (gdPrice==null?null:gdPrice.doubleValue()) +
                ", gdStore=" + gdStore +
                '}';
    }
}
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Order {
    private Integer id;
    private Integer gdId;
    private BigDecimal gdPrice;
    private Integer gdNum;
    private Integer userId;
    private Date createTime;
}
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class OrderVO {
    private Integer gdId;
    private Integer typeId;
    private String gdName;
    private BigDecimal gdPrice;
    private Integer gdStore;
    private String typeName;
    private Integer gdNum;
}
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Page {
    /**
     * 总条数
     */
    private Integer contentSum;
    /**
     * 每一页的条数
     */
    private Integer count;
    /**
     * 当前页码
     */
    private Integer page;
    /**
     * 总页数
     */
    private Integer allPage;

    public void setAllPage() {
        allPage = contentSum / count;
        if (contentSum % count != 0) allPage++;
    }
}
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Type {
    private Integer typeId;
    private String typeName;
    private Integer typeRank;
    private Integer typeParentType;
    private Date typeCreateTime;
    private Date typeUpdateTime;
    private String typeParentName;

    @Override
    public String toString() {
        return "Type{" +
                "typeId=" + typeId +
                ", typeName='" + typeName + '\'' +
                ", typeRank=" + typeRank +
                ", typeParentType=" + typeParentType +
                ", typeCreateTime=" + typeCreateTime +
                ", typeUpdateTime=" + typeUpdateTime +
                ", typeParentName='" + typeParentName + '\'' +
                '}';
    }
}
@Setter
@Getter
@NoArgsConstructor
public class UserInfo {
    private Integer userId;
    private String userName;
    private String userPwd;
    private Integer userRole;//[0、普通用户  1、管理员]
    private Integer userVip;
    private BigDecimal userBalance;
    private Integer vipScore;

    public UserInfo(String userName, String userPwd) {
        this.userName = userName;
        this.userPwd = userPwd;
    }

    @Override
    public String toString() {
        return "UserInfo{" +
                "userId=" + userId +
                ", userName='" + userName + '\'' +
                ", userPwd='" + userPwd + '\'' +
                ", userRole=" + (userRole == 0 ? "顾客" : (userRole == 1 ? "管理员" : "收银员")) +
                ", userVip=" + (userVip == 0 ? "普通用户" : "会员:" + userVip) +
                ", userBalance=" + (userBalance == null ? null : userBalance.doubleValue()) +
                '}';
    }


}

控制层:

public class UserAction {
    private static Scanner scanner = new Scanner(System.in);
    public static UserService service = new UserServiceImpl();
    public static void startMenu() {
        boolean b = true;
        while (b) {
            System.out.println("*********欢迎使用liku超市管理系统*********");
            System.out.println("请选择:");
            System.out.println("1、登录");
            System.out.println("2、注册");
            System.out.println("0、退出");
            int i = scanner.nextInt();
            switch (i) {
                case 1:
                    UserInfo login = service.login();
                    if (login == null) System.out.println("登录失败!用户名和密码不匹配");
                    else if (login.getUserRole() == 1)
                        AdminAction.adminStart();
                    else if (login.getUserRole() == 0)
                        CartAction.customStart(login);
                    else if (login.getUserRole() == 2)
                        CheckerAction.checkerStart(scanner);
                    break;
                case 2:
                    service.register();
                    break;
                case 0:
                    b = false;
                    System.out.println("系统已退出!");
                    break;
            }
        }

    }
    public static void vipCustomer() {
        while (true) {
            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("0、返回上一层");
            int choice = scanner.nextInt();
            switch (choice) {
                case 1:service.addVip();
                    break;
                case 2:service.deleteVip();
                    break;
                case 3:service.updateVip();
                    break;
                case 4:service.select();
                    break;
                case 5:service.save();
                    break;
                case 0:
                    System.out.println("已返回!");
                    return;
            }
        }
    }
}
public class AdminAction {
    public static TypeService typeService = new TypeServiceImpl();
    private static Scanner scanner = new Scanner(System.in);
    private static GoodsService goodsService = new GoodsServiceImpl();
    public static void adminStart() {
        while (true) {
            System.out.println("*********欢迎使用liku超市管理系统*********");
            System.out.println("1、商品类型管理");
            System.out.println("2、商品管理");
            System.out.println("3、会员管理");
            System.out.println("4、添加管理员");
            System.out.println("0、退出系统");
            int choice = scanner.nextInt();
            switch (choice) {
                case 1:
                    typeManage();
                    break;
                case 2:
                    goodsManage();
                    break;
                case 3:UserAction.vipCustomer();
                    break;
                case 4:
                    UserAction.service.regist();
                    break;
                case 0:
                    System.out.println("系统已退出!");
                    return;
            }
        }
    }


    private static void goodsManage() {
        while (true) {
            System.out.println("*************商品管理*************");
            System.out.println("1、添加商品");
            System.out.println("2、删除商品");
            System.out.println("3、修改商品");
            System.out.println("4、查看商品");
            System.out.println("0、返回上一层");
            int choice = scanner.nextInt();
            switch (choice) {
                case 1:goodsService.add();
                    break;
                case 2:goodsService.delete();
                    break;
                case 3:goodsService.update();
                    break;
                case 4:goodsService.select();
                    break;
                case 0:
                    System.out.println("已返回!");
                    return;
            }
        }
    }

    private static void typeManage() {
        while (true) {
            System.out.println("*************商品类型管理*************");
            System.out.println("1、添加类型");
            System.out.println("2、删除类型");
            System.out.println("3、修改类型");
            System.out.println("4、查看所有类型");
            System.out.println("0、返回上一层");
            int choice = scanner.nextInt();
            switch (choice) {
                case 1:
                    typeService.add();
                    break;
                case 2:
                    typeService.delete();
                    break;
                case 3:
                    typeService.update();
                    break;
                case 4:
                    typeService.select();
                    break;
                case 0:
                    System.out.println("已返回!");
                   return;
            }
        }
    }
}
public class CartAction {
    private static GoodsService goodsService=new GoodsServiceImpl();
    private static Scanner scanner=new Scanner(System.in);
    private static CartService cartService=new CartServiceImpl();
    public static void customStart(UserInfo userInfo){
        while (true) {
            System.out.println("*********欢迎使用liku超市管理系统*********");
            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("8、会员积分换购");
            System.out.println("0、退出系统");
            int choice=scanner.nextInt();
            switch (choice) {
                case 1:goodsService.showToUser();
                    break;
                case 2:cartService.add(userInfo);
                    break;
                case 3:cartService.update(userInfo);
                    break;
                case 4:cartService.delete(userInfo);
                    break;
                case 5:cartService.select(userInfo);
                    break;
                case 6:cartService.summary(userInfo);
                    break;
                case 7:cartService.showScore(userInfo);
                    break;
                case 8:cartService.purchase(userInfo);
                    break;
                case 0:
                    System.out.println("系统已退出!");
                    return;
            }
        }
    }
}
public class CheckerAction {
    private static OrderService orderService = new OrderServiceImpl();

    public static void checkerStart(Scanner scanner) {
        while (true) {
            System.out.println("*********欢迎使用liku超市管理系统*********");
            System.out.println("1、订单查询");
            System.out.println("2、排行统计");
            System.out.println("0、退出系统");
            int choice = scanner.nextInt();
            switch (choice) {
                case 1:orderService.select();
                    break;
                case 2:orderService.rank();
                    break;
                case 0:
                    System.out.println("系统已退出!");
                    return;
            }
        }
    }
}

工具包:

public class ClassUtil {
    /**
     * 根据表列名来获取对应方法名
     * @param label
     * @return
     */
    public static String getMethodName(String label) {
        StringBuilder builder=new StringBuilder("set");
        String[] split = label.split("_");
        for (String s : split) {
            builder.append(String.valueOf(s.charAt(0)).toUpperCase());
            builder.append(s.substring(1));
        }
        return builder.toString();
    }

    /**
     * 根据路径获取反射类
     * @param classPath
     * @return
     */
    public static Class getClass(String classPath){
        if("java.sql.Timestamp".equals(classPath)||"java.sql.Date".equals(classPath))classPath="java.util.Date";
        if("java.math.Decimal".equals(classPath))classPath="java.math.BigDecimal";
        try {
            return Class.forName(classPath);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据方法名和路径得到方法 并赋值
     * @param destObject
     * @param value
     * @param path
     * @param methodName
     */
    public static void invoke(Object destObject,Object value,Class path,String methodName){
        Class<?> aClass = destObject.getClass();
        try {
            Method method = aClass.getMethod(methodName, path);
            method.invoke(destObject,value);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }

    }
}

封装的数据库操作:

public class SqlUtil {
    /**
     * 获取数据库连接
     *
     * @return
     */
    public static Connection getConnections() {
        Properties p = new Properties();
        try {
            p.load(SqlUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            Class.forName(p.getProperty("driver"));
            return DriverManager.getConnection(p.getProperty("url"), p.getProperty("user"), p.getProperty("pwd"));
        } catch (IOException | ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 判断数据库是否连接成功
     *
     * @param connection
     * @return
     */
    public static boolean isConnect(Connection connection) {
        try {
            if (connection.isClosed()) return false;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 关闭数据库连接【释放资源】
     *
     * @param connection
     * @param statement
     */
    public static void close(Connection connection, Statement statement) {
        try {
            if (connection != null && !connection.isClosed()) connection.close();
            if (statement != null && !statement.isClosed()) statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭数据库连接【释放资源】
     *
     * @param connection
     * @param statement
     * @param resultset
     */
    public static void close(Connection connection, Statement statement, ResultSet resultset) {
        close(connection, statement);
        try {
            if (resultset != null && !resultset.isClosed()) resultset.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 对数据库进行简单增删改
     *
     * @param sql
     * @param args
     * @return
     */
    public static int update(String sql, Object... args) {
        Connection connections = getConnections();
        if (!isConnect(connections)) {
            return -1;
        }
        int i = 0;
        PreparedStatement statement = null;
        try {
            statement = connections.prepareStatement(sql);
            for (int j = 0; j < args.length; j++) {
                statement.setObject((j + 1), args[j]);
            }
            i = statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close(connections, statement);
        }
        return i;
    }
   /**
     * 事务中进行增删改
     * @param connections
     * @param sql
     * @param args
     * @return
     */
    public static int update(Connection connections, String sql, Object... args) {
        if (!isConnect(connections)) {
            return -1;
        }
        int i = 0;
        PreparedStatement statement = null;
        try {
            statement = connections.prepareStatement(sql);
            for (int j = 0; j < args.length; j++) {
                statement.setObject((j + 1), args[j]);
            }
            i = statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return i;
    }

    /**
     * 查询数据库内容
     *
     * @param sql
     * @param t
     * @param args
     * @param <T>
     * @return
     */
    public static <T> List<T> select(String sql, Class t, Object... args) {
        Connection connections = getConnections();
        if (!isConnect(connections)) {
            return null;
        }
        int i = 0;
        List<T> list = new ArrayList<>(10);
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        Object object;
        try {
            statement = connections.prepareStatement(sql);
            if (args != null && args.length > 0)
                for (int i1 = 0; i1 < args.length; i1++) {
                    statement.setObject((i1 + 1), args[i1]);
                }
            resultSet = statement.executeQuery();
            ResultSetMetaData metaData = statement.getMetaData();
            while (resultSet.next()) {
                object = t.newInstance();
                for (int j = 0; j < metaData.getColumnCount(); j++) {
                    String columnLabel = metaData.getColumnLabel((j + 1));
                    String columnClassName = metaData.getColumnClassName((j + 1));
                    Object value = resultSet.getObject(columnLabel);
                    ClassUtil.invoke(object, value, ClassUtil.getClass(columnClassName), ClassUtil.getMethodName(columnLabel));
                }
                list.add((T) object);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } finally {
            close(connections, statement, resultSet);
        }
        return list;
    }

    /**
     * DBUtils的查询
     * @param sql
     * @param clazz
     * @param params
     * @param <T>
     * @return
     */
    public static<T> List<T>query(String sql, Class<T> clazz, Object... params){
        List<T> list = new ArrayList<>(10);
        //获取连接对象
        Connection connection = getConnections();
        if (isConnect(connection)) {
            try {
                list = new QueryRunner().query(connection, sql, new BeanListHandler<>(clazz), params);
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                DbUtils.closeQuietly(connection);
            }
        }
        return list;
    }
/**
     * 查找单行值
     * @param sql
     * @param t
     * @param args
     * @param <T>
     * @return
     */
    public static <T> T selectObejct(String sql, Class t, Object... args) {
        Connection connections = getConnections();
        if (!isConnect(connections)) {
            return null;
        }
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        Object object = null;
        try {
            statement = connections.prepareStatement(sql);
            object = t.newInstance();
            for (int i1 = 0; i1 < args.length; i1++) {
                statement.setObject((i1 + 1), args[i1]);
            }
            resultSet = statement.executeQuery();
            ResultSetMetaData metaData = statement.getMetaData();
            if (resultSet.next()) {
                for (int j = 0; j < metaData.getColumnCount(); j++) {
                    String columnLabel = metaData.getColumnLabel((j + 1));
                    String columnClassName = metaData.getColumnClassName((j + 1));
                    Object value = resultSet.getObject(columnLabel);
                    ClassUtil.invoke(object, value, ClassUtil.getClass(columnClassName), ClassUtil.getMethodName(columnLabel));
                }
            } else return null;
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } finally {
            close(connections, statement, resultSet);
        }
        return (T) object;
    }

    /**
     * 利用DBUtils获取聚合函数
     *
     * @param sql
     * @param args
     * @return
     */
    public static BigDecimal fun(String sql, Object... args) {
        Connection connection = getConnections();
        if (!isConnect(connection)) return null;
        BigDecimal i=null;
        try {
            i =new QueryRunner().query(connection, sql, new ScalarHandler<BigDecimal>(), args);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DbUtils.closeQuietly(connection);
        }
        return i;
    }

    /**
     * 求总条数
     * @param sql
     * @param args
     * @return
     */
    public static int count(String sql, Object... args) {
        Connection connection = getConnections();
        if (!isConnect(connection)) return -1;
        int i=0;
        try {
            i =new QueryRunner().query(connection, sql, new ScalarHandler<Long>(), args).intValue();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DbUtils.closeQuietly(connection);
        }
        return i;
    }

    /**
     * 得到整型列的单值
     * @param sql
     * @param args
     * @return
     */
    public static Integer column(String sql,Object...args){
        Connection connection=getConnections();
        if(!isConnect(connection))return null;
        Integer object = null;
        PreparedStatement ps=null;
        ResultSet resultSet=null;
        try {
            ps= connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject((i+1),args[i]);
            }
             resultSet= ps.executeQuery();
            if(resultSet.next()) object= (Integer) resultSet.getObject(1);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            close(connection,ps,resultSet);
        }
        return object;
    }
}

数据层:接口和实现类

public interface UserDao {
    Integer score(int id);
    /**
     * 添加普通用户
     *
     * @param userInfo
     * @return
     */
    int addUser(UserInfo userInfo);

    /**
     * 添加管理员
     *
     * @param userInfo
     * @return
     */
    int addAdmin(UserInfo userInfo);

    /**
     * 根据用户名密码去查找用户信息
     *
     * @param name
     * @param pwd
     * @return
     */
    UserInfo selectUser(String name, String pwd);

    /**
     * 修改顾客为vip
     *
     * @return
     */
    int addVip(int id);

    /**
     * 根据编号查找单个用户
     * @param id
     * @return
     */
    UserInfo selectUser(int id);

    /**
     * 根据编号删除会员
     * @param id
     * @return
     */
    int deleteVip(int id);

    /**
     * 根据编号修改会员信息
     * @param userInfo
     * @return
     */
    int updateVip(UserInfo userInfo);

    /**
     * 查找所有会员
     * @return
     */
    List<UserInfo> selectAllVip();

    /**
     * 会员充值
     * @param id
     * @param save
     * @return
     */
    int saveVip(int id, BigDecimal save);

    /**
     * 根据会员卡号查找会员信息
     * @param vip
     * @return
     */
    UserInfo selectVip(int vip);
}
public class UserDaoImpl implements UserDao {
    private ThreadLocalRandom random=ThreadLocalRandom.current();
    @Override
    public Integer score(int id) {
        String sql="select vip_score from tb_user where user_id=?";
        return SqlUtil.column(sql,id);
    }

    @Override
    public int addUser(UserInfo userInfo) {
        String sql="insert into tb_user values(null,?,?,0,default,null,null)";
        return SqlUtil.update(sql,userInfo.getUserName(),userInfo.getUserPwd());
    }

    @Override
    public int addAdmin(UserInfo userInfo) {
        String sql="insert into tb_user values(null,?,?,1,default,null,null)";
        return SqlUtil.update(sql,userInfo.getUserName(),userInfo.getUserPwd());
    }

    @Override
    public UserInfo selectUser(String name, String pwd) {
        String sql="select * from tb_user where user_name=? and user_pwd=?";
        return SqlUtil.selectObejct(sql,UserInfo.class,name,pwd);
    }

    @Override
    public int addVip(int id) {
        String sql="update tb_user set user_vip=? where user_id=?";
        return SqlUtil.update(sql,random.nextInt(100000,999999),id);
    }

    @Override
    public UserInfo selectUser(int id) {
        String sql="select * from tb_user where user_id=?";
        return SqlUtil.selectObejct(sql,UserInfo.class,id);
    }

    @Override
    public int deleteVip(int id) {
        String sql="update tb_user set user_vip=null where user_id=?";
        return SqlUtil.update(sql,id);
    }

    @Override
    public int updateVip(UserInfo userInfo) {
        String sql="update tb_user set user_name=?,user_pwd=?,user_vip=?,vip_score=? where user_id=?";
        return SqlUtil.update(sql,userInfo.getUserName(),userInfo.getUserPwd(),userInfo.getUserVip(),userInfo.getVipScore(),userInfo.getUserId());
    }

    @Override
    public List<UserInfo> selectAllVip() {
        String sql="select * from tb_user where user_vip is not null";
        return SqlUtil.select(sql,UserInfo.class);
    }

    @Override
    public int saveVip(int id, BigDecimal save) {
        String sql="update tb_user set user_balance=? where user_id=?";
        return SqlUtil.update(sql,save,id);
    }

    @Override
    public UserInfo selectVip(int vip) {
        String sql="select * from tb_user where user_vip=?";
        return SqlUtil.selectObejct(sql,UserInfo.class,vip);
    }
}
public interface TypeDao {
    /**
     * 查找所有分类
     * @return
     */
    List<Type> selectAll();
    /**
     * 查找所有二级分类
     * @return
     */
    List<Type> select();

    /**
     * 根据编号查找单个二级分类
     * @param id
     * @return
     */
    Type selectType(int id);

    /**
     * 添加商品类别
     * @param type
     * @return
     */
    int add(Type type);

    /**
     * 根据类型等级查找最高等级的类型名称和编号
     *
     * @return
     */
    List<Type> typeName();

    /**
     * 根据类型信息来删除类型
     *
     * @param type
     * @return
     */
    int delete(Type type);

    /**
     * 根据类型编号修改类型信息
     * @param id
     * @return
     */
    int update(int id,String name,Integer rank,Integer parent);
}
public class TypeDaoImpl implements TypeDao {
    @Override
    public List<Type> selectAll() {
        String sql="select * from tb_type";
        return SqlUtil.select(sql,Type.class);
    }

    @Override
    public List<Type> select() {
        String sql = "select t1.*,t2.type_name typeParentName from tb_type t1 inner join tb_type t2 on t1.type_parent_type=t2.type_id";
        return SqlUtil.select(sql, Type.class);
    }

    @Override
    public Type selectType(int id) {
        String sql = "select t1.*,t2.type_name typeParentName from tb_type t1 left join tb_type t2 on t1.type_parent_type=t2.type_id where t1.type_id=?";
        return SqlUtil.selectObejct(sql, Type.class, id);
    }

    @Override
    public int add(Type type) {
        String sql = "insert into tb_type values(null,?,?,?,default,now())";
        return SqlUtil.update(sql, type.getTypeName(), type.getTypeRank(), type.getTypeParentType());
    }

    @Override
    public List<Type> typeName() {
        String sql = "select type_id,type_name from tb_type where type_rank=0";
        return SqlUtil.select(sql, Type.class);
    }

    @Override
    public int delete(Type type) {
        String sql = "delete from tb_type where type_id=?";
        if (type.getTypeRank() == 0) {
            sql = "delete from tb_type where type_id=? or type_parent_type=?";
            return SqlUtil.update(sql, type.getTypeId(), type.getTypeId());
        }
        return SqlUtil.update(sql, type.getTypeId());
    }

    @Override
    public int update(int id, String name, Integer rank, Integer parent) {
        StringBuilder sql = new StringBuilder("update tb_type set ");

        if (!"".equals(name) && !"".equals(rank)) {
            if (rank == 0) parent = null;
            sql.append("type_name=?,type_rank=?,type_parent_type=? where type_id=?");
            return SqlUtil.update(sql.toString(), name, rank, parent, id);
        } else if (!"".equals(name)) {
            sql.append("type_name=? where type_id=?");
            return SqlUtil.update(sql.toString(), name, id);
        }
        if (rank == 0) parent = null;
        sql.append("type_rank=?,type_parent_type=? where type_id=?");
        return SqlUtil.update(sql.toString(), rank, parent, id);
    }
}
public interface OrderDao {
    /**
     * 事务添加
     * @param connection
     * @param cart
     * @return
     */
    int add(Connection connection,Cart cart);

    /**
     * 根据商品编号和会员号查找订单
     * @param gdId
     * @param vipNum
     * @return
     */
    List<Order> select(int gdId,int vipNum);

    /**
     * 排序展示
     * @return
     */
    List<OrderVO> rank();

    /**
     * 根据商品编号统计总销量
     * @param id
     * @return
     */
    int sum(int id);
}
public class OrderDaoImpl implements OrderDao {
    @Override
    public int add(Connection connection,Cart cart) {
        String sql="insert into tb_order values(null,?,?,?,?,now())";
        return SqlUtil.update(connection,sql,cart.getGdId(),cart.getGdPrice(),cart.getGdNum(),cart.getUserId());
    }

    @Override
    public List<Order> select(int gdId, int vipNum) {
        String sql="select * from tb_order where gd_id=? and user_id=?";
        return SqlUtil.select(sql,Order.class,gdId,vipNum);
    }

    @Override
    public List<OrderVO> rank() {
        String sql="select t2.*,t3.type_name,t1.gd_num from tb_order t1 inner join tb_goods t2 on t1.gd_id=t2.gd_id inner join " +
                "tb_type t3 on t3.type_id=t2.type_id order by t1.gd_num desc,t3.type_name,t1.create_time limit 10";
        return SqlUtil.select(sql,OrderVO.class);
    }

    @Override
    public int sum(int id) {
        String sql="select sum(gd_num) from tb_order where gd_id=?";
        return SqlUtil.fun(sql,id).intValue();
    }
}
public interface GoodsDao {
    /**
     * 查找商品总数
     *
     * @return
     */
    int count();

    /**
     * 分页查询
     *
     * @param page
     * @return
     */
    List<Goods> selectByPage(Page page);

    /**
     * 展示所有商品
     *
     * @return
     */
    List<Goods> select();

    /**
     * 添加商品信息
     *
     * @param goods
     * @return
     */
    int add(Goods goods);

    /**
     * 根据商品编号删除商品
     *
     * @param id
     * @return
     */
    int delete(int id);

    /**
     * 根据商品编号查找单个商品
     *
     * @param id
     * @return
     */
    Goods select(int id);

    /**
     * 根据类型编号查找所有商品
     *
     * @param typeId
     * @return
     */
    List<Goods> selectType(int typeId);

    /**
     * 根据商品种类编号修改种类
     *
     * @param typeId
     * @return
     */
    int updateType(int typeId);

    /**
     * 修改商品
     *
     * @param goods
     * @return
     */
    int update(Goods goods);

    /**
     * 事务修改库存
     *
     * @param connection
     * @param id
     * @param num
     * @return
     */
    int updateStore(Connection connection, int id, int num);
}
public class GoodsDaoImpl implements GoodsDao {
    @Override
    public int count() {
        String sql="select count(*) from tb_goods";
        return SqlUtil.count(sql);
    }

    @Override
    public List<Goods> selectByPage(Page page) {
        StringBuilder sql=new StringBuilder("select * from tb_goods limit ");
        sql.append(page.getPage()*page.getCount()+",");
        sql.append(page.getCount());
        return SqlUtil.select(sql.toString(),Goods.class);
    }

    @Override
    public List<Goods> select() {
        String sql="select * from tb_goods";
        return SqlUtil.select(sql,Goods.class);
    }

    @Override
    public int add(Goods goods) {
        String sql = "insert into tb_goods values(null,?,?,?,?)";
        return SqlUtil.update(sql, goods.getTypeId(), goods.getGdName(), goods.getGdPrice(), goods.getGdStore());
    }

    @Override
    public int delete(int id) {
        String sql = "delete from tb_goods where gd_id=?";
        return SqlUtil.update(sql, id);
    }

    @Override
    public Goods select(int id) {
        String sql = "select * from tb_goods where gd_id=?";
        return SqlUtil.selectObejct(sql, Goods.class, id);
    }

    @Override
    public List<Goods> selectType(int typeId) {
        String sql = "select * from tb_goods where type_id=?";
        return SqlUtil.select(sql, Goods.class, typeId);
    }

    @Override
    public int updateType(int typeId) {
        String sql = "update tb_goods set type_id=? where type_id=?";
        return SqlUtil.update(sql, 1, typeId);
    }

    @Override
    public int update(Goods goods) {
        String sql = "update tb_goods set type_id=?,gd_name=?,gd_price=?,gd_store=? where gd_id=?";
        return SqlUtil.update(sql, goods.getTypeId(), goods.getGdName(), goods.getGdPrice(), goods.getGdStore(), goods.getGdId());
    }

    @Override
    public int updateStore(Connection connection,int id, int num) {
        String sql="update tb_goods set gd_store=? where gd_id=?";
        return SqlUtil.update(connection,sql,num,id);
    }

}
public interface CartDao {
    /**
     * 加入购物车
     * @param userInfo
     * @param goods
     * @param num
     * @return
     */
    int add(UserInfo userInfo, Goods goods, int num);

    /**
     * 删除购物车中的商品
     * @param id
     * @param userId
     * @return
     */
    int delete(int id,int userId);

    /**
     * 修改购物车商品的数量
     * @param id
     * @param num
     * @param userId
     * @return
     */
    int update(int id,int num,int userId);

    /**
     * 展示购物车
     * @param id
     * @return
     */
    List<Cart> select(int id);

    /**
     * 从购物车查找该商品信息
     * @param gdId
     * @param userId
     * @return
     */
    Cart selectSingle(int gdId,int userId);

    /**
     * 结算
     * @param userId
     * @return
     */
    BigDecimal summary(int userId);
}
public class CartDaoImpl implements CartDao {
    @Override
    public int add(UserInfo userInfo,Goods goods,int num) {
        String sql="insert into tb_cart values(?,?,?,?,?)";
        return SqlUtil.update(sql,goods.getGdId(),goods.getGdPrice(),userInfo.getUserId(),userInfo.getUserBalance(),num);
    }

    @Override
    public int delete(int id,int userId) {
        String sql="delete from tb_cart where gd_id=? and user_id=?";
        return SqlUtil.update(sql,id,userId);
    }

    @Override
    public int update(int gdId,int num,int userId) {
        String sql="update tb_cart set gd_num=? where gd_id=? and user_id=?";
        return SqlUtil.update(sql,num,gdId,userId);
    }

    @Override
    public List<Cart> select(int id) {
        String sql="select * from tb_cart where user_id=?";
        return SqlUtil.select(sql,Cart.class,id);
    }

    @Override
    public Cart selectSingle(int gdId,int userId) {
        String sql="select * from tb_cart where gd_id=? and user_id=?";
        return SqlUtil.selectObejct(sql,Cart.class,gdId,userId);
    }

    @Override
    public BigDecimal summary(int userId) {
        String sql="select sum(gd_price) from tb_cart where user_id=?";
        return SqlUtil.fun(sql,userId);
    }

}

业务层:接口和实现类

public interface UserService {
    /**
     * 输入用户名密码从数据库查到用户
     *
     * @return 登录用户
     */
    UserInfo login();

    /**
     * 注册用户
     */
    void register();

    /**
     * 注册管理员
     */
    void regist();

    /**
     * 添加会员
     */
    void addVip();

    /**
     * 删除会员
     */
    void deleteVip();

    /**
     * 修改会员
     */
    void updateVip();

    /**
     * 查看所有会员
     */
    void select();

    /**
     * 余额充值
     */
    void save();
}
public class UserServiceImpl implements UserService {
    private Scanner scanner = new Scanner(System.in);
    private UserDao dao = new UserDaoImpl();

    @Override
    public UserInfo login() {
        System.out.println("请输入您的用户名:");
        String name = scanner.next();
        System.out.println("请输入您的密码:");
        String pwd = scanner.next();
        return dao.selectUser(name, pwd);
    }

    @Override
    public void register() {
        System.out.println("请输入您的用户名:");
        String name = scanner.next();
        System.out.println("请输入您的密码:");
        String pwd = scanner.next();
        int i = dao.addUser(new UserInfo(name, pwd));
        if (i > 0) System.out.println("注册成功!");
        else System.out.println("注册失败");
    }

    @Override
    public void regist() {
        System.out.println("请输入您的用户名:");
        String name = scanner.next();
        System.out.println("请输入您的密码:");
        String pwd = scanner.next();
        int i = dao.addAdmin(new UserInfo(name, pwd));
        if (i > 0) System.out.println("注册成功!");
        else System.out.println("注册失败");
    }

    @Override
    public void addVip() {
        System.out.println("请输入需要添加的用户编号");
        UserInfo userInfo = dao.selectUser(scanner.nextInt());
        if(userInfo==null){
            System.out.println("用户不存在!");
            return;
        }
        int i = dao.addVip(userInfo.getUserId());
        if(i>0) System.out.println("添加会员成功!");
        else System.out.println("添加会员失败!");
    }

    @Override
    public void deleteVip() {
        System.out.println("请输入需要删除的用户编号");
        int id=scanner.nextInt();
        UserInfo userInfo = dao.selectUser(id);
        if(userInfo==null||userInfo.getUserVip()==0) {
            System.out.println("想要删除的会员不存在!");
            return;
        }
        int i = dao.deleteVip(id);
        if(i>0) System.out.println("删除会员成功!");
        else System.out.println("删除会员失败!");
    }

    @Override
    public void updateVip() {
        System.out.println("请输入需要修改的会员编号:");
        UserInfo userInfo = dao.selectUser(scanner.nextInt());
        if(userInfo==null||userInfo.getUserVip()==0){
            System.out.println("输入会员不存在");
            return;
        }
        System.out.println("请输入修改后的会员名称:");
        userInfo.setUserName(scanner.next());
        System.out.println("请输入修改后的会员密码:");
        userInfo.setUserPwd(scanner.next());
        System.out.println("请输入修改后的会员状态:【0、普通用户,1、会员】");
        int i1 = scanner.nextInt();
        if(i1==1) userInfo.setUserVip(ThreadLocalRandom.current().nextInt(100000,999999));
        else userInfo.setUserVip(null);
        int i = dao.updateVip(userInfo);
        if(i>0) System.out.println("修改成功!");
        else System.out.println("修改失败!");
    }

    @Override
    public void select() {
        dao.selectAllVip().forEach(System.out::println);
    }

    @Override
    public void save() {
        System.out.println("请输入需要充值的会员编号:");
        UserInfo userInfo = dao.selectUser(scanner.nextInt());
        if(userInfo==null||userInfo.getUserVip()==0){
            System.out.println("输入会员不存在");
            return;
        }
        System.out.println("请输入需要充值的会员金额:");
        BigDecimal money=BigDecimal.valueOf(scanner.nextDouble());
        money=userInfo.getUserBalance().add(money);
        int i = dao.saveVip(userInfo.getUserId(), money);
        if(i>0) System.out.println("充值成功!");
        else System.out.println("充值失败!");
    }

}
public interface TypeService {
    void select();
    void add();
    void delete();
    void update();
}
public class TypeServiceImpl implements TypeService {
    private TypeDao typeDao = new TypeDaoImpl();
    private Scanner scanner = new Scanner(System.in);
    private GoodsDao goodsDao = new GoodsDaoImpl();

    @Override
    public void select() {
        typeDao.selectAll().forEach(System.out::println);
    }

    @Override
    public void add() {
        Type type = new Type();
        System.out.println("请输入你想要添加的类型名称:");
        String name = scanner.next();
        System.out.println("请输入你想要添加的类型等级:【0、一级分类,1、二级分类】");
        int rank = scanner.nextInt();
        if (rank == 1) {
            System.out.println("请输入你想要添加的类型所属类别编号:");
            typeDao.typeName().forEach((types) -> System.out.println("类型编号" + types.getTypeId() + "\t" + types.getTypeName()));
            int parentType = scanner.nextInt();
            type.setTypeParentType(parentType);
        } else type.setTypeParentType(null);
        type.setTypeName(name);
        type.setTypeRank(rank);
        int add = typeDao.add(type);
        if (add > 0) System.out.println("添加成功!");
        else System.out.println("添加失败!");
    }

    @Override
    public void delete() {
        System.out.println("请输入需要删除的类型编号:");
        int id = scanner.nextInt();
        Type type = typeDao.selectType(id);
        if (type == null) {
            System.out.println("输入编号无对应类型!已返回");
            return;
        }
        System.out.println("您想要删除的类型信息为:确认是否删除?【y/n】");
        System.out.println(type);
        if (type.getTypeName() != null && type.getTypeRank() == 0)
            System.out.println("该类型为一级类型,如若删除,其下二级类型也会被全部删除:确认是否删除?【y/n】");
        String asw = scanner.next().toUpperCase();
        if ("Y".equals(asw)) {
            System.out.println("该类型下所有商品将会修改商品类型为默认类型,请问是否删除?【y/n】");
            asw = scanner.next().toUpperCase();
            if("Y".equals(asw)){
                int i = goodsDao.updateType(id);
                if(i>0) {
                    int delete = typeDao.delete(type);
                    if (delete > 0) {
                        System.out.println("删除成功!");

                    } else System.out.println("删除失败!");
                }
            }

        }

    }

    @Override
    public void update() {
        System.out.println("请输入您需要修改的类型编号:");
        int id = scanner.nextInt();
        Type type = typeDao.selectType(id);
        if (type == null) {
            System.out.println("输入编号属于不属于二级分类!您无权修改,已返回");
            return;
        }
        System.out.println(type);
        //String name, Integer rank, Integer parent
        System.out.println("请输入修改后的类型名称");
        scanner.nextLine();
        String name = scanner.nextLine();
        System.out.println("请输入修改后的类型级别【0、一级分类,1、二级分类】");
        String rank = scanner.nextLine();
        String parent = null;
        if (Integer.valueOf(rank) == 1) {
            System.out.println("请输入修改后的类型所属类别编号:");
            typeDao.typeName().forEach((types) -> {
                if (types.getTypeId() != id)
                    System.out.println("类型编号" + types.getTypeId() + "\t" + types.getTypeName());
            });
            parent = scanner.nextLine();
        }
        if (parent != null) {
            int update = typeDao.update(id, name, Integer.valueOf(rank), Integer.valueOf(parent));
            if (update > 0) System.out.println("修改成功!");
            else System.out.println("修改失败");
        } else {
            int update = typeDao.update(id, name, Integer.valueOf(rank), null);
            if (update > 0) System.out.println("修改成功!");
            else System.out.println("修改失败");
        }
    }

}
public interface OrderService {
    void select();
    void rank();
}
public class OrderServiceImpl implements OrderService {
    private UserDao userDao = new UserDaoImpl();
    private Scanner scanner = new Scanner(System.in);
    private OrderDao orderDao = new OrderDaoImpl();

    @Override
    public void select() {
        System.out.println("请输入商品编号:");
        int gdId = scanner.nextInt();
        System.out.println("请输入会员号:");
        int i = scanner.nextInt();
        UserInfo userInfo = userDao.selectVip(i);
        if (userInfo == null || userInfo.getUserVip() == 0) {
            System.out.println("输入会员号不存在!");
            return;
        }
        orderDao.select(gdId, userInfo.getUserId()).forEach(System.out::println);
    }

    @Override
    public void rank() {
        orderDao.rank().stream().peek(orderVO ->orderVO.setGdNum(orderDao.sum(orderVO.getGdId()))).distinct().sorted(new Comparator<OrderVO>() {
            @Override
            public int compare(OrderVO o1, OrderVO o2) {
                return o2.getGdNum()-o1.getGdNum();
            }
        }).collect(Collectors.toList()).forEach(System.out::println);
    }
}
public interface GoodsService {
    void add();
    void delete();
    void update();
    void select();
    void showToUser();
}
public class GoodsServiceImpl implements GoodsService {
    private TypeDao typeDao = new TypeDaoImpl();
    private Scanner scanner = new Scanner(System.in);
    private GoodsDao goodsDao = new GoodsDaoImpl();

    @Override
    public void add() {
        System.out.println("请输入需要添加的商品种类编号:【全部类型信息如下:】");
        typeDao.selectAll().forEach(System.out::println);
        int i = scanner.nextInt();
        Type type = typeDao.selectType(i);
        if (type == null) {
            System.out.println("没有这个类型!");
            return;
        }
        Goods goods = new Goods();
        goods.setTypeId(i);
        System.out.println("请输入商品名称");
        goods.setGdName(scanner.next());
        System.out.println("请输入商品价格");
        goods.setGdPrice(BigDecimal.valueOf(scanner.nextDouble()));
        System.out.println("请输入商品库存");
        goods.setGdStore(scanner.nextInt());
        int add = goodsDao.add(goods);
        if (add > 0) System.out.println("添加商品成功!");
        else System.out.println("添加商品失败!");
    }

    @Override
    public void delete() {
        System.out.println("请输入需要删除的商品编号:");
        int id = scanner.nextInt();
        Goods select = goodsDao.select(id);
        if (select == null) {
            System.out.println("输入编号对应商品不存在!");
            return;
        }
        int delete = goodsDao.delete(id);
        if (delete > 0) System.out.println("删除商品成功!");
        else System.out.println("删除商品失败!");
    }

    @Override
    public void update() {
        System.out.println("请输入需要修改的商品编号:");
        int id = scanner.nextInt();
        Goods select = goodsDao.select(id);
        if (select == null) {
            System.out.println("商品不存在");
            return;
        }
        System.out.println("请输入修改后的类型编号:");
        typeDao.selectAll().forEach(type -> System.out.println("类型编号:" + type.getTypeId() + "\t对应名称:" + type.getTypeName()));
        Type type = typeDao.selectType(scanner.nextInt());
        if (type == null) {
            System.out.println("输入编号对应类型不存在");
            return;
        }
        select.setTypeId(type.getTypeId());
        System.out.println("请输入修改后的商品名称:");
        select.setGdName(scanner.next());
        System.out.println("请输入修改后的商品价格:");
        select.setGdPrice(scanner.nextBigDecimal());
        System.out.println("请输入修改后的商品库存:");
        select.setGdStore(scanner.nextInt());
        int update = goodsDao.update(select);
        if (update > 0) System.out.println("修改成功!");
        else System.out.println("修改失败!");
    }

    @Override
    public void select() {
        goodsDao.select().forEach(System.out::println);
    }

    @Override
    public void showToUser() {
        System.out.println("商品编号\t商品名称\t商品价格");
        Page page = new Page();
        page.setContentSum(goodsDao.count());
        page.setCount(8);
        page.setAllPage();
        for (Integer i = 0; i < page.getAllPage(); ) {
            page.setPage(i);
            System.out.println("************第" + (i + 1) + "页*************");
            goodsDao.selectByPage(page).forEach(System.out::println);
            System.out.println("<上一页      ||        下一页>");
            String next = scanner.next();
            switch (next) {
                case "<":
                    if (i != 0) i--;
                    else System.out.println("当前已是第一页");
                    break;
                case ">":
                    if (i != page.getAllPage()) i++;
                    else System.out.println("当前已是第最后一页");
                    break;
                case "||":
                    return;
            }
        }
    }


}
public interface CartService {
    void add(UserInfo userInfo);

    void delete(UserInfo userInfo);

    void update(UserInfo userInfo);

    void select(UserInfo userInfo);

    void summary(UserInfo userInfo);

    void showScore(UserInfo userInfo);

    void purchase(UserInfo userInfo);
}
public class CartServiceImpl implements CartService {
    private CartDao cartDao = new CartDaoImpl();
    private Scanner scanner = new Scanner(System.in);
    private GoodsDao goodsDao = new GoodsDaoImpl();
    private OrderDao orderDao = new OrderDaoImpl();
    private UserDao userDao = new UserDaoImpl();

    @Override
    public void add(UserInfo userInfo) {
        System.out.println("请输入想要加购的商品编号:");
        int i = scanner.nextInt();
        Goods select = goodsDao.select(i);
        if (select == null || select.getGdStore() == 0) {
            System.out.println("商品已不存在!");
            return;
        }
        System.out.println("请输入想要购买的数量:");
        int num = scanner.nextInt();
        if (num > goodsDao.select(i).getGdStore()) {
            System.out.println("库存不足!");
            return;
        }
        Cart cart = cartDao.selectSingle(i, userInfo.getUserId());
        if (cart != null) {
            int update = cartDao.update(i, cart.getGdNum() + num, userInfo.getUserId());
            if (update > 0) System.out.println("加入购物车成功!");
            else System.out.println("加购失败!");
        } else {
            int add = cartDao.add(userInfo, select, num);
            if (add > 0) System.out.println("加入购物车成功!");
            else System.out.println("加购失败!");
        }
    }

    @Override
    public void delete(UserInfo userInfo) {
        System.out.println("请输入需要删除的商品编号:");
        int id = scanner.nextInt();
        Cart cart = cartDao.selectSingle(id, userInfo.getUserId());
        if (cart == null) {
            System.out.println("删除失败!商品未加入购物车!");
            return;
        }
        int delete = cartDao.delete(cart.getGdId(), cart.getUserId());
        if (delete > 0) System.out.println("删除成功!");
        else System.out.println("删除失败!");
    }

    @Override
    public void update(UserInfo userInfo) {
        System.out.println("请输入需要修改的商品编号:");
        int id = scanner.nextInt();
        Cart cart = cartDao.selectSingle(id, userInfo.getUserId());
        if (cart == null) {
            System.out.println("修改失败!商品未加入购物车!");
            return;
        }
        System.out.println("请输入需要修改的商品数量:");
        int num = scanner.nextInt();
        int update = cartDao.update(id, num, userInfo.getUserId());
        if (update > 0) System.out.println("修改成功!");
        else System.out.println("修改失败!");
    }

    @Override
    public void select(UserInfo userInfo) {
        System.out.println("购物车商品如下:");
        cartDao.select(userInfo.getUserId()).forEach(System.out::println);
    }

    @Override
    public void summary(UserInfo userInfo) {
        BigDecimal summary = cartDao.summary(userInfo.getUserId());
        if (summary == null) {
            System.out.println("购物车还没有商品!");
            return;
        }
        System.out.println("你需要结算的金额为:" + summary);
        String answer = null;
        if (userInfo.getUserBalance() == null) {
            System.out.println("余额不足,请先充值!");
            return;
        }
        if (userInfo.getUserVip() != null) {
            System.out.println("会员享有八折优惠,请问是否使用会员卡支付?【y/n】");
            answer = scanner.next().toLowerCase();
        }
        Connection connection = SqlUtil.getConnections();
        try {
            connection.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        List<Cart> select1 = cartDao.select(userInfo.getUserId());
        if ("y".equals(answer)) {
            if (userInfo.getUserBalance().compareTo(summary.multiply(BigDecimal.valueOf(0.8))) == 1) {
                int index = 0;
                for (Cart cart : select1) {
                    Integer gdId = cart.getGdId();
                    Goods select = goodsDao.select(gdId);
                    int num = select.getGdStore() - cart.getGdNum();
                    int i = goodsDao.updateStore(connection, gdId, num);
                    if (i > 0) {
                        index++;
                    } else {
                        try {
                            DbUtils.rollback(connection);
                        } catch (SQLException e) {
                            System.out.println("修改库存失败");
                        }
                    }
                }
                if (index == select1.size()) {
                    userInfo.setUserBalance(userInfo.getUserBalance().subtract(summary.multiply(BigDecimal.valueOf(0.8))));
                    if (userInfo.getVipScore() != null)
                        userInfo.setVipScore(userInfo.getVipScore() + summary.intValue());
                    else userInfo.setVipScore(summary.intValue());
                    userDao.updateVip(userInfo);
                    System.out.println("支付成功!您的会员积分为:" + userInfo.getVipScore());
                    for (Cart cart : select1) {
                        orderDao.add(connection, cart);
                        cartDao.delete(cart.getGdId(), userInfo.getUserId());
                    }
                    try {
                        DbUtils.commitAndClose(connection);
                    } catch (SQLException e) {
                        System.out.println("提交订单失败!");
                        e.printStackTrace();
                    }
                } else {
                    try {
                        DbUtils.rollback(connection);
                    } catch (SQLException e) {
                        System.out.println("订单数目不对");
                    }
                }
            } else {
                try {
                    DbUtils.rollback(connection);
                } catch (SQLException e) {
                    System.out.println("会员卡余额不足!请先充值!");
                }
            }
        } else {
            int index = 0;
            for (Cart cart : select1) {
                Integer gdId = cart.getGdId();
                Goods select = goodsDao.select(gdId);
                int num = select.getGdStore() - cart.getGdNum();
                int i = goodsDao.updateStore(connection, gdId, num);
                if (i > 0) {
                    index++;
                } else {
                    try {
                        DbUtils.rollback(connection);
                    } catch (SQLException e) {
                        System.out.println("修改库存失败");
                    }
                }
            }
            if (index == select1.size()) {
                System.out.println("需现金支付:" + summary);
                if (userInfo.getUserBalance().compareTo(summary) == 1) {
                    userInfo.setUserBalance(userInfo.getUserBalance().subtract(summary));
                    userDao.updateVip(userInfo);
                    System.out.println("支付成功!");
                    for (Cart cart : select1) {
                        orderDao.add(connection, cart);
                        cartDao.delete(cart.getGdId(), userInfo.getUserId());
                    }
                    try {
                        DbUtils.commitAndClose(connection);
                    } catch (SQLException e) {
                        System.out.println("现金支付失败!");
                    }
                } else {
                    try {
                        DbUtils.rollback(connection);
                    } catch (SQLException e) {
                        System.out.println("余额不足!");
                    }
                }
            }else {
                try {
                    DbUtils.rollback(connection);
                } catch (SQLException e) {
                    System.out.println("现金支付失败!");
                }
            }
        }

    }

    @Override
    public void showScore(UserInfo userInfo) {
        UserInfo userInfo1 = userDao.selectUser(userInfo.getUserId());
        if (userInfo1 == null || userInfo1.getUserVip() == null) {
            System.out.println("您还不是会员!");
            return;
        }
        System.out.println(userDao.score(userInfo.getUserId()));
    }

    @Override
    public void purchase(UserInfo userInfo) {
        userInfo = userDao.selectUser(userInfo.getUserId());
        if (userInfo == null || userInfo.getUserVip() == null) {
            System.out.println("您还不是会员!");
            return;
        }
        System.out.println("积分换购如下:");
        System.out.println("1、5分:一包面巾纸");
        System.out.println("2、10分:一个棒棒糖");
        System.out.println("3、15分:一根牙刷");
        System.out.println("4、20分:一包餐巾纸");
        System.out.println("5、50分:三元无门槛代金券");
        System.out.println("6、150分:十五元无门槛代金券");
        System.out.println("请选择:");
        int i = scanner.nextInt();
        if (userInfo.getVipScore() == null) {
            System.out.println("积分不足!");
            return;
        }
        Integer vipScore = userInfo.getVipScore();
        switch (i) {
            case 1:
                if (vipScore < 5) {
                    System.out.println("积分不足!");
                    return;
                } else userInfo.setVipScore(userInfo.getVipScore() - 5);
                break;
            case 2:
                if (vipScore < 10) {
                    System.out.println("积分不足!");
                    return;
                } else userInfo.setVipScore(userInfo.getVipScore() - 10);
                break;
            case 3:
                if (vipScore < 15) {
                    System.out.println("积分不足!");
                    return;
                } else userInfo.setVipScore(userInfo.getVipScore() - 15);
                break;
            case 4:
                if (vipScore < 20) {
                    System.out.println("积分不足!");
                    return;
                } else userInfo.setVipScore(userInfo.getVipScore() - 20);
                break;
            case 5:
                if (vipScore < 50) {
                    System.out.println("积分不足!");
                    return;
                } else userInfo.setVipScore(userInfo.getVipScore() - 50);
                break;
            case 6:
                if (vipScore < 150) {
                    System.out.println("积分不足!");
                    return;
                } else userInfo.setVipScore(userInfo.getVipScore() - 150);
                break;
            default:
                System.out.println("输入错误!");
        }
        int i1 = userDao.updateVip(userInfo);
        if (i1 > 0) System.out.println("换购成功!");
        else System.out.println("换购失败!");
    }
}

总结:int类型在数据库进行聚合运算且返回map或list时需要用BigDecimal接收,count用Long接收,注意数据库实体类与表格每一列属性的类型要对应。

标签:Java,项目,int,System,超市,println,return,public,out
From: https://www.cnblogs.com/Liku-java/p/17000740.html

相关文章