一、iBATIS简介:
iBATIS一词来源于“internet”和“abatis”的组合,是一个由Clinton Begin在2001年发起的开放源代码项目。最初侧重于密码软件的开发,现在是一个基于Java的持久层框架ibatis本是apache的一个开源项目,2010年这个项目由apache software foundation 迁移到了google code,并且改名为mybatis。
二、建立Java Project
三、导jar包:ibatis-2.3.4.726.jar
四、entity,同时需要相关的实体类xml文件
1.Classes类
package org.e276.entity;
public class Classes {
private Integer id;
private String name;
private String beginDate;
private String endDate;
//构造方法
public Classes() {
super();
}
public Classes(Integer id) {
super();
this.id = id;
}
public Classes(Integer id, String name, String beginDate, String endDate) {
super();
this.id = id;
this.name = name;
this.beginDate = beginDate;
this.endDate = endDate;
}
//getter/setter
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBeginDate() {
return beginDate;
}
public void setBeginDate(String beginDate) {
this.beginDate = beginDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
}
2.Students类
package org.e276.entity;
public class Students {
private Integer id;
private String name;
private Integer age;
private Classes classes;
// 构造方法
public Students() {
super();
}
public Students(String name, Integer age, Classes classes) {
super();
this.name = name;
this.age = age;
this.classes = classes;
}
// getter/setter
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Classes getClasses() {
return classes;
}
public void setClasses(Classes classes) {
this.classes = classes;
}
@Override
public String toString() {
return "Students [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
3.Students.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "sql-map-2.dtd"> <sqlMap namespace="me"> <typeAlias alias="Students" type="org.e276.entity.Students" /> <typeAlias alias="Classes" type="org.e276.entity.Classes" /> <!-- 学生类,多对一,如果列名和属性名完全一样,则不用映射 --> <resultMap class="Students" id="StudentsResult"> <result property="id" column="id" /> <result property="name" column="name" /> <result property="age" column="age" /> <result property="classes" column="class_id" select="getClassesById" /> </resultMap> <!-- 班级类 --> <resultMap class="Classes" id="ClassesResult"> <result property="id" column="id" /> <result property="name" column="name" /> <result property="beginDate" column="begin_date" /> <result property="endDate" column="end_date" /> </resultMap> <!-- 如果名不同,则必须加上as,通过id查找班级 --> <select id="getClassesById" parameterClass="int" resultMap="ClassesResult"> select * from classes where id = #value# </select> <!-- 查找所有的学生 --> <select id="getAllStudents" resultMap="StudentsResult"> select * from students </select> <!-- 根据id得到当前班级所有的学生 --> <select id="getStudentsByClassId" resultClass="Students" parameterClass="int"> <![CDATA[ select id, name, age, class_id from students where class_id = #value# ]]> </select> <!-- 插入学生 --> <insert id="saveStudent" parameterClass="Students"> <!-- 注意Oracle中的id是以序列的形式插入,不能省略id这一列 --> <![CDATA[ insert into students values(students_seq.nextval,#name#, #age#, #classes.id#) ]]> <!-- 返回主键 --> <selectKey resultClass="int" keyProperty="id"> <!-- Oracle中的写法:select 序列名.currval as id from dual --> <![CDATA[ select students_seq.currval as id from dual ]]> </selectKey> </insert> <!-- 多表联接查询,查询学生表和班级表 --> <select id="selectStudentsAndClasses" resultClass="java.util.HashMap"> <![CDATA[ select s.id as sid, s.name as sname, s.age as sage, c.name as cname from students s inner join classes c on s.class_id = c.id ]]> </select> </sqlMap>
五、测试类(使用单元测试)
package org.e276.test;
import java.io.Reader;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.e276.entity.Classes;
import org.e276.entity.Students;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
public class TestStudents {
SqlMapClient sqlMapper;
@Before
public void setUp() throws Exception {
Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
// 得到SqlMapClient接口对象
sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader);
// 关闭对象
reader.close();
}
@After
public void tearDown() throws Exception {
sqlMapper = null;
}
/**
* 通过id查找班级
*
* @throws SQLException
*/
public void getClassesById() throws SQLException {
@SuppressWarnings("unchecked")
List<Classes> classes = sqlMapper.queryForList("getClassesById", 2);
for (Classes clazz : classes) {
System.out.println("班级名:" + clazz.getName());
}
}
/**
* 查找所有的学生
*
* @throws SQLException
*/
public void getAllStudents() throws SQLException {
@SuppressWarnings("unchecked")
List<Students> students = sqlMapper.queryForList("getAllStudents");
for (Students stus : students) {
System.out.println(stus);
}
}
/**
* 查询班级ID为3的学生信息
*
* @throws SQLException
*/
public void getStudentsByClassId() throws SQLException {
@SuppressWarnings("unchecked")
List<Students> stuList = sqlMapper.queryForList("getStudentsByClassId", 3);
for (Students students : stuList) {
System.out.println(students);
}
}
/**
* 插入一个学生记录
*
* @throws SQLException
*/
public void saveStudent() throws SQLException {
Students student = new Students("李某某", 32, new Classes(2));
int id = (Integer) sqlMapper.insert("saveStudent", student);
System.out.println(id);
}
/**
* 多表联接,查询学生表和班级表
*
* @throws SQLException
*/
@Test
public void selectStudentsAndClasses() throws SQLException {
@SuppressWarnings("unchecked")
List<Map<String, Object>> result = sqlMapper.queryForList("selectStudentsAndClasses");
for (Map<String, Object> map : result) {
System.out.println("序号:" + map.get("SID"));
System.out.println("学生姓名:" + map.get("SNAME"));
System.out.println("年龄:" + map.get("SAGE"));
System.out.println("班级名:" + map.get("CNAME"));
System.out.println("-------------");
}
}
}
六、iBatis的配置文件 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> <!-- Configure a built-in transaction manager. If you're using an app server, you probably want to use its transaction manager and a managed datasource --> <transactionManager type="JDBC" commitRequired="false"> <dataSource type="SIMPLE"> <property name="JDBC.Driver" value="oracle.jdbc.driver.OracleDriver"/> <property name="JDBC.ConnectionURL" value="jdbc:oracle:thin:@localhost:1521:orcl"/> <property name="JDBC.Username" value="y2"/> <property name="JDBC.Password" value="bdqn"/> </dataSource> </transactionManager> <!-- List the SQL Map XML files. They can be loaded from the classpath, as they are here (com.domain.data...) --> <sqlMap resource="org/e276/entity/Students.xml"/> <!-- List more here... <sqlMap resource="com/mydomain/data/Order.xml"/> <sqlMap resource="com/mydomain/data/Documents.xml"/> --> </sqlMapConfig>
七、demo