用JDBCTemplate实现的单表通用DAO,实现增删改查和统计(六)

2014-11-24 07:23:27 · 作者: · 浏览: 6
atedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
* @author xiakan
* @version 1.0
*/
@Component
@Transactional(propagation=Propagation.SUPPORTS,readOnly=true)
public abstract class BaseDao {

@Autowired
protected JdbcTemplate template = null;

protected Table table = null;

public BaseDao(){

}

public Table getTable() {
return table;
}

public void setTable(Table table) {
this.table = table;
}

public JdbcTemplate getTemplate() {
return template;
}

public void setTemplate(JdbcTemplate template) {
this.template = template;
}

@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
public T insert(T item){
final KeyHolder keyHolder = new GeneratedKeyHolder();
final String sql = table.createInsertSql(item);
template.update(new PreparedStatementCreator(){
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement ps = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
return ps;
}
}, keyHolder);
table.setID(item,keyHolder.getKey().longValue());
return item;
}

@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
public int update(T item){
String sql = table.createUpdateSql(item);
return template.update(sql);
}

@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
public int deleteItem(T item){
String sql = table.createDeleteSql(item);
return template.update(sql);
}

@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
public int delete(PK pkValue){
String sql = table.createDeleteSqlByPKValue(pkValue);
return template.update(sql);
}

public T searchByID(PK pkValue){
String sql = table.createSearchSqlByPKValue(pkValue);
List list = template.query(sql,new RowMapperResultSetExtractor(table.getRowMapper()));
return (null!=list&&list.size()==1 list.get(0):null);
}

public List search(String condition){
String sql = table.createSearchSqlByCondition(condition);
return template.query(sql,new RowMapperResultSetExtractor(table.getRowMapper()));
}

public Long count(){
String sql = table.createCountSql();
return template.queryForLong(sql);
}

public Long count(String condition){
String sql = table.createCountSqlByCondition(condition);
return template.queryForLong(sql);
}

}


testcase:
[java]
package com.nbport.ctos2.dao;

import java.util.List;

import org.apache.commons.lang.RandomStringUtils;

import com.nbport.ctos2.common.AppDefine;
import com.nbport.ctos2.dao.ContainerDao;
import com.nbport.ctos2.entity.Container;

import junit.framework.Assert;
import junit.framework.TestCase;

public class ContainerDaoTest ex