这段时间闲来无事重新研究下SSH和SSI的模型,以前写过一篇关于Hibernate对JDBC的封装的文章,这不就再来写一篇Ibatis的。
相对于Hibernate的一站式ORM解决方案而言,Ibatis则是一种半自动化的ORM的实现方案了,怎么说呢,大家看Hibernate是对数据库结构提供了较为完整的封装,提供了POJO到数据库表的全套映射机制,我们要做的就是配置好配置文件和POJO以及他们之间的映射关系即可,即便是你不懂SQL语句,也能进行开发使用。可是往往这种情况下就稍微的有点儿局限性,对于有些需求来说不容易满足,并且不利于sql的优化等。这时我们就更多的考虑到了轻量级的Ibatis这种半自动的实现形式了。要知道Ibatis的优点在于,它仅仅实现的是POJO与sql之间的映射关系,具体的sql语句需要我们自己来写才行。然后通过Ibatis的配置文件将sql所需的参数,以及返回的结果字段映射到指定的POJO。从而达到ORM效果.下面让我们来一一介绍Ibatis的配置文件以及核心函数:
1.Ibatis的实例配置文件及jdbc的配置:
<sqlMapConfig>
<properties resource="SqlMap.properties"/>这里是jdbc的配置文件
<transactionManager type="JDBC">
<dataSource type="SIMPLE">
<property value="${driver}" name="JDBC.Driver"/>
<property value="${url}" name="JDBC.ConnectionURL"/>
<property value="${username}" name="JDBC.Username"/>
<property value="${password}" name="JDBC.Password"/>
</dataSource>
</transactionManager>
<sqlMap resource="ncut/com/map/Student.xml"/>这里是POJO与sql语句的映射文件
</sqlMapConfig>
2.POJO的基础类文件:
public class Student {
private int id;
private String username;
private String password;
private int age;
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
3.sql的映射文件:
<sqlMap>
<typeAlias alias="Student" type="ncut.com.bean.Student"/><!-- 其实就是将bean的替换成一个短的名字 -->
<select id="selectAllStudent" resultClass="Student">
select * from student1
</select>
<!-- parameterClass 和 parameterMap都是参数类型
resultClass resultMap都是返回值类型 -->
<select id="selectStudentById" parameterClass="int" resultClass="Student">
select * from student1
where id=#id#
</select>
<insert id="addStudent" parameterClass="Student">
insert student1(id,username,password,age)
values (#id#,#username#,#password#,#age#)
</insert>
</sqlMap>
4.SqlMapClient是Ibatis运作的核心,所有的数据库操作都是通过SqlMapClient实例来完成的。
XmlSqlMapClientBuilder是ibatis的组件,是用来根据配置文件创建SqlMapClient实例的:
private static SqlMapClient sqlMapClient;
static{
try {
Reader reader=com.ibatis.common.resources.Resources.getResourceAsReader("SqlMapConfig.xml");
sqlMapClient=com.ibatis.sqlmap.client.SqlMapClientBuilder.buildSqlMapClient(reader);
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
然后就可以直接调用
SqlMapClient中的方法,进行数据库的CRUD了。
其中还有很多的细节,值得自己去慢慢研究。