`
rs_zheng
  • 浏览: 13901 次
社区版块
存档分类
最新评论

iBatis入门

 
阅读更多
  1. iBatis 简介:

iBatis apache 的一个开源项目,一个O/R Mapping 解决方案,iBatis 最大的特点就是小巧,上手很快。如果不需要太多复杂的功能,iBatis 是能够满足你的要求又足够灵活的最简单的解决方案,现在的iBatis 已经改名为Mybatis 了。

官网为:http://www.mybatis.org/

 

搭建iBatis 开发环境:

1 、导入相关的jar 包,ibatis-2.3.0.677.jarmysql-connector-java-5.1.6-bin.jar

2 、编写配置文件:

Jdbc 连接的属性文件

总配置文件, SqlMapConfig.xml

关于每个实体的映射文件(Map 文件)

 

Demo

Student.java:

Java代码 复制代码 收藏代码
  1. package com.iflytek.entity;   
  2.   
  3. import java.sql.Date;   
  4.   
  5.  
  6. public class Student {   
  7.     // 注意这里需要保证有一个无参构造方法,因为包括Hibernate在内的映射都是使用反射的,如果没有无参构造可能会出现问题   
  8.     private int id;   
  9.     private String name;   
  10.     private Date birth;   
  11.     private float score;   
  12.   
  13.     public int getId() {   
  14.         return id;   
  15.     }   
  16.   
  17.     public void setId(int id) {   
  18.         this.id = id;   
  19.     }   
  20.   
  21.     public String getName() {   
  22.         return name;   
  23.     }   
  24.   
  25.     public void setName(String name) {   
  26.         this.name = name;   
  27.     }   
  28.   
  29.     public Date getBirth() {   
  30.         return birth;   
  31.     }   
  32.   
  33.     public void setBirth(Date birth) {   
  34.         this.birth = birth;   
  35.     }   
  36.   
  37.     public float getScore() {   
  38.         return score;   
  39.     }   
  40.   
  41.     public void setScore(float score) {   
  42.         this.score = score;   
  43.     }   
  44.   
  45.     @Override  
  46.     public String toString() {   
  47.         return "id=" + id + "\tname=" + name + "\tmajor=" + birth + "\tscore="  
  48.                 + score + "\n";   
  49.     }   
  50.   
  51. }  

 

SqlMap.properties

Properties代码 复制代码 收藏代码
  1. driver=com.mysql.jdbc.Driver   
  2. url=jdbc:mysql://localhost:3306/ibatis   
  3. username=root   
  4. password=123   

Student.xml

Xml代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"   
  3.    "http://ibatis.apache.org/dtd/sql-map-2.dtd">  
  4.   
  5. <sqlMap>  
  6.     <!-- 通过typeAlias使得我们在下面使用Student实体类的时候不需要写包名 -->  
  7.     <typeAlias alias="Student" type="com.iflytek.entity.Student" />  
  8.   
  9.     <!-- 这样以后改了sql,就不需要去改java代码了 -->  
  10.     <!-- id表示select里的sql语句,resultClass表示返回结果的类型 -->  
  11.     <select id="selectAllStudent" resultClass="Student">  
  12.         select * from   
  13.         tbl_student   
  14.     </select>    
  15.     <!-- parameterClass表示参数的内容 -->  
  16.     <!-- #表示这是一个外部调用的需要传进的参数,可以理解为占位符 -->  
  17.     <select id="selectStudentById" parameterClass="int" resultClass="Student">  
  18.         select * from tbl_student where id=#id#   
  19.     </select>  
  20.   
  21.     <!-- 注意这里的resultClass类型,使用Student类型取决于queryForList还是queryForObject -->  
  22.     <select id="selectStudentByName" parameterClass="String"  
  23.         resultClass="Student">  
  24.         select name,birth,score from tbl_student where name like   
  25.         '%$name$%'   
  26.     </select>  
  27.   
  28.     <insert id="addStudent" parameterClass="Student">  
  29.         insert into   
  30.         tbl_student(name,birth,score) values   
  31.         (#name#,#birth#,#score#);   
  32.         <selectKey resultClass="int" keyProperty="id">  
  33.             select @@identity as inserted   
  34.             <!-- 这里需要说明一下不同的数据库主键的生成,对各自的数据库有不同的方式: -->  
  35.             <!-- mysql:SELECT LAST_INSERT_ID() AS VALUE -->  
  36.             <!-- mssql:select @@IDENTITY as value -->  
  37.             <!-- oracle:SELECT STOCKIDSEQUENCE.NEXTVAL AS VALUE FROM DUAL -->  
  38.             <!-- 还有一点需要注意的是不同的数据库生产商生成主键的方式不一样,有些是预先生成 (pre-generate)主键的,如Oracle和PostgreSQL。    
  39.                 有些是事后生成(post-generate)主键的,如MySQL和SQL Server 所以如果是Oracle数据库,则需要将selectKey写在insert之前 -->  
  40.         </selectKey>  
  41.     </insert>  
  42.   
  43.     <delete id="deleteStudentById" parameterClass="int">  
  44.         <!-- #id#里的id可以随意取,但是上面的insert则会有影响,因为上面的name会从Student里的属性里去查找 -->  
  45.         <!-- 我们也可以这样理解,如果有#占位符,则ibatis会调用parameterClass里的属性去赋值 -->  
  46.         delete from tbl_student where id=#id#   
  47.     </delete>  
  48.   
  49.     <update id="updateStudent" parameterClass="Student">  
  50.         update tbl_student set   
  51.         name=#name#,birth=#birth#,score=#score# where id=#id#   
  52.     </update>  
  53.   
  54. </sqlMap>   

说明:

如果xml 中没有ibatis 的提示,则window --> Preference--> XML-->XML Catalog---> 点击add

选择uri URI: 请选择本地文件系统上

iBatisDemo1/WebContent/WEB-INF/lib/sql-map-config-2.dtd 文件;

Key Type: 选择Schema Location;

Key: 需要联网的,不建议使用;

 

SqlMapConfig.xml

Xml代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"   
  3.     "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">  
  4.   
  5. <sqlMapConfig>  
  6.     <!-- 引用JDBC属性的配置文件 -->  
  7.     <properties resource="com/iflytek/entity/SqlMap.properties" />  
  8.     <!-- 使用JDBC的事务管理 -->  
  9.     <transactionManager type="JDBC">  
  10.         <!-- 数据源 -->  
  11.         <dataSource type="SIMPLE">  
  12.             <property name="JDBC.Driver" value="${driver}" />  
  13.             <property name="JDBC.ConnectionURL" value="${url}" />  
  14.             <property name="JDBC.Username" value="${username}" />  
  15.             <property name="JDBC.Password" value="${password}" />  
  16.         </dataSource>  
  17.     </transactionManager>  
  18.     <!-- 这里可以写多个实体的映射文件 -->  
  19.     <sqlMap resource="com/iflytek/entity/Student.xml" />  
  20. </sqlMapConfig>  

 

StudentDao

Java代码 复制代码 收藏代码
  1. package com.iflytek.dao;   
  2.   
  3. import java.util.List;   
  4.   
  5. import com.iflytek.entity.Student;   
  6.   
  7. public interface StudentDao {   
  8.   
  9.     /**  
  10.      * 添加学生信息  
  11.      *   
  12.      * @param student  
  13.      *            学生实体  
  14.      * @return 返回是否添加成功  
  15.      */  
  16.     public boolean addStudent(Student student);   
  17.   
  18.     /**  
  19.      * 根据学生id删除学生信息  
  20.      *   
  21.      * @param id  
  22.      *            学生id  
  23.      * @return 删除是否成功  
  24.      */  
  25.     public boolean deleteStudentById(int id);   
  26.   
  27.     /**  
  28.      * 更新学生信息  
  29.      *   
  30.      * @param student  
  31.      *            学生实体  
  32.      * @return 更新是否成功  
  33.      */  
  34.     public boolean updateStudent(Student student);   
  35.   
  36.     /**  
  37.      * 查询全部学生信息  
  38.      *   
  39.      * @return 返回学生列表  
  40.      */  
  41.     public List<Student> selectAllStudent();   
  42.   
  43.     /**  
  44.      * 根据学生姓名模糊查询学生信息  
  45.      *   
  46.      * @param name  
  47.      *            学生姓名  
  48.      * @return 学生信息列表  
  49.      */  
  50.     public List<Student> selectStudentByName(String name);   
  51.   
  52.     /**  
  53.      * 根据学生id查询学生信息  
  54.      *   
  55.      * @param id  
  56.      *            学生id  
  57.      * @return 学生对象  
  58.      */  
  59.     public Student selectStudentById(int id);   
  60.   
  61. }  
  1. package com.iflytek.daoimpl;   
  2.   
  3. import java.io.IOException;   
  4. import java.io.Reader;   
  5. import java.sql.SQLException;   
  6. import java.util.List;   
  7.   
  8. import com.ibatis.common.resources.Resources;   
  9. import com.ibatis.sqlmap.client.SqlMapClient;   
  10. import com.ibatis.sqlmap.client.SqlMapClientBuilder;   
  11. import com.iflytek.dao.StudentDao;   
  12. import com.iflytek.entity.Student;   
  13.   
  14. public class StudentDaoImpl implements StudentDao {   
  15.   
  16.     private static SqlMapClient sqlMapClient = null;   
  17.   
  18.     // 读取配置文件   
  19.     static {   
  20.         try {   
  21.             Reader reader = Resources   
  22.                     .getResourceAsReader("com/iflytek/entity/SqlMapConfig.xml");   
  23.             sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);   
  24.             reader.close();   
  25.         } catch (IOException e) {   
  26.             e.printStackTrace();   
  27.         }   
  28.     }   
  29.   
  30.     public boolean addStudent(Student student) {   
  31.         Object object = null;   
  32.         boolean flag = false;   
  33.         try {   
  34.             object = sqlMapClient.insert("addStudent", student);   
  35.             System.out.println("添加学生信息的返回值:" + object);   
  36.         } catch (SQLException e) {   
  37.             e.printStackTrace();   
  38.         }   
  39.         if (object != null) {   
  40.             flag = true;   
  41.         }   
  42.         return flag;   
  43.     }   
  44.   
  45.     public boolean deleteStudentById(int id) {   
  46.         boolean flag = false;   
  47.         Object object = null;   
  48.         try {   
  49.             object = sqlMapClient.delete("deleteStudentById", id);   
  50.             System.out.println("删除学生信息的返回值:" + object + ",这里返回的是影响的行数");   
  51.         } catch (SQLException e) {   
  52.             e.printStackTrace();   
  53.         }   
  54.         if (object != null) {   
  55.             flag = true;   
  56.   
  57.         }   
  58.         return flag;   
  59.   
  60.     }   
  61.   
  62.     public boolean updateStudent(Student student) {   
  63.         boolean flag = false;   
  64.         Object object = false;   
  65.         try {   
  66.             object = sqlMapClient.update("updateStudent", student);   
  67.             System.out.println("更新学生信息的返回值:" + object + ",返回影响的行数");   
  68.         } catch (SQLException e) {   
  69.             e.printStackTrace();   
  70.         }   
  71.         if (object != null) {   
  72.             flag = true;   
  73.         }   
  74.         return flag;   
  75.     }   
  76.   
  77.     public List<Student> selectAllStudent() {   
  78.         List<Student> students = null;   
  79.         try {   
  80.             students = sqlMapClient.queryForList("selectAllStudent");   
  81.         } catch (SQLException e) {   
  82.             e.printStackTrace();   
  83.         }   
  84.         return students;   
  85.     }   
  86.   
  87.     public List<Student> selectStudentByName(String name) {   
  88.         List<Student> students = null;   
  89.         try {   
  90.             students = sqlMapClient.queryForList("selectStudentByName",name);   
  91.         } catch (SQLException e) {   
  92.             e.printStackTrace();   
  93.         }   
  94.         return students;   
  95.     }   
  96.   
  97.     public Student selectStudentById(int id) {   
  98.         Student student = null;   
  99.         try {   
  100.             student = (Student) sqlMapClient.queryForObject(   
  101.                     "selectStudentById", id);   
  102.         } catch (SQLException e) {   
  103.             e.printStackTrace();   
  104.         }   
  105.         return student;   
  106.     }   
  107. }   

TestIbatis.java

Java代码 复制代码 收藏代码
  1. package com.iflytek.test;   
  2.   
  3. import java.sql.Date;   
  4. import java.util.List;   
  5.   
  6. import com.iflytek.daoimpl.StudentDaoImpl;   
  7. import com.iflytek.entity.Student;   
  8.   
  9. public class TestIbatis {   
  10.   
  11.     public static void main(String[] args) {   
  12.         StudentDaoImpl studentDaoImpl = new StudentDaoImpl();   
  13.   
  14.         System.out.println("测试插入");   
  15.         Student addStudent = new Student();   
  16.         addStudent.setName("李四");   
  17.         addStudent.setBirth(Date.valueOf("2011-09-02"));   
  18.         addStudent.setScore(88);   
  19.         System.out.println(studentDaoImpl.addStudent(addStudent));   
  20.   
  21.         System.out.println("测试根据id查询");   
  22.         System.out.println(studentDaoImpl.selectStudentById(1));   
  23.   
  24.         System.out.println("测试模糊查询");   
  25.         List<Student> mohuLists = studentDaoImpl.selectStudentByName("李");   
  26.         for (Student student : mohuLists) {   
  27.             System.out.println(student);   
  28.         }   
  29.   
  30.         System.out.println("测试查询所有");   
  31.         List<Student> students = studentDaoImpl.selectAllStudent();   
  32.         for (Student student : students) {   
  33.             System.out.println(student);   
  34.         }   
  35.   
  36.         System.out.println("根据id删除学生信息");   
  37.         System.out.println(studentDaoImpl.deleteStudentById(1));   
  38.   
  39.         System.out.println("测试更新学生信息");   
  40.         Student updateStudent = new Student();   
  41.         updateStudent.setId(1);   
  42.         updateStudent.setName("李四1");   
  43.         updateStudent.setBirth(Date.valueOf("2011-08-07"));   
  44.         updateStudent.setScore(21);   
  45.         System.out.println(studentDaoImpl.updateStudent(updateStudent));   
  46.   
  47.     }   
  48. }  

iBatis 的优缺点:

优点:

1、减少代码量,简单;

2、性能增强;

3、Sql 语句与程序代码分离;

4、增强了移植性;

缺点:

1、Hibernate 相比,sql 需要自己写;

2、参数数量只能有一个,多个参数时不太方便;

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics