iBatis简明教程及快速入门
iBatis是又一个O/R Mapping解决方案,j2ee的O/R方案真是多,和Hibernate相比,iBatis最大的特点就是小巧,上手很快。如果你不需要太多复杂的功能,iBatis是能满足你的要求又足够灵活的最简单的解决方案。
iBatis最大的特点是简单,最新版本2.0(下载),和1.0相比,主要改动在XML配置文件上,不过,只要有SQL基础,相信你不用教程也能看明白。下面我们看一个最简单的例子入门。
我们先建一个表Account,包括字段username, varchar(20), pk和password, varchar(20),随便填入一些数据。然后编写iBatis必须的配置文件sql-map-config.xml,文件名随意,内容如下:
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN" "http://www.ibatis.com/dtd/sql-map-config-2.dtd"><sqlMapConfig> <settings cacheModelsEnabled="true" enhancementEnabled="true" lazyLoadingEnabled="true" maxRequests="32" maxSessions="10" maxTransactions="5" useStatementNamespaces="false" /> <transactionManager type="JDBC" > <dataSource type="SIMPLE"> <property name="JDBC.Driver" value="sun.jdbc.odbc.JdbcOdbcDriver"/> <property name="JDBC.ConnectionURL" value="jdbc:odbc:Blog"/> <property name="JDBC.Username" value="admin"/> <property name="JDBC.Password" value=""/> </dataSource> </transactionManager> <sqlMap resource="Account.xml" /></sqlMapConfig>
package example;public class Account { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username=username; } public String getPassword() { return password; } public void setPassword(String password) { this.password=password; }}
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://www.ibatis.com/dtd/sql-map-2.dtd"><sqlMap namespace="Account"> <select id="getAccount" parameterresultparametername="code"> com.ibatis.sqlmap.client.SqlMapClient sqlMap = null; try { java.io.Reader reader = om.ibatis.common.resources.Resources.getResourceAsReader ("sql-map-config.xml"); sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader); } catch (Exception e) { e.printStackTrace(); }
try { Account accout = (Account)sqlMap.queryForObject("getAccount", "admin"); ... }
try { Account account = new Account(); account.setUsername("micheal"); account.setPassword("1234"); sqlMap.insert("createAccount", account); }