您可以通过使用 SimpleJdbcTemplate 而不是 JdbcTemplate 并通过扩展 SimpleJdbcDaoSupport 来获得更相似的效果,所有 DB 操作都可以放在一个 DAO 类中:
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
import org.springframework.stereotype.Repository;
@Repository
public class BankDaoImpl extends SimpleJdbcDaoSupport implements BankDao {
@Autowired
public BankDaoImpl(@Qualifier("dataSource") DataSource dataSource) {
setDataSource(dataSource);
}
@Override
public void insert(Bank bank) {
String sql = "INSERT INTO BANK (id, oib, short_name, name, street, town, postal_code, homepage_url, last_change) VALUES (NEXT VALUE FOR bank_seq, :oib, :shortName, :name, :street, :town, :postalCode, :homepageUrl, CURRENT_TIMESTAMP)";
SqlParameterSource parameterSource = new BeanPropertySqlParameterSource(
bank);
getSimpleJdbcTemplate().update(sql, parameterSource);
}
@Override
public void update(Bank bank) {
String sql = "UPDATE BANK SET oib=:oib, short_name=:shortName, name=:name, street=:street, town=:town, postal_code=:postalCode, homepage_url=:homepageUrl, last_change=CURRENT_TIMESTAMP WHERE id=:id";
SqlParameterSource parameterSource = new BeanPropertySqlParameterSource(
bank);
getSimpleJdbcTemplate().update(sql, parameterSource);
}
@Override
public void delete(String id) {
String sql = "DELETE FROM BANK WHERE id=:id";
getSimpleJdbcTemplate().update(sql,
new MapSqlParameterSource("id", id));
}
@Override
public Bank findById(String id) {
String sql = "select b.ID, b.OIB, b.SHORT_NAME, b.NAME, b.STREET, b.TOWN, b.POSTAL_CODE, b.HOMEPAGE_URL, b.LAST_CHANGE, CASE WHEN count(f.id) = 0 THEN 0 ELSE 1 END AS ready " +
"from BANK WHERE b.ID = :id";
return getSimpleJdbcTemplate().queryForObject(sql,
BeanPropertyRowMapper.newInstance(Bank.class),
new MapSqlParameterSource("id", id));
}
}