显示多个表

时间:2016-03-21 14:26:04

标签: jsf jsf-2 primefaces

我是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;

}

我的DAO

@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 个答案:

答案 0 :(得分: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>
...