私はMVCにデータベースを持ったアプリケーションを構築しようとしています。モデルクラスからデータをキャストしている複数のモデルがあります。アプリケーションの進捗状況が続くにつれて、重複しているようです。私のモデルのすべての関数で、私は接続、ステートメント、結果セットを開いてクエリなどを構築し、result.next();
ステートメントでデータを取得する必要があります。抽象モデルを作成してデータを取得する
これらの重複を取り除くために、私はAbstractModelという抽象クラスを使い始めました。私の目標は、すべてのモデルをこのクラスに拡張してクエリを渡すことです。私にとって難しい部分は、result.next()
ループ内のデータを取得する必要がある場所です。
私は結果セットをモデルに戻すことができると思っていましたが、もうリソースを閉じることはできません。
私のモデルクラスの1つです。
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;
}
私は以前、私がAbstractModelにbezoekerModelで作成されようとしているクエリを渡したい言ったように。これが可能なのかどうかわかりません。あなたの誰かがこれについての情報を提供してくれれば大いに感謝します。私はもう時間を無駄にする必要はありません。
なぜライブラリを使用しないのですか? SpringからのJdbcTemplate? –
'public abstract class AbstractModel'を意味しましたか? 'public class BezoekerModel extends AbstractModel'とは何ですか? – Buildersrejected
@Buildersrejectedはい、私はあなたがそれまでに得られたhavent示したものです。私の目標が何であるかを示すだけでした。それら2つのクラスは今接続されていません。 – Necati