0

当类有另一个类字段时,如何在java中列出类元素?它看起来像这样:

public class Grad {

private int grad_id;
private **Drzava drzava**;
private String naziv;
private boolean aktivan;
private Set<Korisnik> korisnici = new HashSet<Korisnik>(0);
public Drzava getDrzava() {
    return drzava;
}
public void setDrzava(Drzava drzava) {
    this.drzava = drzava;
}
        public List<Grad> getAllGrad() {

    List<Grad> gradovi = new ArrayList<Grad>();
    try {
        Statement statement = DBConnection.getConnection().createStatement();
        ResultSet rs = statement.executeQuery("select * from grad;");
        while (rs.next()) {
            Grad grad = new Grad();
            grad.setGrad_id(rs.getInt("grad_id"));
        **grad.setDrzava( (Drzava)rs.getObject("drzava"));**/**(HERE IS A     PROBLEM!!)**/
            grad.setNaziv(rs.getString("naziv"));
            grad.setAktivan(rs.getBoolean("aktivan"));
            gradovi.add(grad);
        }




else if (action.equalsIgnoreCase("listGrad")){
        forward = LIST_GRAD;
        request.setAttribute("gradovi", dao.getAllGrad());

这是在 jsp 页面中,我认为错误在 grad.drzava.naziv:

<c:forEach items="${gradovi}" var="grad">
            <tr>
                <td><c:out value="${grad.grad_id}"/></td>
                <td><c:out value="${grad.drzava.naziv}"/></td> 
                <td><c:out value="${grad.naziv}" /></td>
                <td><c:out value="${grad.aktivan}" /></td>

例外是:找不到 java sql SQLException 列“drzava”。

非常感谢您的回答:))

4

1 回答 1

0
ResultSet rs = statement.executeQuery("select * from grad;");

这将返回“Drzava”表的主键,它是 grad 表中的外键。因此,要获取 Drzava 类对象,您需要再次执行另一个查询,例如:

ResultSet rs = statement.executeQuery("select * from drzava;");

然后将生成的 drzava 类对象分配给 grad 类变量。

于 2013-05-17T02:04:41.003 回答