ibatis_HelloWorld

 

1.导入ibatis-2.3.4.726.jar; mysql-connector-java-5.1.8-bin.jar两个包

2.在pojo包下建一个javabean文件User.Java:

package pojo;

import java.util.Date;

public class User {
  
private int id;   private String name;   private Date birthday;
  省略get和set方法 }

3.在pojo包下建一个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  namespace="User">

<!-- 命名空间以外空间引用此空间时用这个别名引用 -->
        <typeAlias alias="user" type="pojo.User"/>
            <!-- 给这个javabean对象起个别名这里不区分大小写 -->
            <select id="getAllUsers" resultClass="user">
                 select * from user order by id;
            </select>
            <!-- 定义查找方法id为getAllUsers,返回的结果类型resultClass是user类型的 -->
            <select id="getUser" parameterClass="java.lang.String" resultClass="user">
                 select * from user where name=#name#;
            </select>
            <!-- 定义查找方法id为getUser,传入的参数类型是java.lang.String类型的,返回的结果类型resultClass是user类型的 -->
            <insert id="addUser" parameterClass="user">
                 insert into user(id, name,birthday) values(#id#, #name#, #birthday#);
            </insert>
            <delete id="delUser" parameterClass="java.lang.Integer">
                 delete from user where id=#id#;
            </delete>
            <update id="updateUser" parameterClass="user">
                 update user set name=#name#, birthday=#birthday# where id = #id#
            </update>
</sqlMap>
  1. src下配置好一个SqlMapConfig.xml文件,主要是负责jdbc的Connection,和与映射相联系(也可以通过.properties文件.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">
   <dataSource type="SIMPLE">
      <property name="JDBC.Driver" value="com.mysql.jdbc.Driver" />
      <property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost:3306/test" />
<property name="JDBC.Username" value="root" /> <property name="JDBC.Password" value="123456" /> </dataSource> </transactionManager> <sqlMap resource="pojo/User.xml" /><!-- 映射源是pojo/User.xml --> </sqlMapConfig>
  1. 在test包里建一个UserDaoTest.java进行测试

省略导包。。。。。。和捕捉异常。。。。

public class UserDaoTest {
  public static void main(String[] args) {
      //查找根据name来查找
      List list = null;
      SqlMapClient sqlMap = null;
      User user = new User();
      user.setName("小强");
      Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
      sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
      reader.close();
      list = sqlMap.queryForList("getUser","小强");
      for(int i=0;i<list.size();i++){
          User us = (User)list.get(i);
          System.out.println("name:"+us.getName()+"--"+"birthday:"+us.getBirthday());
      }
  }
}

 

 

posted @ 2011-11-22 19:26  horizon~~~  阅读(325)  评论(0编辑  收藏  举报