通用DAO模式Spring JDBC模板

时间:2012-10-18 22:26:11

标签: java database spring dao jdbctemplate

已经有一段时间了,因为必须从头开始实现这种模式,所以我对使用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都需要自己定义这两种方法吗?我没有看到jdbc模板如何能够灵活地编写单独的插入,更新,删除语句。浏览网页我看到大量使用hibernate或entitymanager的例子。这是我应该采取的路线吗?或者我在这里错过了一个明显明显的步骤?

我知道保存和删除没有填写,但我只是想知道如何处理行

final Integer newId = jdbcTemplate.update("INSERT INTO " + tableName);

处理任何投掷的DTO。

谢天谢地!

1 个答案:

答案 0 :(得分:0)

你走的路很好,JdbcTemplate方法update can handle insert/delete/update operations

引用this article的示例演示了插入操作:

private DataSource dataSource;
private JdbcTemplate jdbcTemplate;

public void setDataSource(DataSource dataSource) {
    this.dataSource = dataSource;
}

public void insert(Customer customer){

    String sql = "INSERT INTO CUSTOMER " +
        "(CUST_ID, NAME, AGE) VALUES (?, ?, ?)";

    jdbcTemplate = new JdbcTemplate(dataSource);

    jdbcTemplate.update(sql, new Object[] { customer.getCustId(),
        customer.getName(),customer.getAge()  
    });

}
相关问题