2016-03-21 117 views
1

我是JSF/Java和关系数据库查询的新手。显示来自多个表的数据

我想在一个数据表中显示来自两个表的数据。

我有两个表tblUser和tblCity。

对于这些表我有两个模型用户和城市。 还有一个UserDAO和一个UserController。

我想知道如何从tblUser中选择用户数据并从tblCity中选择城市数据并在我的视图中显示它们。采用MVC风格。

型号:

public class User{ 
    private Integer user_id; 
    private String user_name; 
    private Integer City_id; 

    //getter and setter 
    ... 
} 


public class City{ 
    private Integer city_id; 
    private String city_name; 

    //getter and setter 
    ... 
} 

我的控制器

@ManagedBean 
@SessionScoped 
public List<User> showUser(){ 

    List<User> users = new ArrayList<>(); 
    users= userDAO.showUserList(); 
    return users; 

} 

吾道

@ManagedBean 
@RequestScoped 
public class userDAO{ 

    /** 
    * Creates a new instance of patientDAO 
    */ 
    private final connectToDB con = new connectToDB(); 

    public userDAO() { 
    } 
    public List<User> showUserList() { 

      Connection dbConnection = null; 

      dbConnection = con.getDBConnection(); 

      PreparedStatement pstmt = dbConnection 
        .prepareStatement("select a.user_id, a.user_name, b.city_name" 
          + " from users a, cities b WHERE a.city_id = b.city_id"); 
      ResultSet rs = pstmt.executeQuery(); 

      List<User> users = new ArrayList<>(); 
      List<City> cities = new ArrayList<>(); 

      while (rs.next()) { 

       User user = new User(); 
       City city = new City(); 

       user.setUser_Id(rs.getInt("user_id")); 
       user.setUser_Id(rs.getString("user_name")); 

       city.setCity_Name(rs.getInt("city_name"));  


       users.add(user); 
       cities.add(city); 
      } 
      // close resources 
      rs.close(); 
      pstmt.close(); 

      dbConnection.close(); 


      return users; 
     } 
} 

我查看

<p:dataTable id="userDT" var="user" value="#{userController.showUserList()}"> 
    <p:column width="200" headerText="User Name"> 
     <h:outputText value="#{user.user_name}" /> 
    </p:column> 

    <p:column width="200" headerText="City Name"> 
     <h:outputText value="#{...}" /> 
    </p:column> 
</p:dataTable> 

回答

1

假设一个User有一个City,您可以在city属性添加到User类:

public class User{ 
    ... 
    private City city; 

    public City getCity() { 
     return city; 
    } 

    public void setCity(City city) { 
     this.city = city; 
    } 
    ... 
} 

在你userDAO,在showUserList()方法的while循环结束时,把城市中的用户对象:

... 
while (rs.next()) { 
    User user = new User(); 
    City city = new City(); 

    user.setUser_Id(rs.getInt("user_id")); 
    user.setUser_Id(rs.getString("user_name")); 

    city.setCity_Name(rs.getInt("city_name"));  

    user.setCity(city); 

    users.add(user); 
} 
... 

showUserList()方法中的城市列表未在方法外使用,您可以将其删除。

最后,编辑这样的观点:

... 
<p:column width="200" headerText="City Name"> 
    <h:outputText value="#{user.city.city_name}" /> 
</p:column> 
... 
相关问题