一共有三个表<Table 1>, <Table 2> and <Table 3>
我的 SQL 是这样的:
"Select table1.col1, table1.col2, table1.col3, table2.col4, table2.col5, table2.col6,
table3.col7, table3.col8 from Table 1 as table1
LEFT JOIN Table 2 as table2 on (table1.col1 = table2.col4)
LEFT JOIN Table 3 as table3 on (table1.col1 = table3.col8)"
获取结果集的正常方法是:
public List getExportDataList() throws ClassNotFoundException, SQLException {
Connection connect = null;
String url = "jdbc:.....";
String username = "username ";
String password = "password ";
try {
connect = DriverManager.getConnection(url, username, password);
} catch (SQLException ex) {
System.out.println("in exec");
System.out.println(ex.getMessage());
}
List dataList = new ArrayList<>();
PreparedStatement pstmt = connect.prepareStatement(
THE SQL CODE SHOWN ABOVE
}
ResultSet rs = pstmt.executeQuery();
while(rs.next()){
Table1 table1 = new Table1();
table1.setCOL1(rs.getString("col1"));
table1.setCOL2(rs.getString("col2"));
dataList.add(table1);
}
rs.close();
pstmt.close();
connect.close();
return dataList;
}
这样“dataList”就可以用来显示Primefaces dataTable中的数据了。
但是,这种方式只能将Table1中的列保存到“dataList”中。我尝试dataList.add(table2)
以及 dataList.add(table3)
同时,但出现错误:“/reportGenerate.xhtml @50,75 value =“#{reportData.dateCreated}”:类'net.picary.model.Liaison'没有属性'dateCreated' ”
有人可以告诉我如何将三个表中所有选定的列保存到“dataList”中吗?或者有什么替代方法可以实现它?
最佳答案
error: "/reportGenerate.xhtml @50,75 value="#{reportData.dateCreated}": The class 'net.picary.model.Liaison' does not have the property 'dateCreated'."
您的问题不在于 Query 或 JDBC,您应该确保属性 dateCreated
存在于您的net.picary.model.Liaison
中带有 getter 和 setter 的类如下:
private Date dateCreated;
public String name;
public String experience;
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
所以当你的页面 reportGenerate.xhtml
尝试加载此属性但找不到它,因为:
- 您的类(class)中不存在
- 它存在,但它是私有(private)的,没有 getter 和 setter。
所以请确保你的属性存在并且有gtter和setter,这可以解决你的错误。
编辑
你有两个选择:
- 当你得到结果时,你应该使用 3 个类型为 table1、table2、table3 的列表,并将它们填充到同一个循环中,如下所示:
List dataList1 = ...; List dataList2 = ...; List dataList3 = ...; while(rs.next()){ table1 = new Table1(); table1.setCOL1(rs.getString("col1")); ... dataList1.add(table1); table2 = new Table2(); table2.setCOL1(rs.getString("col1")); ... dataList2.add(table2); table3 = new Table3(); table3.setCOL1(rs.getString("col1")); ... dataList3.add(table3); }
并且在您的 xhtml 页面中,您必须使用这三个列表而不是一个
- 创建一个新对象,将这三个表组合起来,如下所示:
class MyObject { private Table1 table1; private Table2 table2; //constructor //getters and setters }
然后创建一个List<MyObject> list = ....;
并在每个表中设置信息。
希望你明白我的意思,祝你好运
关于java - jdbc左连接3个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42440741/