iBatis初步认识与使用(二)

2015-02-03 04:25:42 · 作者: · 浏览: 38
Map; import com.ibatis.common.resources.Resources; import com.ibatis.sqlmap.client.SqlMapClient; import com.ibatis.sqlmap.client.SqlMapClientBuilder; import com.wxc.bean.BookInfo; import com.wxc.dao.BookInfoDao; public class BookInfoDaoImpl implements BookInfoDao { private static SqlMapClient sqlMapClient = null; //读取配置文件 static{ try { Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml"); sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader); reader.close(); } catch (Exception e) { e.printStackTrace(); } } @SuppressWarnings("unchecked") @Override public List listBookInfo() { List list = null; try { //注意第一个参数,是对应xml文件里的查询id list = this.sqlMapClient.queryForList("listBookInfo", null); } catch (Exception e) { e.printStackTrace(); } return list; } @SuppressWarnings("unchecked") @Override public List bookInfoByAuthor(String name) { List list = null; try { list = this.sqlMapClient.queryForList("listBookInfoByAuthor", name); } catch (Exception e) { e.printStackTrace(); } return list; } @SuppressWarnings("static-access") @Override public void update(BookInfo bookinfo) { try { this.sqlMapClient.update("update", bookinfo); } catch (SQLException e) { e.printStackTrace(); } } @SuppressWarnings("static-access") @Override public void delete(int id) { try { this.sqlMapClient.delete("delete", id); } catch (SQLException e) { e.printStackTrace(); } } @Override public List listByAuthorAndPublish(String author, String publish) { Map mp = new HashMap(); mp.put("anthor", author); mp.put("publish", publish); List list = null; try { list = this.sqlMapClient.queryForList("listByAuthorAndPublis", mp); } catch (SQLException e) { e.printStackTrace(); } return list; } } 到此,所有的文件都敲好了,只需要写一个测试类调用Impl里的方法就行了。这里说几点ibatis独特的地方,注意实体类的映射文件BookInfo.xml里有
select * from bookinfo where author=#sql#

然后在java文件里这样写

String sql = author+"and publish"+publish;

也就是把sql语句从中间劈开,这样有的时候也许是通用的,但是也有特殊的时候,我就是被这样的写法坑了一次,所以建议大家还是用Map传递参数

到这里,有没有感到ibatis是一个持久层的框架啊,如果把hibernate比作是自动冲锋枪的话那ibatis数据半自动冲锋枪。sql语句还是需要自己写的!!!

好了,以上就是我对ibatis的初步认识,在以后如果有学到新的更近一层的知识,我会更新的!