SqlMapClient基本操作示例

摘自ibatis官方开发手册,笔者对其进行了重新排版以获得更好的阅读效果。

例 1: 数据写入操作(insert, update, delete):

sqlMap.startTransaction();

Product product = new Product();

product.setId (1);

product.setDescription (“Shih Tzu”);

int rows = sqlMap.insert (“insertProduct”, product);

sqlMap.commitTransaction();

例 2: 数据查询(select)

sqlMap.startTransaction();

Integer key = new Integer (1);

Product product = (Product)sqlMap.queryForObject

(“getProduct”, key);

sqlMap.commitTransaction();

例 3: 在指定对象中存放查询结果(select)

sqlMap.startTransaction();

Customer customer = new Customer();

sqlMap.queryForObject(“getCust”, parameterObject, customer);

sqlMap.queryForObject(“getAddr”, parameterObject, customer);

sqlMap.commitTransaction();

例 4: 执行批量查询(select)

sqlMap.startTransaction();

List list = sqlMap.queryForList (“getProductList”, null);

sqlMap.commitTransaction();

例 5: 关于AutoCommit

//没有预先执行startTransaction时,默认为auto_commit模式

int rows = sqlMap.insert (“insertProduct”, product);

例 6:查询指定范围内的数据

sqlMap.startTransaction();

List list = sqlMap.queryForList (“getProductList”, null, 0, 40);

sqlMap.commitTransaction();

例7: 结合RowHandler进行查询(select)

public class MyRowHandler implements RowHandler {

public void handleRow (Object object, List list) throws

SQLException {

Product product = (Product) object;

product.setQuantity (10000);

sqlMap.update (“updateProduct”, product);

}

}

sqlMap.startTransaction();

RowHandler rowHandler = new MyRowHandler();

List list = sqlMap.queryForList (“getProductList”, null,

rowHandler);

sqlMap.commitTransaction();

例8: 分页查询(select)

PaginatedList list =

sqlMap.queryForPaginatedList (“getProductList”, null, 10);

list.nextPage();

list.previousPage();

例9: 基于Map的批量查询(select)

sqlMap.startTransaction();

Map map = sqlMap.queryForMap (“getProductList”, null,

“productCode”);

sqlMap.commitTransaction();

Product p = (Product) map.get(“EST-93”);

相关推荐