• 随机获得MySQL数据库中100条数据方法 驾照题库项目 MVC架构 biz业务层的实现类 根据考试类型rand或order通过dao数据访问层接口得到数据库中100或全部数据


    package com.swift.jztk.biz;
    
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Random;
    
    import com.google.gson.Gson;
    import com.swift.jztk.bean.Result;
    import com.swift.jztk.bean.Root;
    import com.swift.jztk.dao.IQuestionDao;
    import com.swift.jztk.dao.QuestionDaoImpl;
    
    public class QuestionBizImpl implements IQuestionBiz {
        IQuestionDao dao = new QuestionDaoImpl();
    
        @Override
        public String getQuestions(String testType) {
            List<Result> list = null;
            if (testType.equals("rand")) {
                HashSet<Integer> set = new HashSet<Integer>();//生成一个哈希集合,用于存放随机数
                Random ran = new Random();
                for (;;) {//无限循环
                    int n = ran.nextInt(200) + 1;// 1~200间的随机整数,不加1是0到199
                    set.add(n);// 随机数放到 整数类型的哈希集合中,保证没有相同的整数
                    if (set.size() == 100) {
                        break;
                    }
                }
                Iterator<Integer> it = set.iterator();//迭代器,用于获取集合中各条内容
                while (it.hasNext()) {
                    int id = it.next();
                    Result result = dao.getResultById(id);
                    list.add(result);//加入对象列表集合
                    Collections.sort(list, new Comparator<Result>() {// 比较器 匿名内部类
    
                        @Override
                        public int compare(Result o1, Result o2) {
                            int id1 = o1.getId();
                            int id2 = o2.getId();
                            return id1 - id2;// 按照id大小从小到大排序
                        }
                    });
                }
    
            } else if (testType.equals("order")) {
                list = dao.getAll();//MVC架构,数据访问层用接口进行连接,得到数据库中全部数据
            }
            String json=listToJson(list);
            return json;
        }
        //把得到的List<Result>对象列表集合转换成字符串
        public String listToJson(List<Result> list) {
            Root root = new Root();
            root.setResult(list);
            root.setStatusCode("000000");
            root.setDesc("请求成功");//json实体类对象赋值
            Gson gson = new Gson();
            String json = gson.toJson(root);//json实体类对象用Gson解析成字符串
            return json;
        }
    
    }
  • 相关阅读:
    BZOJ 2034 【2009国家集训队】 最大收益
    vijos P1780 【NOIP2012】 开车旅行
    BZOJ 2115 【WC2011】 Xor
    BZOJ 3631 【JLOI2014】 松鼠的新家
    BZOJ 4717 改装
    BZOJ 2957 楼房重建
    BZOJ 4034 【HAOI2015】 T2
    BZOJ 1834 【ZJOI2010】 network 网络扩容
    BZOJ 2440 【中山市选2011】 完全平方数
    BZOJ 2733 【HNOI2012】 永无乡
  • 原文地址:https://www.cnblogs.com/qingyundian/p/7616003.html
Copyright © 2020-2023  润新知