iBatis入门教程

fmms 13年前
     <p class="MsoNormal"><strong><span>iBatis</span> </strong><strong><span>简介:</span> </strong></p>    <p style="text-indent:21pt;" class="MsoNormal"><span>iBatis</span> <span>是<span lang="EN-US">apache</span> 的一个开源项目,一个<span lang="EN-US">O/R Mapping</span> 解决方案,<span lang="EN-US">iBatis</span> 最大的特点就是小巧,上手很快。如果不需要太多复杂的功能,<span lang="EN-US">iBatis</span> 是能够满足你的要求又足够灵活的最简单的解决方案,现在的<span lang="EN-US">iBatis</span> 已经改名为<span lang="EN-US">Mybatis</span> 了。</span> </p>    <p class="MsoNormal"><span>官网为:<span lang="EN-US">http://www.mybatis.org/</span> </span></p>    <p class="MsoNormal"><span> </span> </p>    <p class="MsoNormal"><strong><span>搭建<span lang="EN-US">iBatis</span> 开发环境:</span> </strong></p>    <p style="text-indent:21pt;" class="MsoNormal"><span>1</span> <span>、导入相关的<span lang="EN-US">jar</span> 包,<span lang="EN-US">ibatis-2.3.0.677.jar</span> 、<span lang="EN-US">mysql-connector-java-5.1.6-bin.jar</span> </span></p>    <p class="MsoNormal"><span><span>        </span>2</span> <span>、编写配置文件:</span> </p>    <p class="MsoNormal"><span><span>              </span>Jdbc</span> <span>连接的属性文件</span> </p>    <p class="MsoNormal"><span><span>              </span></span><span>总配置文件,<a name="OLE_LINK2"></a> <a name="OLE_LINK1"><span><span lang="EN-US">SqlMapConfig.xml</span> </span></a></span></p>    <p class="MsoNormal"><span><span><span><span>              </span></span></span></span><span><span><span>关于每个实体的映射文件(<span lang="EN-US">Map</span> 文件)</span> </span></span></p>    <p> </p>    <p class="MsoNormal"><strong><span>Demo</span> </strong><strong><span>:</span> </strong></p>    <p class="MsoNormal"><span>Student.java:</span></p>    <pre class="brush:java; toolbar: true; auto-links: false;">package com.iflytek.entity;  import java.sql.Date;  /**  * @author xudongwang 2011-12-31  *   *         Email:xdwangiflytek@gmail.com  *   */ public class Student {  // 注意这里需要保证有一个无参构造方法,因为包括Hibernate在内的映射都是使用反射的,如果没有无参构造可能会出现问题  private int id;  private String name;  private Date birth;  private float score;   public int getId() {   return id;  }   public void setId(int id) {   this.id = id;  }   public String getName() {   return name;  }   public void setName(String name) {   this.name = name;  }   public Date getBirth() {   return birth;  }   public void setBirth(Date birth) {   this.birth = birth;  }   public float getScore() {   return score;  }   public void setScore(float score) {   this.score = score;  }   @Override  public String toString() {   return "id=" + id + "\tname=" + name + "\tmajor=" + birth + "\tscore="     + score + "\n";  }  }</pre>    <p></p>    <p class="MsoNormal"><span>SqlMap.properties</span> <span>:</span></p>    <pre class="brush:shell; toolbar: true; auto-links: false;">driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/ibatis username=root password=123</pre>    <p></p>    <p class="MsoNormal"><span>Student.xml</span> <span>:</span></p>    <pre class="brush:xml; toolbar: true; auto-links: false;"><?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使得我们在下面使用Student实体类的时候不需要写包名 -->  <typeAlias alias="Student" type="com.iflytek.entity.Student" />   <!-- 这样以后改了sql,就不需要去改java代码了 -->  <!-- id表示select里的sql语句,resultClass表示返回结果的类型 -->  <select id="selectAllStudent" resultClass="Student">   select * from   tbl_student  </select>   <!-- parameterClass表示参数的内容 -->  <!-- #表示这是一个外部调用的需要传进的参数,可以理解为占位符 -->  <select id="selectStudentById" parameterClass="int" resultClass="Student">   select * from tbl_student where id=#id#  </select>   <!-- 注意这里的resultClass类型,使用Student类型取决于queryForList还是queryForObject -->  <select id="selectStudentByName" parameterClass="String"   resultClass="Student">   select name,birth,score from tbl_student where name like   '%$name$%'  </select>   <insert id="addStudent" parameterClass="Student">   insert into   tbl_student(name,birth,score) values   (#name#,#birth#,#score#);   <selectKey resultClass="int" keyProperty="id">    select @@identity as inserted    <!-- 这里需要说明一下不同的数据库主键的生成,对各自的数据库有不同的方式: -->    <!-- mysql:SELECT LAST_INSERT_ID() AS VALUE -->    <!-- mssql:select @@IDENTITY as value -->    <!-- oracle:SELECT STOCKIDSEQUENCE.NEXTVAL AS VALUE FROM DUAL -->    <!-- 还有一点需要注意的是不同的数据库生产商生成主键的方式不一样,有些是预先生成 (pre-generate)主键的,如Oracle和PostgreSQL。      有些是事后生成(post-generate)主键的,如MySQL和SQL Server 所以如果是Oracle数据库,则需要将selectKey写在insert之前 -->   </selectKey>  </insert>   <delete id="deleteStudentById" parameterClass="int">   <!-- #id#里的id可以随意取,但是上面的insert则会有影响,因为上面的name会从Student里的属性里去查找 -->   <!-- 我们也可以这样理解,如果有#占位符,则ibatis会调用parameterClass里的属性去赋值 -->   delete from tbl_student where id=#id#  </delete>   <update id="updateStudent" parameterClass="Student">   update tbl_student set   name=#name#,birth=#birth#,score=#score# where id=#id#  </update>  </sqlMap></pre>    <p></p>    <p class="MsoNormal"><span>说明:</span> </p>    <p class="MsoNormal"><span>如果<span lang="EN-US">xml</span> 中没有<span lang="EN-US">ibatis</span> 的提示,则<span lang="EN-US">window --> Preference--> XML-->XML Catalog---></span> 点击<span lang="EN-US">add</span> </span></p>    <p class="MsoNormal"><span>选择<span lang="EN-US">uri</span> </span><span>URI: </span><span>请选择本地文件系统上</span> </p>    <p class="MsoNormal"><span>iBatisDemo1/WebContent/WEB-INF/lib/sql-map-config-2.dtd</span> <span>文件;</span> </p>    <p class="MsoNormal"><span>Key Type: </span><span>选择<span lang="EN-US">Schema Location;</span> </span></p>    <p class="MsoNormal"><span>Key: </span><span>需要联网的,不建议使用;</span> </p>    <p class="MsoNormal"> </p>    <p class="MsoNormal"><span>SqlMapConfig.xml</span> <span>:</span></p>    <pre class="brush:xml; toolbar: true; auto-links: false;"><?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>  <!-- 引用JDBC属性的配置文件 -->  <properties resource="com/iflytek/entity/SqlMap.properties" />  <!-- 使用JDBC的事务管理 -->  <transactionManager type="JDBC">   <!-- 数据源 -->   <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/iflytek/entity/Student.xml" /> </sqlMapConfig></pre>    <p></p>    <p class="MsoNormal"><span>StudentDao</span> <span>:</span></p>    <pre class="brush:java; toolbar: true; auto-links: false;">package com.iflytek.dao;  import java.util.List;  import com.iflytek.entity.Student;  /**  * @author xudongwang 2011-12-31  *   *         Email:xdwangiflytek@gmail.com  *   */ public interface StudentDao {   /**   * 添加学生信息   *    * @param student   *            学生实体   * @return 返回是否添加成功   */  public boolean addStudent(Student student);   /**   * 根据学生id删除学生信息   *    * @param id   *            学生id   * @return 删除是否成功   */  public boolean deleteStudentById(int id);   /**   * 更新学生信息   *    * @param student   *            学生实体   * @return 更新是否成功   */  public boolean updateStudent(Student student);   /**   * 查询全部学生信息   *    * @return 返回学生列表   */  public List<Student> selectAllStudent();   /**   * 根据学生姓名模糊查询学生信息   *    * @param name   *            学生姓名   * @return 学生信息列表   */  public List<Student> selectStudentByName(String name);   /**   * 根据学生id查询学生信息   *    * @param id   *            学生id   * @return 学生对象   */  public Student selectStudentById(int id);  }</pre>    <p></p>    <p class="MsoNormal"><span>StudentDaoImpl</span> <span>:</span></p>    <pre class="brush:java; toolbar: true; auto-links: false;">package com.iflytek.daoimpl;  import java.io.IOException; import java.io.Reader; import java.sql.SQLException; import java.util.List;  import com.ibatis.common.resources.Resources; import com.ibatis.sqlmap.client.SqlMapClient; import com.ibatis.sqlmap.client.SqlMapClientBuilder; import com.iflytek.dao.StudentDao; import com.iflytek.entity.Student;  /**  * @author xudongwang 2011-12-31  *   *         Email:xdwangiflytek@gmail.com  *   */ public class StudentDaoImpl implements StudentDao {   private static SqlMapClient sqlMapClient = null;   // 读取配置文件  static {   try {    Reader reader = Resources      .getResourceAsReader("com/iflytek/entity/SqlMapConfig.xml");    sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);    reader.close();   } catch (IOException e) {    e.printStackTrace();   }  }   public boolean addStudent(Student student) {   Object object = null;   boolean flag = false;   try {    object = sqlMapClient.insert("addStudent", student);    System.out.println("添加学生信息的返回值:" + object);   } catch (SQLException e) {    e.printStackTrace();   }   if (object != null) {    flag = true;   }   return flag;  }   public boolean deleteStudentById(int id) {   boolean flag = false;   Object object = null;   try {    object = sqlMapClient.delete("deleteStudentById", id);    System.out.println("删除学生信息的返回值:" + object + ",这里返回的是影响的行数");   } catch (SQLException e) {    e.printStackTrace();   }   if (object != null) {    flag = true;    }   return flag;   }   public boolean updateStudent(Student student) {   boolean flag = false;   Object object = false;   try {    object = sqlMapClient.update("updateStudent", student);    System.out.println("更新学生信息的返回值:" + object + ",返回影响的行数");   } catch (SQLException e) {    e.printStackTrace();   }   if (object != null) {    flag = true;   }   return flag;  }   public List<Student> selectAllStudent() {   List<Student> students = null;   try {    students = sqlMapClient.queryForList("selectAllStudent");   } catch (SQLException e) {    e.printStackTrace();   }   return students;  }   public List<Student> selectStudentByName(String name) {   List<Student> students = null;   try {    students = sqlMapClient.queryForList("selectStudentByName",name);   } catch (SQLException e) {    e.printStackTrace();   }   return students;  }   public Student selectStudentById(int id) {   Student student = null;   try {    student = (Student) sqlMapClient.queryForObject(      "selectStudentById", id);   } catch (SQLException e) {    e.printStackTrace();   }   return student;  } }</pre>    <p></p>    <p class="MsoNormal"><span>TestIbatis.java</span> <span>:</span></p>    <pre class="brush:java; toolbar: true; auto-links: false;">package com.iflytek.test;  import java.sql.Date; import java.util.List;  import com.iflytek.daoimpl.StudentDaoImpl; import com.iflytek.entity.Student;  /**  * @author xudongwang 2011-12-31  *   *         Email:xdwangiflytek@gmail.com  *   */ public class TestIbatis {   public static void main(String[] args) {   StudentDaoImpl studentDaoImpl = new StudentDaoImpl();    System.out.println("测试插入");   Student addStudent = new Student();   addStudent.setName("李四");   addStudent.setBirth(Date.valueOf("2011-09-02"));   addStudent.setScore(88);   System.out.println(studentDaoImpl.addStudent(addStudent));    System.out.println("测试根据id查询");   System.out.println(studentDaoImpl.selectStudentById(1));    System.out.println("测试模糊查询");   List<Student> mohuLists = studentDaoImpl.selectStudentByName("李");   for (Student student : mohuLists) {    System.out.println(student);   }    System.out.println("测试查询所有");   List<Student> students = studentDaoImpl.selectAllStudent();   for (Student student : students) {    System.out.println(student);   }    System.out.println("根据id删除学生信息");   System.out.println(studentDaoImpl.deleteStudentById(1));    System.out.println("测试更新学生信息");   Student updateStudent = new Student();   updateStudent.setId(1);   updateStudent.setName("李四1");   updateStudent.setBirth(Date.valueOf("2011-08-07"));   updateStudent.setScore(21);   System.out.println(studentDaoImpl.updateStudent(updateStudent));   } }</pre>    <p></p>    <p class="MsoNormal"><strong><span>iBatis</span> </strong><strong><span>的优缺点:</span> </strong></p>    <p class="MsoNormal"><span>优点:</span> </p>    <p class="MsoListParagraph"><span><span>1、<span style="line-height:normal;font-variant:normal;font-style:normal;font-size:7pt;font-weight:normal;"> </span></span></span><span>减少代码量,简单;</span> </p>    <p class="MsoListParagraph"><span><span>2、<span style="line-height:normal;font-variant:normal;font-style:normal;font-size:7pt;font-weight:normal;"> </span></span></span><span>性能增强;</span> </p>    <p class="MsoListParagraph"><strong><span><span>3、<span style="line-height:normal;font-variant:normal;font-style:normal;font-size:7pt;font-weight:normal;"> </span></span></span></strong><strong><span>Sql</span> </strong><strong><span>语句与程序代码分离;</span> </strong></p>    <p class="MsoListParagraph"><span><span>4、<span style="line-height:normal;font-variant:normal;font-style:normal;font-size:7pt;font-weight:normal;"> </span></span></span><span>增强了移植性;</span> </p>    <p class="MsoNormal"><span>缺点:</span> </p>    <p class="MsoListParagraph"><span><span>1、<span style="line-height:normal;font-variant:normal;font-style:normal;font-size:7pt;font-weight:normal;"> </span></span></span><span>和<span lang="EN-US">Hibernate</span> 相比,<span lang="EN-US">sql</span> 需要自己写;</span> </p>    <p class="MsoListParagraph"><span><span>2、<span style="line-height:normal;font-variant:normal;font-style:normal;font-size:7pt;font-weight:normal;"> </span></span></span><span>参数数量只能有一个,多个参数时不太方便;<br /> <br /> 转自:<a href="/misc/goto?guid=4959500166710054016" target="_blank">Iteye</a>。</span> </p>    <p class="MsoNormal"></p>    <p class="MsoNormal"></p>    <p class="MsoNormal"></p>    <p class="MsoNormal"></p>    <p class="MsoNormal"></p>    <p class="MsoNormal"></p>    <p class="MsoNormal"></p>