java入门--------JDBC2(尚马day24) week6(2)

3. 分页查询

dao

@Override
public int findUserInfoCount() {
    connection = DBUtil.getConn();
    sql = "select count(*) from tb_userinfo";
    int totalRow = 0;
    try {
        ps = connection.prepareStatement(sql);
        rs = ps.executeQuery();
        if (rs.next()) {
            totalRow = rs.getInt(1);
        }
    } catch (SQLException throwables) {
        throwables.printStackTrace();
    }
    return totalRow;
}

@Override
public List findUserInfoByPage(int page, int size) {
    connection = DBUtil.getConn();
    sql = "select * from tb_userinfo limit ?,?";
    List userInfoList = new ArrayList<>(10);
    try {
        ps = connection.prepareStatement(sql);
        ps.setInt(1, (page - 1) * size);
        ps.setInt(2, size);
        rs = ps.executeQuery();
        while (rs.next()) {
            userInfoList.add(userInfoInstance(rs));
        }
    } catch (SQLException throwables) {
        throwables.printStackTrace();
    } finally {
        DBUtil.close(connection, ps, rs);
    }
    return userInfoList;
}

测试类

public static void pageTest() {
​
    Scanner input = new Scanner(System.in);
    UserInfoDao userInfoDao = new UserInfoDaoImpl();
    final int size = 5;
    //表里面的总记录数
    int totalRow = userInfoDao.findUserInfoCount();
    //总页数
    int totalPage = totalRow / size;
    totalPage = (totalRow % size == 0) ? totalPage : totalPage + 1;
    System.out.println("目前数据一共有<<" + totalPage + ">>页");
    for (int i = 1; i <= totalPage; i++) {
        System.out.print(i + "\t");
    }
    System.out.println();
    // 1  2  3  4  5  6  7
    String str;
    do {
        System.out.println("请录入要查看的页数:");
        int page = input.nextInt();
        System.out.println("当前第<<" + page + ">>页的数据如下:");
        userInfoDao.findUserInfoByPage(page, size).forEach(System.out::println);
​
        System.out.println("是否继续查询?y/n");
        str = input.next();
    } while (Objects.equals("y", str));
}

private static void pageTest1() {
    Scanner input = new Scanner(System.in);
    UserInfoDao userInfoDao = new UserInfoDaoImpl();
    final int size = 5;
    //表里面的总记录数
    int totalRow = userInfoDao.findUserInfoCount();
    //总页数
    int totalPage = totalRow / size;
    totalPage = (totalRow % size == 0) ? totalPage : totalPage + 1;
​
    int page = 1;//一进来就应该展示第一页的数据
    userInfoDao.findUserInfoByPage(page, size).forEach(System.out::println);
    System.out.println("目前数据一共有<<" + totalPage + ">>页");
    String s;
    do {
        if (page != 1) {
            System.out.print("1.首页\t");
            System.out.print("2.上一页\t");
        }
        if (page != totalPage) {
            System.out.print("3.下一页\t");
            System.out.print("4.尾页");
        }
        System.out.println();
        System.out.println("请选择要执行的功能:");
        int choice = input.nextInt();
        switch (choice) {
            case 1:
                page = 1;
                break;
            case 2:
                page--;
                break;
            case 3:
                page++;
                break;
            case 4:
                page = totalPage;
                break;
        }
        System.out.println("当前第<<" + page + ">>页的数据如下:");
        userInfoDao.findUserInfoByPage(page, size).forEach(System.out::println);
        System.out.println("是否继续?y/n");
        s = input.next();
    } while (Objects.equals("y", s));
}

4.条件查询

java入门--------JDBC2(尚马day24) week6(2)_第1张图片 

@Override
    public List findUserInfoByParams(Map paramMap, int page, int size) {
        connection = DBUtil.getConn();
        StringBuilder builder = new StringBuilder("SELECT * FROM tb_userinfo ");
        List userInfoList = new ArrayList<>(10);
      if (!paramMap.isEmpty()) {
            builder.append(" WHERE ");
            //SELECT * FROM tb_userinfo WHERE name LIKE '%1%' OR gender like '%女%'
            paramMap.forEach((key, value) -> {
                builder.append(key).append(" like ").append(" ? ").append(" OR ");
            });
            //将最后一个OR删除
            //System.out.println(builder);
            builder.delete(builder.lastIndexOf("OR"), builder.length());
            //sql = builder.substring(0,builder.lastIndexOf("OR")).toString();
            //System.out.println(sql);
        }
        
        builder.append(" limit ?,?");
        System.out.println(builder);
        try {
            ps = connection.prepareStatement(builder.toString());
           int index = 1;
        if (!paramMap.isEmpty()) {
            Set> entrySet = paramMap.entrySet();
            for (Map.Entry entry : entrySet) {
                ps.setObject(index++, "%" + entry.getValue() + "%");
            }
        }
            
            ps.setInt(index++, (page - 1) * size);
            ps.setInt(index, size);
            rs = ps.executeQuery();
            while (rs.next()) {
                userInfoList.add(userInfoInstance(rs));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBUtil.close(connection, ps, rs);
        }
        return userInfoList;
    }
​

简化之后

 @Override
    public List findUserInfoByParams(Map paramMap, int page, int size) {
        connection = DBUtil.getConn();
        StringBuilder builder = new StringBuilder("SELECT * FROM tb_userinfo ");
        List userInfoList = new ArrayList<>(10);
        appendSql(builder, paramMap);
        builder.append(" limit ?,?");
        System.out.println(builder);
        try {
            ps = connection.prepareStatement(builder.toString());
            int index = setParamValue(paramMap);
            ps.setInt(index++, (page - 1) * size);
            ps.setInt(index, size);
            rs = ps.executeQuery();
            while (rs.next()) {
                userInfoList.add(userInfoInstance(rs));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBUtil.close(connection, ps, rs);
        }
        return userInfoList;
    }
public void appendSql(StringBuilder builder, Map paramMap) {
        if (!paramMap.isEmpty()) {
            builder.append(" WHERE ");
            //SELECT * FROM tb_userinfo WHERE name LIKE '%1%' OR gender like '%女%'
            paramMap.forEach((key, value) -> {
                builder.append(key).append(" like ").append(" ? ").append(" OR ");
            });
            //将最后一个OR删除
            //System.out.println(builder);
            builder.delete(builder.lastIndexOf("OR"), builder.length());
            //sql = builder.substring(0,builder.lastIndexOf("OR")).toString();
            //System.out.println(sql);
        }
    }
​
    public int setParamValue(Map paramMap) throws SQLException {
        int index = 1;
        if (!paramMap.isEmpty()) {
            Set> entrySet = paramMap.entrySet();
            for (Map.Entry entry : entrySet) {
                ps.setObject(index++, "%" + entry.getValue() + "%");
            }
        }
        return index;
    }

条件查询获得记录数

@Override
public int findUserInfoCount(Map paramMap) {
​
    connection = DBUtil.getConn();
    StringBuilder builder = new StringBuilder("select count(*) from tb_userinfo ");
    appendSql(builder, paramMap);
    System.out.println(builder);
    int totalRow = 0;
    try {
        ps = connection.prepareStatement(builder.toString());
        setParamValue(paramMap);
        rs = ps.executeQuery();
        if (rs.next()) {
            totalRow = rs.getInt(1);
        }
    } catch (SQLException throwables) {
        throwables.printStackTrace();
    }
    return totalRow;
}

测试

private static void findByParams() {
    //假设自定义条件
    UserInfoDao userInfoDao = new UserInfoDaoImpl();
    Map map = new LinkedHashMap<>(16);
    map.put("name", "1");
    map.put("gender", "女");
    int page = 1;
    int size = 5;
    System.out.println("总记录数:" + userInfoDao.findUserInfoCount(map));
    //       System.out.println(userInfoDao.findUserInfoByParams(map,page,size).size());
    userInfoDao.findUserInfoByParams(map, page, size).forEach(System.out::println);
}

5. 关联查询

-- 查询指定用户购物车里面的商品详情
-- 查询用户购买的商品
-- 查询指定用户购物车里面的购物项的详细信息
​
SELECT
 u.id,u.`name`,u.balance,c.total_money,ci.buy_num,ci.money,p.prod_name,p.prod_price,p.prod_image
FROM
tb_userinfo AS u,tb_cart AS c, tb_cart_item AS ci , tb_product AS p
 WHERE u.id=? AND u.id=c.uid AND c.id=ci.cid AND ci.pid=p.id;

1. 扩展类VO

@Setter
@Getter
@ToString
public class UserInfoVO {
​
    private Integer id;
    private String name;
    private BigDecimal balance;
    private BigDecimal totalMoney;
    private Integer buyNum;
    private BigDecimal money;
    private String prodName;
    private BigDecimal prodPrice;
    private String prodImage;
​
​
}

@Override
    public List findUserInfoAndProd(int uid) {
        connection = DBUtil.getConn();
        sql = "SELECT\n" +
                " u.id,u.`name`,u.balance,c.total_money,ci.buy_num,ci.money,p.prod_name,p.prod_price,p.prod_image\n" +
                "FROM\n" +
                "tb_userinfo AS u,tb_cart AS c, tb_cart_item AS ci , tb_product AS p\n" +
                " WHERE u.id=? AND u.id=c.uid AND c.id=ci.cid AND ci.pid=p.id";
        List userInfoVOS = new ArrayList<>(10);
        try {
            ps = connection.prepareStatement(sql);
            ps.setInt(1, uid);
​
            rs = ps.executeQuery();
            while (rs.next()) {
                userInfoVOS.add(getUserInfoVo(rs));
            }
​
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBUtil.close(connection, ps, rs);
        }
        return userInfoVOS;
    }
​
    private UserInfoVO getUserInfoVo(ResultSet rs) throws SQLException {
        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setId(rs.getInt("id"));
        userInfoVO.setName(rs.getString("name"));
        userInfoVO.setBalance(rs.getBigDecimal("balance"));
        userInfoVO.setBuyNum(rs.getInt("buy_num"));
        userInfoVO.setTotalMoney(rs.getBigDecimal("total_money"));
        userInfoVO.setMoney(rs.getBigDecimal("money"));
        userInfoVO.setProdName(rs.getString("prod_name"));
        userInfoVO.setProdImage(rs.getString("prod_image"));
        userInfoVO.setProdPrice(rs.getBigDecimal("prod_price"));
        return userInfoVO;
    }
​

2. 将一行记录转成一个map

 List> findUserInfoAndProd1(int uid);
​
​
 public List> findUserInfoAndProd1(int uid) {
        connection = DBUtil.getConn();
        sql = "SELECT\n" +
                " u.id,u.`name`,u.balance,c.total_money,ci.buy_num,ci.money,p.prod_name,p.prod_price,p.prod_image\n" +
                "FROM\n" +
                "tb_userinfo AS u,tb_cart AS c, tb_cart_item AS ci , tb_product AS p\n" +
                " WHERE u.id=? AND u.id=c.uid AND c.id=ci.cid AND ci.pid=p.id";
        List> userInfoVOS = new ArrayList<>(10);
        try {
            ps = connection.prepareStatement(sql);
            ps.setInt(1, uid);
            rs = ps.executeQuery();
            while (rs.next()) {
                Map rowMap = new LinkedHashMap<>(16);
                rowMap.put("id",rs.getInt("id"));
                rowMap.put("name",rs.getString("name"));
                rowMap.put("balance",rs.getBigDecimal("balance"));
                rowMap.put("buyNum",rs.getInt("buy_num"));
                rowMap.put("totalMoney",rs.getBigDecimal("total_money"));
                rowMap.put("money",rs.getBigDecimal("money"));
                rowMap.put("prodName",rs.getString("prod_name"));
                rowMap.put("prodImage",rs.getString("prod_image"));
                rowMap.put("prodPrice",rs.getBigDecimal("prod_price"));
                userInfoVOS.add(rowMap);
            }
​
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBUtil.close(connection, ps, rs);
        }
        return userInfoVOS;
    }

问题:

java入门--------JDBC2(尚马day24) week6(2)_第2张图片

3. 采取表与表(类与类)

一个用户有1个购物车----> 一对一
一个购物车有多个购物----->一对多
一个购物项有1个商品----> 一对一
​
要将这些表的关系  在类中进行体现:
@Override
public UserInfo findUserInfoAndProd2(int uid) {
    connection = DBUtil.getConn();
    sql = "SELECT\n" +
        " u.id,u.`name`,u.balance,c.total_money,ci.buy_num,ci.money,p.prod_name,p.prod_price,p.prod_image\n" +
        "FROM\n" +
        "tb_userinfo AS u,tb_cart AS c, tb_cart_item AS ci , tb_product AS p\n" +
        " WHERE u.id=? AND u.id=c.uid AND c.id=ci.cid AND ci.pid=p.id";
​
    UserInfo userInfo = new UserInfo();
    try {
        ps = connection.prepareStatement(sql);
        ps.setInt(1, uid);
        rs = ps.executeQuery();
        Cart cart = new Cart();
        List cartItems = new ArrayList<>(10);
        while (rs.next()) {
            userInfo.setId(rs.getInt("id"));
            userInfo.setName(rs.getString("name"));
            userInfo.setBalance(rs.getBigDecimal("balance"));
            //解决关系: 对属性赋值
            cart.setTotalMoney(rs.getBigDecimal("total_money"));
​
            CartItem item = new CartItem();
            item.setBuyNum(rs.getInt("buy_num"));
            item.setMoney(rs.getBigDecimal("money"));
​
            Product product = new Product();
            product.setProdName(rs.getString("prod_name"));
            product.setProdPrice(rs.getBigDecimal("prod_price"));
            product.setProdImage(rs.getString("prod_image"));
​
            item.setProduct(product);
            cartItems.add(item);
        }
        cart.setCartItemList(cartItems);
        userInfo.setCart(cart);
​
    } catch (SQLException throwables) {
        throwables.printStackTrace();
    } finally {
        DBUtil.close(connection, ps, rs);
    }
    return userInfo;
}

4. service

java入门--------JDBC2(尚马day24) week6(2)_第3张图片

 

新增用户: 密码密文存储 上传之后的图片存储服务器路径

    @Override
    public int addUserInfo(UserInfo userInfo) {
        connection = DBUtil.getConn();
        sql = "insert into tb_userinfo (name, gender, phone, age, balance,password, birthday,user_image) VALUES (?,?,?,?,?,?,?,?)";
        int result = 0;
        try {
            ps = connection.prepareStatement(sql);//参数化的sql语句在ps对象
            ps.setString(1, userInfo.getName());
            ps.setString(2, userInfo.getGender());
            ps.setString(3, userInfo.getPhone());
            ps.setInt(4, userInfo.getAge());
            ps.setBigDecimal(5, userInfo.getBalance());
            ps.setString(6, userInfo.getPassword());
            ps.setObject(7, userInfo.getBirthday());
            ps.setString(8,userInfo.getUserImage());
            result = ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBUtil.close(connection, ps, rs);
        }
        return result;
    }
​

public class UserServiceImpl implements UserService {
​
    private static UserInfoDao userInfoDao = new UserInfoDaoImpl();
​
    //硬业务
    @Override
    public int addUserInfo(UserInfo userInfo) {
        //对数据进行处理
        //密码加密
        userInfo.setPassword(MD5Util.md5(userInfo.getPassword()));
        try {
            //文件上传
            userInfo.setUserImage(FileUtil.upload(userInfo.getUserImage()));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return userInfoDao.addUserInfo(userInfo);
    }
}

5. 自增id

6. 事务

7. 反射

你可能感兴趣的:(尚马java课堂笔记,java,linq,开发语言)