当前位置: 代码迷 >> J2EE >> 多对多查询有关问题,
  详细解决方案

多对多查询有关问题,

热度:16   发布时间:2016-04-22 00:25:21.0
多对多查询问题,急
我想通过部门的id查询所有员工,部门与员工是多对多关系,上主要代码
Employee.java
Java code
@Entitypublic class Employee implements Serializable{    private Set<Department> departments = new HashSet<Department>();//所属部门    @ManyToMany(cascade=CascadeType.REFRESH, fetch=FetchType.EAGER)    @JoinTable(name="employee_department", joinColumns=@JoinColumn(name="username"),            inverseJoinColumns=@JoinColumn(name="department_id"))    public Set<Department> getDepartments() {        return departments;    }    public void setDepartments(Set<Department> departments) {        this.departments = departments;    }        public void addDepartment(Department department){        if(!this.departments.contains(department)) this.departments.add(department);    }    public void removeDepartment(Department department){        if(this.departments.contains(department)) this.departments.remove(department);    }}

Department.java
Java code
@Entitypublic class Department implements Serializable{    private Set<Employee> employees = new HashSet<Employee>();//员工        @ManyToMany(mappedBy="departments", cascade=CascadeType.REFRESH)    public Set<Employee> getEmployees() {        return employees;    }    public void setEmployees(Set<Employee> employees) {        this.employees = employees;    }

EployeeAction.java
Java code
    public String list(){        StringBuffer hql = new StringBuffer();        hql.append("o.visible=?");        List pr = new ArrayList();        pr.add(true);        if("true".equals(ef.getQuery())) {             if(ef.getDepartment()!=null && !"".equals(ef.getDepartment())) {                System.out.println(ef.getDepartment());                hql.append(" and o.departments in (select d from Department d where id =?)");//问题是这句hql怎么写                pr.add(ef.getDepartment());//ef.getDepartment()接收回来的部门id,初始化问号            }        }        pl = new PageList<Employee>(Integer.valueOf(ReadMessageConnection.getMessageConnection("employeePageSize")), ef.getFirstIndex());        pl.setQueryResult(employeeManager.getScrollData(Employee.class, pl.getFirstindex(), pl                .getMaxresult(), hql.toString(), pr.toArray()));        return "list";    }

现在我是打开员工表的,不是打开部门表,我想通过接收回来的部门id在员工表下把所有的员工都显示出来,大神来啊

------解决方案--------------------
where的前面只有“select e from Employee e”,如果限定死只能这么写,没有JOIN,恐怕不可能实现。
  相关解决方案