介绍
iBATIS是以SQL为中心的持久化层框架。能支持懒加载、关联查询、继承等特性。
iBATIS不同于一般的OR映射框架。OR映射框架,将数据库表、字段等映射到类、属性,那是一种元数据(meta-data)映射。iBATIS则是将SQL查询的参数和结果集映射到类。
所以,iBATIS做的是SQL Mapping的工作。
它把SQL语句看成输入以及输出,结果集就是输出,而where后面的条件参数则是输入。iBATIS能将输入的普通POJO对象、Map、XML等映射到SQL的条件参数上,同时也可以将查询结果映射到普通POJO对象(集合)、Map、XML等上面。
iBATIS使用xml文件来映射这些输入以及输出。
简单示例
基于ibatis-2.3.0.677版本。
创建新的项目,并引入jar包
ibatis-2.3.0.677.jar
mysql驱动
在类路径中提供ibatis的配置文件:sqlMapConfig.xml
- <?xml version="1.0" encoding="UTF-8" ?>
-
- <!DOCTYPE sqlMapConfig
- PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
- "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
-
- <sqlMapConfig>
-
- <transactionManager type="JDBC" commitRequired="false">
- <dataSource type="SIMPLE">
- <property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/>
- <property name="JDBC.ConnectionURL" value="jdbc:mysql://127.0.0.1/ibatis"/>
- <property name="JDBC.Username" value="root"/>
- <property name="JDBC.Password" value="mysql"/>
- </dataSource>
- </transactionManager>
- <sqlMap resource="com/bjsxt/crm/model/User.xml"/>
- </sqlMapConfig>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<transactionManager type="JDBC" commitRequired="false">
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/>
<property name="JDBC.ConnectionURL" value="jdbc:mysql://127.0.0.1/ibatis"/>
<property name="JDBC.Username" value="root"/>
<property name="JDBC.Password" value="mysql"/>
</dataSource>
</transactionManager>
<sqlMap resource="com/bjsxt/crm/model/User.xml"/>
</sqlMapConfig>
3、创建实体类:User.java
- package com.bjsxt.crm.model;
-
- public class User {
- private int id;
- private String username;
- private String password;
-
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- }
package com.bjsxt.crm.model;
public class User {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
创建针对User对象的CRUD的xml映射配置:User.xml
- <?xml version="1.0" encoding="UTF-8" ?>
-
- <!DOCTYPE sqlMap
- PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
- "http://ibatis.apache.org/dtd/sql-map-2.dtd">
-
- <sqlMap>
-
-
-
- <typeAlias alias="User" type="com.bjsxt.crm.model.User"/>
-
-
-
- <select id="selectAllUsers" resultClass="User">
- select * from t_user
- </select>
-
- <select id="selectUser" resultClass="User" parameterClass="int">
- select * from t_user where id=#id#
- </select>
-
-
- <insert id="insertUser" parameterClass="User">
- insert into t_user values (
- null,#username#,#password#
- )
- </insert>
-
- <update id="updateUser" parameterClass="User">
- update t_user set username = #username#,password=#password#
- where id=#id#
- </update>
-
- <delete id="deleteUser" parameterClass="int">
- delete from t_user where id=#id#
- </delete>
- </sqlMap>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap
PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap>
<!-- Use type aliases to avoid typing the full classname every time. -->
<!--定义一个实体类型,要写全包和类名在下面的CRUD操作中可以引用 -->
<typeAlias alias="User" type="com.bjsxt.crm.model.User"/>
<!-- Select with no parameters using the result map for Account class. -->
<!-- resultClass:所定义的语句的返回值类型-->
<select id="selectAllUsers" resultClass="User">
select * from t_user
</select>
<!--parameterClass:要传递进来的参数类型 -->
<select id="selectUser" resultClass="User" parameterClass="int">
select * from t_user where id=#id#
</select>
<!--parameterClass:把一个类做为参数传递进来-->
<!--sql语句中#中间的值必须在传递进来的这个类的属性中有才能赋值 -->
<insert id="insertUser" parameterClass="User">
insert into t_user values (
null,#username#,#password#
)
</insert>
<update id="updateUser" parameterClass="User">
update t_user set username = #username#,password=#password#
where id=#id#
</update>
<delete id="deleteUser" parameterClass="int">
delete from t_user where id=#id#
</delete>
</sqlMap>
5、创建测试程序测试:
- package com.bjsxt.crm.model;
-
- import java.io.Reader;
- import java.util.Iterator;
- import java.util.List;
-
- import com.ibatis.common.resources.Resources;
- import com.ibatis.sqlmap.client.SqlMapClient;
- import com.ibatis.sqlmap.client.SqlMapClientBuilder;
-
-
-
-
-
-
- public class UserTest {
-
-
-
-
- public static void main(String[] args) throws Exception{
-
-
- Reader reader = Resources.getResourceAsReader("sqlMapConfig.xml");
- SqlMapClient sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader);
- reader.close();
-
-
- for(int i=0; i<10; i++){
- User user = new User();
- user.setUsername("用户"+i);
- user.setPassword("密码"+i);
- sqlMapper.insert("insertUser", user);
- }
-
-
- List users = sqlMapper.queryForList("selectAllUsers");
- for (Iterator iter = users.iterator(); iter.hasNext();) {
- User user = (User) iter.next();
- System.out.println(user.getUsername());
- }
-
-
- User user = (User)sqlMapper.queryForObject("selectUser", 1);
- System.out.println("用户【id="+1+"】的名称是:"+user.getUsername());
-
-
- user = new User();
- user.setId(3);
- user.setUsername("更改之后的用户名称");
- user.setPassword("密码被更改");
- sqlMapper.update("updateUser", user);
-
-
- sqlMapper.delete("deleteUser", 6);
- }
-
- }
package com.bjsxt.crm.model;
import java.io.Reader;
import java.util.Iterator;
import java.util.List;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
/**
* 最简单的形式!
* @author Lee
*
*/
public class UserTest {
/**
* @param args
*/
public static void main(String[] args) throws Exception{
//从配置文件中得到SqlMapClient对象
Reader reader = Resources.getResourceAsReader("sqlMapConfig.xml");
SqlMapClient sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader);
reader.close();
//创建用户数据
for(int i=0; i<10; i++){
User user = new User();
user.setUsername("用户"+i);
user.setPassword("密码"+i);
sqlMapper.insert("insertUser", user);
}
//查询用户数据
List users = sqlMapper.queryForList("selectAllUsers");
for (Iterator iter = users.iterator(); iter.hasNext();) {
User user = (User) iter.next();
System.out.println(user.getUsername());
}
//查询特定用户的数据
User user = (User)sqlMapper.queryForObject("selectUser", 1);
System.out.println("用户【id="+1+"】的名称是:"+user.getUsername());
//更新用户的信息
user = new User();
user.setId(3);
user.setUsername("更改之后的用户名称");
user.setPassword("密码被更改");
sqlMapper.update("updateUser", user);
//删除用户的信息
sqlMapper.delete("deleteUser", 6);
}
}
SqlMapClient对象
这个对象是iBatis操作数据库的接口(执行CRUD等操作),它也可以执行事务管理等操作。这个类是我们使用iBATIS的最主要的类。它是线程安全的。通常,将它定义为单例。(与
- hibernate中sessionFactory的定义类似)。如:
- import java.io.Reader;
- import com.ibatis.common.resources.Resources;
- import com.ibatis.sqlmap.client.SqlMapClient;
- import com.ibatis.sqlmap.client.SqlMapClientBuilder;
-
- public class IbatisSQLMapConfig {
-
- private static final SqlMapClient sqlMap;
-
-
- static {
- try {
-
- String resource = "sql_map_config.xml";
-
-
- Reader reader = Resources.getResourceAsReader(resource);
-
-
- sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
-
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException(
- "Error initializing MyAppSqlConfig class. Cause: " + e);
- }
- }
- public static SqlMapClient getSqlMapInstance() {
-
- return sqlMap;
- }
- }
hibernate中sessionFactory的定义类似)。如:
import java.io.Reader;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
public class IbatisSQLMapConfig {
private static final SqlMapClient sqlMap;
//在静态区块中初试化返回
static {
try {
//声明配置文件的名称(映射文件被定义在其中)
String resource = "sql_map_config.xml";
//利用工具类Resources来读取到配置文件
Reader reader = Resources.getResourceAsReader(resource);
//创建SqlMapClient接口的变量实例
sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(
"Error initializing MyAppSqlConfig class. Cause: " + e);
}
}
public static SqlMapClient getSqlMapInstance() {
//提供静态方法返回静态区块中得到的SqlMapClient
return sqlMap;
}
}
上面相当于是对SqlMapClient的一个简单的封装,在用junit进行单元测试的时候,为了防止重复的写代码获取SqlMapClient对象,我们进行一个简单的封装