2012-10-18 89 views
0

自從不得不從一開始就實現這個模式以來,我有點困惑,因爲我對使用spring jdbc使用這個模式的想法有些困惑。這是從我的BaseDao片段:通用DAO模式Spring JDBC模板

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來「保存」save(句柄插入和更新)和刪除。這不能完成嗎?每個DAO都需要自己定義這兩種方法嗎?我看不出jdbc模板如何可以彎曲來編寫單獨的插入,更新,刪除語句。瀏覽網頁我看到了大量使用hibernate或entitymanager的示例。這是我應該採取的路線嗎?或者我在這裏失蹤的明顯步驟是什麼?

我知道保存和刪除不填寫,但我只是想知道如何處理線

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

要處理扔給它的任何DTO。

謝謝親切!

回答

0

你是一個很好的路徑,JdbcTemplate方法updatecan 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() 
    }); 

} 
+1

感謝您的答覆,我知道如何爲特定的DTO執行插入。但我試圖弄清楚如何使通用插入,以便它可以採取任何DTO。這只是jdbctemplate可能嗎?我見過enityManger這樣做,hibernate,JPA等等。謝謝 – sauce

+1

無論jdbcTemplate還是ORM,都無法避免在哪些列中解析哪些數據。它從來不會自動發生。即使在您引用的ORM框架中,您也需要指定DTO的哪個字段映射到哪個表列。它基本上是在ORM實體中引入一個額外的圖層來抽象上面例子中用jdbctemplate所看到的映射。 – dimitrisli

+1

謝謝你回答我的問題! – sauce