このパターンを最初から実装する必要があったので、Spring jdbc でこのパターンを使用することについて何が欠けているのか少し混乱しています。これが私の BaseDao からのスニペットです。
protected BaseDao(RowMapper<T> rowMapper, String tableName, JdbcTemplate jdbcTemplate)
{
this.rowMapper = rowMapper;
this.tableName = tableName;
this.findByIdSql = "SELECT * FROM " + tableName + " WHERE id = ?";
this.jdbcTemplate = jdbcTemplate;
}
public T findById(final Integer id)
{
if (id == null)
{
return null;
}
Object[] params = { id };
return jdbcTemplate.queryForObject(findByIdSql, params, rowMapper);
}
public T save(final T dto)
{
if (dto == null)
{
return null;
}
try
{
if (dto.isNew())
{
final Integer newId = jdbcTemplate.update("INSERT INTO " + tableName);
}
}
catch (UncategorizedSQLException e)
{
logger.error("****************" + e.getMessage(), e);
throw new RuntimeException("Could not persist: " + e.getMessage());
}
}
public void delete(final T dto)
{
if (dto == null)
{
final String errorMessage = "Can't delete a null object";
logger.warn(errorMessage);
throw new RuntimeException(errorMessage);
}
if (!dto.cameFromDatabase())
{
throw new RuntimeException("Can't delete an object that didn't come from the database");
}
try
{
}
catch (JdbcUpdateAffectedIncorrectNumberOfRowsException e)
{
final String message = "The delete failed on " + dto + ". " + e.getMessage();
logger.error(message);
throw new RuntimeException(message, e);
}
}
ご覧のとおり、findById が機能し、スローされたクラスを処理できるようになりました。問題は、単純に jdbctemplate を使用して保存 (挿入と更新を処理) および削除を「生成」する方法を思い出せないことです。これは実現できないのでしょうか? すべての DAO は、これら 2 つのメソッド自体を定義する必要がありますか? jdbc テンプレートがどのように柔軟に挿入、更新、削除ステートメントを個別に記述できるかわかりません。Web をブラウジングすると、休止状態やエンティティ マネージャーを使用した例がたくさんあります。これは私が取るべきルートですか?または、ここで見逃している明白なステップは何ですか?
保存と削除が記入されていないことは知っていますが、その行をどのように処理するのか疑問に思っています
final Integer newId = jdbcTemplate.update("INSERT INTO " + tableName);
スローされた DTO を処理するため。
よろしくお願いします!