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
public BaseDao(){
}
public Table
return table;
}
public void setTable(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){
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
return (null!=list&&list.size()==1 list.get(0):null);
}
public List
String sql = table.createSearchSqlByCondition(condition);
return template.query(sql,new RowMapperResultSetExtractor
}
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