iBatis入門教程

fmms 12年前發布 | 106K 次閱讀 MyBatis3 持久層框架 iBATIS

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:

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";
    }

}

SqlMap.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/ibatis
username=root
password=123

Student.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使得我們在下面使用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>

說明:

如果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 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>

StudentDao

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);

}

StudentDaoImpl

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;
    }
}

TestIbatis.java

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));

    }
}

iBatis 的優缺點:

優點:

1、 減少代碼量,簡單;

2、 性能增強;

3、 Sql 語句與程序代碼分離;

4、 增強了移植性;

缺點:

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

2、 參數數量只能有一個,多個參數時不太方便;

轉自:Iteye

 本文由用戶 fmms 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!