ibatis学习

一、简介

iBatis是一款简单的数据访问工具,也可作为数据持久层的框架。对比于Hibernate虽然在对象属性的扩展上修改麻烦,但是对SQL的集中管理和主动权。 iBatis的最大优点是简便,轻量级,仅需iBatis的一个jar和数据库的驱动即可运行,而且使用iBatis仅需掌握SQL和XML的用法即可,而不像Hibernate那样需要配置对象间的关系。而且iBatis比Hibernate易学。 iBatis和Hibernate目的都是解决是JDBC程序开发的繁琐性和代码的冗余性(如加载驱动,建立连接等重复且无技术含量的过程)。 

二、ibatis 应用

iBatis的配置关系图:

1. 导入 ibatis-2.3.4.726.jar

2. 数据库配置 jdbc.properties文件

jdbc.driverClassName=com.mysql.jdbc.Driver  
jdbc.url=jdbc:mysql://localhost:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=utf8  
jdbc.username=root  
jdbc.password=123  

3.  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>  
    <properties resource="jdbc.properties" />  
    <transactionManager type="JDBC">  
        <dataSource type="SIMPLE">  
            <property name="JDBC.Driver" value="${jdbc.driverClassName}" />  
            <property name="JDBC.ConnectionURL" value="${jdbc.url}" />  
            <property name="JDBC.Username" value="${jdbc.username}" />  
            <property name="JDBC.Password" value="${jdbc.password}" />  
        </dataSource>  
    </transactionManager>  
    <sqlMap resource="ibatis/resources/User.xml" />  
</sqlMapConfig>  

4. iBatis 映射文件 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="ibatis.model.User" />  
    <select id="getAllUsers" resultClass="User"> select * from users </select>  
</sqlMap>  

5. 应用程序

public class IBatisDemo {  
    public static void main(String[] args) throws IOException, SQLException {  
        String config = "ibatis/SqlMapConfig.xml";  
        Reader reader = Resources.getResourceAsReader(config);  
        SqlMapClient sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);  
        List<User> list = sqlMap.queryForList("getAllUsers");  
        for (User user : list) {  
            System.out.println(user);  
        }  
    }  
} 

三、ibatis 增删改查

a. 为了简化我们SQL输入参数的配置,我们写一个类来专门负责处理输入参数,把它们封装成一个Map类型,代码如下: 

public class ParameterMap extends HashMap<Object, Object> {  
    private static final long serialVersionUID = 1L;  
    public ParameterMap(Object... parameters) {  
        for (int i = 0; i < parameters.length - 1; i += 2) {  
            super.put(parameters[i], parameters[i + 1]);  
        }  
    }  
}  

b. 在映射文件User.xml 中声明且使用这个类型:

<typeAlias alias="User" type="ibatis.model.User" />  
<select id="getUserByName" parameterClass="java.lang.String" resultClass="User">  
    select * from users where USERNAME=#VARCHAR#  
</select>  

<select id="getUserByRealNameAndMobile" parameterClass="parameterMap" resultClass="java.util.HashMap">  
    select * from users where REALNAME=#realName:VARCHAR# and MOBILE=#mobile:VARCHAR#  
</select>  

<insert id="addUser" parameterClass="parameterMap">  
    insert into users(USERNAME,PASSWORD,REALNAME,MOBILE,EMAIL) values(#userName:VARCHAR#,#password:VARCHAR#,#realName:VARCHAR#,#mobile:VARCHAR#,#email:VARCHAR#)  
</insert>  

<update id="updateUser">  
    update users set PASSWORD='123456'  
</update>  

<delete id="deleteUser" parameterClass="java.lang.Integer">  
    delete from users where ID=#INT#  
</delete>  

c. 应用程序:

User user = sqlMap.queryForObject("getUserByName", userName);

ParameterMap parameterMap = new ParameterMap("realName", "sarin","mobile", "15940990000");  
HashMap result = sqlMap.queryForObject("getUserByRealNameAndMobile", parameterMap);  

ParameterMap parameterMap = new ParameterMap("userName", "sarin", "password", "123", "realName", "sarin", "mobile", "1","email","@");  
sqlMap.update("addUser", parameterMap);  

sqlMap.update("updateUser"); 

sqlMap.delete("deleteUser", userId);  

select 中的<sql>和<include>

<sql id="select-user"> select * from users </sql>  
<sql id="select-count"> select count(*) as value from users </sql>  
<sql id="where-age-over-value"> <![CDATA[ where age > #value:INT# ]]> </sql>  
<select id="getUserAgeOver" resultClass="hashmap">  
    <include refid="select-user" />  
    <include refid="where-age-over-value" />  
</select>  
<select id="getUserCountAgeOver" resultClass="int">  
    <include refid="select-count" />  
    <include refid="where-age-over-value" />  
</select>  

四、 spring整合ibatis

1. sqlMapConfig.xml, user.xml和jdbc.properties同上, applicationContext.xml如下:

<context:component-scan base-package="com.ibatis.model"/>

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list> <value>classpath:jdbc.properties</value> </list>
    </property>
</bean>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${driver}"/>
    <property name="url" value="${url}"/>
    <property name="username" value="${username}"/>
    <property name="password" value="${password}"/>
</bean>

<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
    <property name="configLocation" value="classpath:sqlMapConfig.xml"/>
    <property name="dataSource" ref="dataSource"/>
</bean>

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>

应用程序:

@Component
public class UserDaoImpl extends SqlMapClientDaoSupport implements UserDao {
    @Resource(name = "sqlMapClient")
    private SqlMapClient sqlMapClient;
    @PostConstruct
    public void initSqlMapClient(){
        super.setSqlMapClient(sqlMapClient);
    }

    @Override
    public List<User> getAllUsers() {
        return getSqlMapClientTemplate().queryForList("getAllUsers");
    }
}

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value="classpath:applicationContext.xml")
public class AttendDAOTest {
    @Resource
    private UserDaoImpl userDaoImpl;

    @Test
    public void selectTest() {
        List<User> users = userDaoImpl.getAllUsers();
        for(int i = 0; i<users.size();i++)
        {
            System.out.println(users.get(i).getUsername());
        }
    }
}

五、 ibatis分页

posted @ 2019-09-28 12:32  安小  阅读(219)  评论(1编辑  收藏  举报