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了。
架构分析
DAO层上面,DAO类通过SqlMapConfig文件,来构建iBatis提供的SqlMapClient,SqlMapConfig文件的作用就是:将操作行为以iBatis约定的方式配置到文件中;由iBatis提供的解析类SqlMapClientBuilder来进行解析并构建出SqlMapClient对象,,如下所示:
Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml") sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader) reader.close()
应用层通过SqlMapClient对象来执行之前通过配置文件定义的操作;所以iBatis沿用的是Java第三方框架 一贯沿用的”面向配置”的思路。
iBatis处理提供了一个对象用来执行操作,使得操作更加集中,提高了工作效率之外,还做了一件更重要的事情,就是实现了和DTO互操作,也是就是O/R Mapping。这里的提到了”互操作”是指:iBatis接收DTO的形式作为参数容器,底层采用反射的方式根据命名进行参数映射;另一方面iBatis可以将(查询)结果自动映射到指定的DTO中。
学习案例
项目工程目录图
创建表
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;
这里表格的编码应该为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 { 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 alias="Student" type="com.alibaba.ibatis.dataobject.Student" /> <select id="selectAllStudent" resultClass="Student"> select * from tbl_student </select> <select id="selectStudentById" parameterClass="int" resultClass="Student"> select * from tbl_student where id=#id# </select> <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 </selectKey> </insert> <delete id="deleteStudentById" parameterClass="int"> 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=
创建配置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> <properties resource="sql/sqlmap/SqlMap.properties" /> <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.ibatisTestimport java.sql.Dateimport java.util.Listimport com.alibaba.ibatis.daoimpl.StudentDaoImplimport com.alibaba.ibatis.dataobject.Studentpublic 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介绍及简单示例