iBatis应用

来源:互联网 发布:java线程池的函数 编辑:程序博客网 时间:2024/04/28 03:53
1,iBatis简介
    iBatis是apache的一个开源项目,一个ORM的解决方案,最大的特点就是小巧,上手很快,如果不需要太多复杂的功能,iBatis是能满足你的要求并且又足够灵活的最简单的解决方案。参看:http://ibatis.apache.org/

2,搭建环境:导入相关的jar包(iBatis包,数据库驱动包)

3,配置文件
    *JDBC连接到数据库信息(properties属性文件)
    *SqlMapConfig.xml配置文件(...\ibatis\simple_example\com\mydomain\data)
     <sqlMapConfig>
         <!-- 引入资源文件 -->
         <properties resource="mysql.properties" />
         <!-- 根据资源文件配置信息,创建数据库连接 -->
         <transactionManager type="JDBC" commitRequired="false">
            <dataSource type="SIMPLE">
                  <property name="JDBC.Driver" value="${Driver}" />
                  <property name="JDBC.ConnectionURL" value="${URL}" />
                  <property name="JDBC.Username" value="${Username}" />
                  <property name="JDBC.Password" value="${Password}" />
            </dataSource>
         </transactionManager>
         <sqlMap resource="com/softeem/ibatis/vo/User.xml" />
     </sqlMapConfig>
    *对应于每个实体类的map映射文件(...\ibatis\simple_example\com\mydomain\data)

4,读取配置
    static{
        try {
            reader = Resources.getResourceAsReader(CONFIG_FILE);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static SqlMapClient getSqlMapClient(){
        try {
            if(client == null){
                client = SqlMapClientBuilder.buildSqlMapClient(reader);
            }else if(client.getCurrentConnection()==null){
                client = SqlMapClientBuilder.buildSqlMapClient(reader);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return client;
    }


5,基本的CRUD操作(借助SqlMapClient中的方法)
    *创建一个pojo
    *orm映射文件配置
    *创建dao
    *SqlMapClient:queryForObject/queryForList/insert/delete/update

6,模糊查询
    <select id="mohu" parameterClass="java.lang.String" resultMap="stu">
     <!-- 当在"'"中需要引入参数的时候(参数拼接),我们需要将“#”换成“$”来接收参数 -->
     select * from tb_student where username like '%$name$%'
    </select>
 

7,自动主键selectKey
<insert id="addUser" parameterClass="User">
    <selectKey resultClass="int" keyProperty="sid">
        select sq.nextVal as sid from dual
    </selectKey>
    insert into user(userid,username,password) values(#sid#,#username#,#password#)        
</insert>