使用hibernate和spring MVC从DB中选择时保留顺序

时间:2016-04-09 12:19:12

标签: java json spring spring-mvc jsonobject

伙计们我有2张桌子"员工"它有EMPID,EMPAGE,ADDRESS,SALARY,EMPNAME,department_id(外键参考表格#34;部门")和"部门"有department_id,name的表...我做了一个HQL查询来选择部门

public List<Department> listDepartment() {
    List<Department> deps = sessionFactory.getCurrentSession()
                           .createCriteria(Department.class).list();
    return deps;
}

并循环遍历表以构造要由ajax请求调用的JSON对象

    public void listDepartment(HttpServletResponse response) throws IOException, JSONException {
        PrintWriter out = response.getWriter();
        JSONObject obj1 = new JSONObject();
        JSONObject obj = new JSONObject();

        for(int index = 0; index<listDepartment().size(); index++){
            obj1.put("Department ID "+index,listDepartment().get(index).getDepId());
            obj1.put("Department Name "+index,listDepartment().get(index).getDepName());

            JSONArray array = new JSONArray();
            for(Employee l : listDepartment().get(index).getEmployees()){
                array.add(l.getEmpId()+" "+l.getEmpAge()+" "+l.getSalary()+" "+l.getEmpAddress());
                obj1.put("Employees "+index, array);
            }

        }

        System.out.println(obj1);
        obj.put("MyListDep", obj1);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        out.write(obj.toString());
        out.close();

但我找到了&#39; obj1&#39;就像这样

  

{&#34;部门名称0&#34;:&#34;名称1&#34;,&#34;部门名称1&#34;:&#34;名称2&#34;,&#34;部门   名称2&#34;:&#34;名称3&#34;,&#34;部门名称3&#34;:&#34;名称4&#34;,&#34;部门名称   4&#34;:&#34; name5&#34;,&#34;员工0&#34;:[&#34; 1 10薪水1地址1&#34;,&#34; 2 20薪水2   地址2&#34;],&#34;部门ID 0&#34;:1,&#34;部门ID 1&#34;:2,&#34;员工2&#34;:[&#34; 5   50 salary5 address5&#34;,&#34; 6 60 salary6 address6&#34;],&#34;员工1&#34;:[&#34; 3 30   salary3 address3&#34;,&#34; 4 40 salary4 address4&#34;],&#34; Department ID   2&#34;:3,&#34;部门ID 3&#34;:4,&#34;部门ID 4&#34;:5,&#34;员工4&#34;:[&#34; 9 90   salary9 address9&#34;,&#34; 10 100 salary10 address10&#34;],&#34;员工3&#34;:[&#34; 7 70   salary7 address7&#34;,&#34; 8 80 salary8 address8&#34;]}

不保留订单..所以我希望它打印索引0的所有信息,然后索引1然后......等 任何帮助??

0 个答案:

没有答案
相关问题