第一步:创建Java工程或者web工程,同时在工程目录下创建lib目录,并将ibatis工作包ibatis-2.3.4.726.jar和数据库驱动例如:mysql-connector-java-5.1.7-bin.jar拷贝到lib目录下
第二步:创建数据库,创建脚本如下:
DROP TABLE IF EXISTS person;
CREATE TABLE person (
id int(8) NOT NULL AUTO_INCREMENT,
username varchar(32) NOT NULL,
password varchar(32) NOT NULL,
PRIMARY KEY (id))
ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=gbk;
第三步:在工程目录下构建数据库配置连接文件:SqlMapConfig.xml,具体内容如下:
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
第四步:在工程目录下构建数据库表操作配置文件:PersonSqlMap.xml,具体内容如下:
PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">
insert into person (
username,
password
)
values (
#username#, #password#
)
update person set
username = #username#,
password = #password#
where
id = #id#
delete from person where id = #id#
第五步:构建数据封装类文件:Person.java,具体内容如下:
package com;
public class Person {
private int id;
private String username;
private String password;
public Person() {
// 注意:这里无参构造函数必须要要,否则会抛空指针异常
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
String str = "ID:" + id + "/t用户名:" + username + "/t密码:" + password;
return str;
}
}
第六步:构建数据库操作、静态工厂创建、测试类文件:OperateDatabase.java,具体内容如下:
package com;
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;
public class OperateDatabase {
private static SqlMapClient sqlMapClient;
// 静态加载配置文件
static {
try {
Reader reader = Resources.getResourceAsReader("./SqlMapConfig.xml");
sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 创建新用户
public static void insertPerson(Person person) throws SQLException {
sqlMapClient.insert("insertPerson", person);
}
// 删除用户
public static void deletePersonById(int id) throws SQLException {
sqlMapClient.delete("deletePersonById", id);
}
// 查询用户
@SuppressWarnings("unchecked")
public static List
List
return personList;
}
// 更新用户
public static void updatePersonById(Person person) throws SQLException {
sqlMapClient.update("updatePersonById", person);
}
public static void main(String[] args) throws Exception {
// 插入新的用户
Person per = new Person();
per.setUsername("zhangwenhai");
per.setPassword("456789234");
insertPerson(per);
// 按id删除用户
deletePersonById(4);
// 查询所有的用户
for (Person person : selectAllPerson()) {
System.out.println(person);
}
// 按id更新用户
Person pp = new Person();
pp.setId(1);
pp.setUsername("wangfeiyan");
pp.setPassword("996432");
updatePersonById(pp);
}
}
到这里一个用ibatis来实现增删查改的功能已经全部实现了......