我想在MVC中也有一个数据库建立一个应用程序。我有多个模型,我正在从模型类中投射数据。随着应用程序进展的继续,它似乎有很多重复。在我的模型中的每个函数中,我需要打开一个连接,语句和结果集构建查询等,并使用result.next();
语句获取数据。创建一个抽象模型来检索数据
为了摆脱这些重复,我开始使用名为AbstractModel的抽象类。我的目标是将所有模型扩展到这个类并传递查询。对我来说困难的部分是我需要在result.next()
循环中检索数据的位置。
我以为我可以将结果集传回给我的模型,但后来我无法再关闭我的资源。
我的模型类之一。
public class BezoekerModel
{
public Gebruiker getGebruiker(String username, String password)
{
Gebruiker user = null;
PreparedStatement stat = null;
ResultSet result = null;
Connection conn = null;
try
{
conn = SimpleDataSourceV2.getConnection();
String query = "SELECT * FROM gebruiker WHERE gebruikersnaam = ? AND wachtwoord = ?;";
stat = conn.prepareStatement(query);
stat.setString(1, username);
stat.setString(2, password);
result = stat.executeQuery();
while (result.next())
{
String gebruikerstype = result.getString("gebruikerstype");
String voornaam = result.getString("voornaam");
String tussenvoegsel = result.getString("tussenvoegsel");
String achternaam = result.getString("achternaam");
int schoolcode = result.getInt("schoolcode");
user = new Gebruiker(voornaam, tussenvoegsel, achternaam, gebruikerstype, schoolcode);
}
}
catch (SQLException ex)
{
ex.printStackTrace();
} finally
{
try
{
result.close();
stat.close();
conn.close();
}
catch (SQLException ex)
{
System.out.println("Error: " + ex.toString());
}
}
return user;
}
}
正如你所看到的,我把我检索到的所有数据都转换成了Gebruiker对象,后来我也回来了。
这是我现在正在构建的抽象模型。
public class AbstractModel
{
public List<Object> getData(String query) {
List<Object> data = new ArrayList();
Statement stat = null;
ResultSet result = null;
Connection conn = null;
try {
conn = SimpleDataSourceV2.getConnection();
stat = conn.createStatement();
result = stat.executeQuery(query);
while (result.next()) {
// ?????
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
result.close();
stat.close();
conn.close();
} catch (SQLException ex) {
System.out.println("Error: " + ex.toString());
}
}
return data;
}
正如我前面说过的,我想将要在bezoekerModel中创建的查询传递给AbstractModel。我不知道这是否可能。如果你们中的任何一位对此提供了意见,我们将不胜感激,所以我不必再浪费任何时间。
为什么你不使用图书馆? Spring的JdbcTemplate? –
您是不是指'公共抽象类AbstractModel'?和'公共类BezoekerModel扩展AbstractModel'? – Buildersrejected
@Buildersrejected是的,但是我展示的那些你还没有得到那么多。这只是为了展示我的目标是什么。这两个班级现在没有连接。 – Necati