1. 新建一个web 项目
2. 复制两个包过到lib下
3. 在src下建立jdbc.properties文件, 内容如下:
# Properties file with JDBC-related settings.
# Applied by PropertyPlaceholderConfigurer from "dataAccessContext-local.xml".
# Targeted at system administrators, to avoid touching the context XML files.
driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://localhost:1433;DatabaseName=school
username=sa
password=sa
4. 建包com.yenange.entity;
5. 做配置文件
6.建Student实体类
package com.yenange.entity;
public class Student {
private Integer sid;
private String sname;
private Integer sage;
public Student() {
}
public Student(Integer sid, String sname, Integer sage) {
this.sid = sid;
this.sname = sname;
this.sage = sage;
}
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public Integer getSage() {
return sage;
}
public void setSage(Integer sage) {
this.sage = sage;
}
}
7.做实体映射文件Student.xml
8.写测试方法
package com.yenange.entity;
import java.io.IOException;
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 StudentDAOTest {
public static void main(String[] args) throws IOException, SQLException {
Reader reader = Resources
.getResourceAsReader("com/yenange/entity/SqlMapConfig.xml");
SqlMapClient sqlmapClient = SqlMapClientBuilder
.buildSqlMapClient(reader);
queryByID(sqlmapClient);
getAllUser(sqlmapClient);
saveUser(sqlmapClient);
updateUser(sqlmapClient);
}
private static void queryByID(SqlMapClient sqlmapClient)
throws SQLException {
Student student=(Student)sqlmapClient.queryForObject("getStudentById", 1001);
System.out.println(student.getSname());
}
private static void saveUser(SqlMapClient sqlmapClient) throws SQLException {
Student student = new Student();
student.setSname("环形");
student.setSage(89);
sqlmapClient.startTransaction();
sqlmapClient.insert("addStudent", student);
sqlmapClient.commitTransaction();
}
private static void updateUser(SqlMapClient sqlmapClient) throws SQLException {
Student student = new Student();
student.setSid(1001);
student.setSname("环形999");
student.setSage(89);
sqlmapClient.startTransaction();
sqlmapClient.insert("addStudent", student);
sqlmapClient.commitTransaction();
}
private static void getAllUser(SqlMapClient sqlmapClient)
throws SQLException {
List<Student> list = sqlmapClient.queryForList("getAllStudent");
for (Student student : list) {
System.out.println(student.getSname());
}
}
}