简体   繁体   中英

Generic DAO pattern Spring JDBC Template

It's been a while since had to implement this pattern from the beginning so I am a bit confused on what I am missing about using this pattern with spring jdbc. Here is a snippet from my 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);

      }
   }

As you can see I got my findById working and able to handle any class thrown at it. The trouble is I don't recall on how to "generify" the save (handles insert and update) and delete using simply the jdbctemplate. Can this not be accomplished? Does every DAO need to define these two methods itself? I don't see how jdbc template can flex to writing seperate insert, update, delete statements. Browsing the web I see tons of examples using hibernate or an entitymanager. Is this the route I should take? Or what is the plainly obvious step I am missing here?

I know the save and delete are not filled out but I'm just wondering how to handle the line

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

To handle any DTO thrown at it.

Thank you kindly!

You are in a good path, JdbcTemplate method update can handle insert/delete/update operations

An example quoted from this article demonstrating an insert operation:

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()  
    });

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM