ibatis新手入门

来源:互联网 发布:ubuntu 双显卡 编辑:程序博客网 时间:2024/05/17 02:34

ibatis 是什么

iBATIS是以SQL为中心的持久化层框架。能支持懒加载、关联查询、继承等特性。 
iBATIS不同于一般的OR映射框架。OR映射框架,将数据库表、字段等映射到类、属性,那是一种元数据(meta-data)映射。iBATIS则是将SQL查询的参数和结果集映射到类。所以,iBATIS做的是SQL Mapping的工作。 
它把SQL语句看成输入以及输出,结果集就是输出,而where后面的条件参数则是输入。iBATIS能将输入的普通POJO对象、Map、XML等映射到SQL的条件参数上,同时也可以将查询结果映射到普通POJO对象(集合)、Map、XML等上面。iBATIS使用xml文件来映射这些输入以及输出。

环境搭建

  • eclipse+maven
  • mysql服务器安装,参见帖子:MySQL 5.6 for Windows 解压缩版配置安装
  • 写一个java程序来测试jdbc驱动:Eclipse连接MySQL数据库 
    至此,ibatis的基本环境就ok了。

架构分析

ibatis架构 
DAO层上面,DAO类通过SqlMapConfig文件,来构建iBatis提供的SqlMapClient,SqlMapConfig文件的作用就是:将操作行为以iBatis约定的方式配置到文件中;由iBatis提供的解析类SqlMapClientBuilder来进行解析并构建出SqlMapClient对象,,如下所示:

Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");            sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);            reader.close();
  • 1
  • 2
  • 3

应用层通过SqlMapClient对象来执行之前通过配置文件定义的操作;所以iBatis沿用的是Java第三方框架 一贯沿用的”面向配置”的思路。 
iBatis处理提供了一个对象用来执行操作,使得操作更加集中,提高了工作效率之外,还做了一件更重要的事情,就是实现了和DTO互操作,也是就是O/R Mapping。这里的提到了”互操作”是指:iBatis接收DTO的形式作为参数容器,底层采用反射的方式根据命名进行参数映射;另一方面iBatis可以将(查询)结果自动映射到指定的DTO中。

学习案例

项目工程目录图

ibatistest工程目录图

创建表

mysql创建表格语句如下:

CREATE TABLE `tbl_student` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `name` char(255) CHARACTER SET utf8 DEFAULT NULL,  `birth` date DEFAULT NULL,  `score` float DEFAULT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=latin1;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

这里表格的编码应该为utf-8,否则后面插入中文字符会出现乱码,后面会解决这个问题。

首先配置maven的pom文件,导入依赖:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <groupId>com.alibaba.ibatisTest</groupId>    <artifactId>ibatisTest</artifactId>    <version>0.0.1-SNAPSHOT</version>    <dependencies>        <dependency>            <groupId>junit</groupId>            <artifactId>junit</artifactId>            <version>3.8.1</version>            <scope>test</scope>        </dependency>        <dependency>            <groupId>org.apache.ibatis</groupId>            <artifactId>ibatis-sqlmap</artifactId>            <version>2.3.0</version>        </dependency>        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>            <version>5.1.35</version>        </dependency>    </dependencies></project>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

创建dataobject

package com.alibaba.ibatis.dataobject;import java.sql.Date;/** * @Title: Student.java * @Prject: ibatisTest * @Package: com.alibaba.ibatis.dataobject * @Description: TODO * @author: andy.zy   * @date: 2015年7月3日 上午11:23:18 * @version: V1.0  */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";    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62

创建dao接口:

package com.alibaba.ibatis.dao;import java.util.List;import com.alibaba.ibatis.dataobject.Student;/** * @Title: StudentDao.java * @Prject: ibatisTest * @Package: com.alibaba.ibatis.dao * @Description: TODO * @author: andy.zy   * @date: 2015年7月3日 上午11:24:21 * @version: V1.0  */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);}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70

创建daoimpl

package com.alibaba.ibatis.daoimpl;import java.io.IOException;import java.io.Reader;import java.sql.SQLException;import java.util.List;import com.alibaba.ibatis.dao.StudentDao;import com.alibaba.ibatis.dataobject.Student;import com.ibatis.common.resources.Resources;import com.ibatis.sqlmap.client.SqlMapClient;import com.ibatis.sqlmap.client.SqlMapClientBuilder;/** * @Title: StudentDaoImpl.java * @Prject: ibatisTest * @Package: com.alibaba.ibatis.daoimpl * @Description: TODO * @author: andy.zy   * @date: 2015年7月3日 上午10:07:51 * @version: V1.0  */public class StudentDaoImpl implements StudentDao {    private static SqlMapClient sqlMapClient = null;    // 读取配置文件    static {        try {            Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");            sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);            reader.close();        } catch (IOException e) {            e.printStackTrace();        }    }    @Override    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;    }    @SuppressWarnings("unchecked")    public List<Student> selectAllStudent() {        List<Student> students = null;        try {            students = sqlMapClient.queryForList("selectAllStudent");        } catch (SQLException e) {            e.printStackTrace();        }        return students;    }    @SuppressWarnings("unchecked")    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;    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115

创建关联的DAO 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.alibaba.ibatis.dataobject.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 -->            <!-- mysql: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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51

创建关联的Properties文件

driver=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/testusername=rootpassword=
  • 1
  • 2
  • 3
  • 4

创建配置sqlMapConfig

<?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="sql/sqlmap/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="sql/sqlmap/Student.xml" /></sqlMapConfig>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

以上就配置好了,写测试用例,来测试增删改查的操作:

package com.alibaba.ibatisTest;import java.sql.Date;import java.util.List;import com.alibaba.ibatis.daoimpl.StudentDaoImpl;import com.alibaba.ibatis.dataobject.Student;/** * @Title: TestStudent.java * @Prject: ibatisTest * @Package: com.alibaba.ibatisTest * @Description: TODO * @author: andy.zy   * @date: 2015年7月3日 上午11:30:33 * @version: V1.0  */public class TestStudent {    public static void main(String[] args) {        StudentDaoImpl studentDaoImpl = new StudentDaoImpl();        System.out.println("测试插入");        Student addStudent = new Student();        addStudent.setName("zhangsan");        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(6));        System.out.println("测试模糊查询");        List<Student> mohuLists = studentDaoImpl.selectStudentByName("zhang");        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(6);        updateStudent.setName("lisi");        updateStudent.setBirth(Date.valueOf("2011-08-07"));        updateStudent.setScore(21);        System.out.println(studentDaoImpl.updateStudent(updateStudent));    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51

运行结果如下:

测试插入添加学生信息的返回值:15true测试根据id查询id=6    name=lisi   major=2011-08-07    score=21.0测试模糊查询id=0    name=zhangsan   major=2011-08-07    score=21.0id=0    name=zhangsan   major=2011-09-02    score=88.0测试查询所有id=6    name=lisi   major=2011-08-07    score=21.0id=8    name=zhangsan   major=2011-08-07    score=21.0id=9    name=lisi   major=2011-09-02    score=88.0id=10   name=lisi   major=2011-09-02    score=88.0id=11   name=lisi   major=2011-09-02    score=88.0id=12   name=lisi   major=2011-09-02    score=88.0id=13   name=lisi   major=2011-09-02    score=88.0id=14   name=lisi   major=2011-09-02    score=88.0id=15   name=zhangsan   major=2011-09-02    score=88.0根据id删除学生信息删除学生信息的返回值:0,这里返回的是影响的行数true测试更新学生信息更新学生信息的返回值:1,返回影响的行数true
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

总结和参考资源

  • 注意xml文件中的路径的配置问题,很多其他博客里面会存在xml文件中没有空格等问题
  • iBatis入手案例
  • ibatis的简单入门教程
  • ata内网入门教程
  • ibatis英文简单入门教程
  • iBATIS介绍及简单示例
原创粉丝点击