开始自学ibatis
1.环境:
导包classes12.jar和ibatis-2.3.4.726.jar
配置文件:
①数据库驱动,URL,用户名,密码
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:SID
username=ibatis
password=ibatis
②XML文件
复制ibatis-2.3.4.726\simple_example\com\mydomain\data\SqlMapConfig.xml文件和Account.xml文件到工程
(这里可以参考ibatis-2.3.4.726\simple_example\com\mydomain\data下的例子怎么写的)
修改Account.xml名为Role.xml,并配置<sqlMap resource="com/braint/ibatis/Role.xml"/>
2.使用
①建立个普通Bean,保证有个无参数构造方法,创建所对应的表的属性以及set,get方法
②Role.xml文件中写和实现类中方法所对应的标签,如:
<typeAlias alias="Role" type="com.braint.beans.Role"/>
这里alias="Role"应该是对于后面type的简写,下面查询的时候写的resultClass应与alias所对应(当然如果改为alias="Role111",下面的查询改为resultClass="Role111"也是可以的)
<select id="searchRole" resultClass="Role">
select * from t_role
</select>
即为查找表t_role所有记录,返回为List<Role>
③建立DAO和实现类,在实现类中创建各个方法。
首先得先创建读写流从Role.xml文件中读方法,所以在实现类中加如以下代码:
private static SqlMapClient sqlMapClient;
static {
try {
Reader reader = Resources.getResourceAsReader("com/braint/ibatis/SqlMapConfig.xml");
sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
④实现类中调用Role.xml文件中的方法:
public List<Role> searchRole() {
List<Role> roleList = null;
try {
roleList = sqlMapClient.queryForList("searchRole");
//这里的参数和返回值对应xml文件中的<select id="searchRole" resultClass="Role">
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return roleList;
}