很多人都倾向于使用Hibernate,个人觉得,如果做个小项目的话,显得也比较的繁琐,Ibatis相对来说会更灵活一点。
下面就来介绍Ibatis的用法:
1、首先去下载Ibatis的jar包,https://code.google.com/p/mybatis/wiki/Downloads?tm=2,Ibatis从3.x开始就叫Mybatis了,新版本有很多更使用的改进,有兴趣的话可以去了解,我这里用的是ibatis-2.3.0.67版本的。
2、接下来就是配置属性文件和.xml文件了:
SqlMap.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=ibatis
password=123456
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="cg/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="cg/entity/Student.xml" />
</sqlMapConfig>
每个实体要建一个对应的xml文件
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="cg.entity.Student" />
<!-- 这样以后改了sql,就不需要去改java代码了 -->
<!-- id表示select里的sql语句,resultClass表示返回结果的类型 -->
<select id="selectAllStudent" resultClass="Student">
select * from student
</select>
<!-- parameterClass表示参数的内容 -->
<!-- #表示这是一个外部调用的需要传进的参数,可以理解为占位符 -->
<select id="selectStudentById" parameterClass="int" resultClass="Student">
select * from student where id=#id#
</select>
<!-- 模糊查询 -->
<select id="selectStudentByName" parameterClass="String" resultClass="Student">
select id,name from student where name like '%$name$%'
</select>
<!-- 插入 -->
<insert id="addStudent" parameterClass="Student">
insert into student(name)
values(#name#);
<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 student where id=#id#
</delete>
<!-- 修改 -->
<update id="updateStudent" parameterClass="Student">
update student set name=#name# where id=#id#
</update>
<!-- 联表查询测试 -->
<select id="selectCombine" parameterClass="int" resultClass="Student">
select student.name,grade.grades from student,grade where student.id=grade.sid and grade.cid=#cid#
</select>
</sqlMap>
实体类:Student.java
package cg.entity;
public class Student {
private int id;
private String name;
private int cid;
private int grades;
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 int getCid() {
return cid;
}
public void setCid(int cid) {
this.cid = cid;
}
public int getGrades() {
return grades;
}
public void setGrades(int grades) {
this.grades = grades;
}
}
测试类:TestIbatis.java
package cg.test;
import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import cg.entity.Student;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
public class TestIbatis {
private static SqlMapClient sqlMapClient = null;
static{
Reader reader;
try {
reader = Resources.getResourceAsReader("SqlMapConfig.xml");
sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public List<Student> queryAllStudent() throws SQLException{
List<Student> studentList = null;
studentList = sqlMapClient.queryForList("selectAllStudent");
return studentList;
}
public Student queryStudentById(int id) throws SQLException{
Student s = new Student();
s = (Student) sqlMapClient.queryForObject("selectStudentById", id);
return s;
}
public Student queryStudentByName(String name) throws SQLException{
Student s = new Student();
s = (Student) sqlMapClient.queryForObject("selectStudentByName", name);
return s;
}
public boolean insert(Student s){
Object o = null;
boolean flag = false;
try {
o = sqlMapClient.insert("addStudent", s);
System.out.println("添加信息返回的值:"+o);
} catch (SQLException e) {
e.printStackTrace();
}
if(o != null){
flag = true;
}
return flag;
}
public boolean deleteStudentById(int id){
boolean flag = false;
Object o = null;
try {
o = sqlMapClient.delete("deleteStudentById", id);
System.out.println("删除学生信息返回的值:"+o+"这里返回的是受影响的行数");
} catch (SQLException e) {
e.printStackTrace();
}
if(o != null){
flag = true;
}
return flag;
}
public boolean updateStudentById(Student s){
boolean flag = false;
Object o = null;
try {
o = sqlMapClient.update("updateStudent", s);
System.out.println("返回的值为:"+o);
} catch (SQLException e) {
e.printStackTrace();
}
if(o != null){
flag = true;
}
return flag;
}
public static void main(String[] args){
TestIbatis t = new TestIbatis();
//测试全部查询
// try {
// Student s = t.queryStudentById(1);
// System.out.println(s.getName());
// List<Student> stlist = t.queryAllStudent();
// Iterator<Student> it = stlist.iterator();
// while(it.hasNext()){
// Student st = it.next();
// System.out.println(st.getName());
// }
// } catch (SQLException e) {
// e.printStackTrace();
// }
//测试模糊查询
// try {
// System.out.println(t.queryStudentByName("刘").getName());
// } catch (SQLException e) {
// e.printStackTrace();
// }
//测试添加
// Student s = new Student();
// s.setName("刘诗诗");
// System.out.println(t.insert(s));
//测试删除
// System.out.println(t.deleteStudentById(5));
//测试更新
Student s = new Student();
s.setName("诗诗");
s.setId(6);
System.out.println(t.updateStudentById(s));
}
}
测试联表查询的类:TestIbatis2.java
package cg.test;
import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import cg.entity.Student;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
public class TestIbatis2 {
private static SqlMapClient sqlMapClient = null;
static{
try {
Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//联表查询
public List<Student> queryList(int cid){
List<Student> stuList = null;
try {
stuList = sqlMapClient.queryForList("selectCombine", cid);
} catch (SQLException e) {
e.printStackTrace();
}
return stuList;
}
public List<Map<Object,Object>> toList(List<Student> list){
Iterator<Student> it = list.iterator();
List<Map<Object,Object>> mapList = new ArrayList<Map<Object,Object>>();
while(it.hasNext()){
Student stu = it.next();
Map m = new LinkedHashMap();
m.put("x", stu.getName());
m.put("y", stu.getGrades());
mapList.add(m);
}
return mapList;
}
public static void main(String[] args){
TestIbatis2 t = new TestIbatis2();
List<Student> stuList = t.queryList(1);
Iterator<Student> it = stuList.iterator();
while(it.hasNext()){
Student stu = it.next();
System.out.println("姓名:"+stu.getName()+" ,成绩:"+stu.getGrades());
}
System.out.println(t.toList(t.queryList(1)).size());
}
}