Skip to content

Instantly share code, notes, and snippets.

@tony1223
Created November 15, 2010 10:07
Show Gist options
  • Save tony1223/700236 to your computer and use it in GitHub Desktop.
Save tony1223/700236 to your computer and use it in GitHub Desktop.
package test.combobox;
import java.util.ArrayList;
public class Department {
private int id;
private String name;
public ArrayList<Employee> list;
public Department(){
list=new ArrayList<Employee> ();
}
public ArrayList<Employee> getEmployees() {
return list;
}
public void addEmployees(Employee emp) {
this.list.add(emp);
}
public void removeEmployees(Employee emp) {
this.list.remove(emp);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package test.combobox;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class DepartmentDao {
public List<Department> getDepartments() {
HashMap<Integer, Department> depMap = new HashMap<Integer, Department>(); // 待回傳部門LIST
String url = "jdbc:mysql://localhost:3306/test"; // 依環境變動
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url,"userid","passwd");
Statement stDep = conn.createStatement();
// loop1 SEARCH 部門資料
ResultSet rsDep = stDep.executeQuery("Select id , name From dep");
// 先撈部門再撈員工,避免過多的sql query,反正橫豎都是要建map。
while (rsDep.next()) {
Department depbean = new Department();
depbean.setId(rsDep.getInt("id"));
depbean.setName(rsDep.getString("name"));
// 加入 BEAN 物件至 DepList
depMap.put(depbean.getId(), depbean);
}
// 用完養成好習慣順手close
rsDep.close();
// loop1 SEARCH 員工資料 如果說要查詢的部門只有一部分的話,
// 也可以把前一個map的key兜過來寫sql,但在這裡我先不考慮這個。
Statement stEmp = conn.createStatement();
ResultSet rsEmp = stEmp.executeQuery("Select id , name,depId From emp ");
while (rsEmp.next()) {
Employee empBean = new Employee();
empBean.setId(rsEmp.getString("id"));
empBean.setName(rsEmp.getString("name"));
// 加入 BEAN 物件至 DepList
if (depMap.containsKey(rsEmp.getInt("depId"))) {
Department depart = (Department) depMap.get(rsEmp.getInt("depId"));
depart.addEmployees(empBean);
}
}
// 用完養成好習慣順手close
rsEmp.close();
conn.close();
return new ArrayList<Department>(depMap.values());
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}
package test.combobox;
public class Employee {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment