ibatis入門實例(完整)


一:首先展示一下我的web文件結構,首先導入Ibatis所需jar和數據庫驅動,從第二步開始跟着筆者一步步來

二:數據庫建測試表

CREATE TABLE STUDENT (
ID NUMBER(5),
NAME VARCHAR2(10),
SEX VARCHAR2(10),
AGE NUMBER(10),
ADDRESS VARCHAR2(10),
CONSTRAINT PK_ID PRIMARY KEY(ID)
);

三:創建SqlMapConfig.xml文件

<?xml version="1.0" encoding="UTF-8" ?>  
<!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"  "http://www.ibatis.com/dtd/sql-map-config-2.dtd">  
<sqlMapConfig>  
  
    <properties resource="SqlMapConfig.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="sqlMap_student.xml" />  
  
</sqlMapConfig>  

四:創建SqlMapConfig.properties,將用戶名和密碼改成自己的

driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:orcl
username=ynsb1  
password=1 

五 創建sqlMap_student.xml映射文件,注意parameterClass要改成自己的pojo類

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://www.ibatis.com/dtd/sql-map-2.dtd">  
  
<sqlMap namespace="Test">  
  
    <statement id="insert_student"  
        parameterClass="com.shangcg.ibatis.StudentDto">  
        insert into student(  
        id,name,age,sex,address) values(  
        #id#,#name#,#age#,#sex#,#address# )  
    </statement>  
  
    <statement id="delete_all_student" 
        parameterClass="com.shangcg.ibatis.StudentDto">  
        delete from student  
    </statement>  
  
    <statement id="deleteByID_student"   
        parameterClass="com.shangcg.ibatis.StudentDto">  
        delete from student where   
        id = #id#  
    </statement>  
      
    <statement id="updataStudent_test"   
        parameterClass="com.shangcg.ibatis.StudentDto">  
        update student set   
        name=#name#,sex=#sex#,age=#age#,address=#address#   
        where id = #id#  
    </statement>    
      
    <statement id="select_all_student"  
        resultClass="com.shangcg.ibatis.StudentDto">  
        select * from student order by id  
    </statement>  
      
    <statement id="selectByID_student"  
        parameterClass="com.shangcg.ibatis.StudentDto"  
        resultClass="com.shangcg.ibatis.StudentDto">  
        select * from student   
        where id = #id#   
        order by id  
    </statement>        
</sqlMap>  

 

 六:配置文件創建完成,接下來創建java類

1)創建StudentDto

import java.sql.Date;

public class StudentDto {
    // 注意這里需要保證有一個無參構造方法,因為包括Hibernate在內的映射都是使用反射的,如果沒有無參構造可能會出現問題
     //學生ID   
    private int id = 0;  
    //學生姓名   
    private String name = "";  
    //學生性別   
    private String sex = "";  
    //學生年齡   
    private int age = 0;  
    //學生地址   
    private String address = "";
    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 String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }  

    
}

2)創建接口StudentDao

import java.util.ArrayList;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.shangcg.ibatis.StudentDto;

public interface StudentDao {

     //添加student表的數據   
    public void addStudent(SqlMapClient sqlMap,StudentDto studentdto);  
    //刪除student表的數據   
    public void delStudent(SqlMapClient sqlMap);  
    //刪除student表的指定ID數據   
    public void delStudentByID(SqlMapClient sqlMap,StudentDto studentdto);  
    //更新student表的數據   
    public void updataStudent(SqlMapClient sqlMap,StudentDto studentdto);  
    //查詢student表的所有數據   
    public ArrayList selectStudent(SqlMapClient sqlMap);  
    //查詢student表的指定ID數據   
    public StudentDto selectStudentByID(SqlMapClient sqlMap,StudentDto studentdto); 
}

3)創建實現類StudentImpl

import java.sql.SQLException;
import java.util.ArrayList;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.shangcg.ibatis.StudentDto;
import com.shangcg.interfaces.StudentDao;

public class StudentImpl implements StudentDao {

     //添加student表的數據   
    public void addStudent(SqlMapClient sqlMap, StudentDto studentdto) {  
  
        try {  
            sqlMap.insert("insert_student", studentdto);  
        } catch (SQLException e) {  
  
            e.printStackTrace();  
        }  
    }  
      
    //刪除student表的數據   
    public void delStudent(SqlMapClient sqlMap) {  
  
        try {  
            sqlMap.delete("delete_all_student", null);  
        } catch (SQLException e) {  
  
            e.printStackTrace();  
        }  
    }  
  
    //刪除student表的指定ID數據   
    public void delStudentByID(SqlMapClient sqlMap, StudentDto studentdto) {  
  
        try {  
            sqlMap.delete("deleteByID_student",studentdto );  
        } catch (SQLException e) {  
  
            e.printStackTrace();  
        }  
    }  
  
    //更新student表的數據   
    public void updataStudent(SqlMapClient sqlMap, StudentDto studentdto) {  
  
        try {  
            sqlMap.update("updataStudent_test",studentdto );  
        } catch (SQLException e) {  
  
            e.printStackTrace();  
        }  
    }  
      
    //查詢student表的所有數據   
    public ArrayList selectStudent(SqlMapClient sqlMap) {  
  
        //保存查詢結果   
        ArrayList rsList = new ArrayList();  
  
        try {  
            rsList = (ArrayList)sqlMap.queryForList("select_all_student","");  
        } catch (SQLException e) {  
  
            e.printStackTrace();  
        }  
        return rsList;  
    }  
  
    //查詢student表的指定ID數據   
    public StudentDto selectStudentByID(SqlMapClient sqlMap, StudentDto studentdto) {  
  
        //返回后保存在info中   
        StudentDto info = new StudentDto();  
        try {  
            info = (StudentDto)sqlMap.queryForObject("selectByID_student", studentdto);  
        } catch (SQLException e) {  
  
            e.printStackTrace();  
        }  
        return info;  
    }  
  

}

4)創建MainTest 測試類

import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.shangcg.ibatis.StudentDto;
import com.shangcg.impl.StudentImpl;

public class MainTest {

     public StudentImpl impl = new StudentImpl();  
        public StudentDto info = new StudentDto();  
        public static SqlMapClient sqlmapclient = null;  
        static {  
            try {  
                //讀取xml文件   
                Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");  
                sqlmapclient = SqlMapClientBuilder.buildSqlMapClient(reader);  
                reader.close();  
            } catch (IOException e) {  
      
                e.printStackTrace();  
            }  
        }  
          
        public static void main(String []args){  
            MainTest stu = new MainTest();  
              
            System.out.println("------------------------------- start ------------------------------");  
              
            //以下為各種方法測試   
              
            //添加student表的數據   
            stu.addStudent_test();   
              
            //刪除student表的數據   
            //stu.delStudent_test();   
              
            //刪除student表的指定ID數據   
            //stu.delStudentByID_test();   
              
            //更新student表的數據   
            //stu.updataStudent_test();   
              
            //查詢student表的所有數據   
            //stu.selectStudent_test();   
              
            //查詢student表的所有數據   
            //stu.selectStudentByID_test();   
              
            System.out.println("-------------------------------  end  ------------------------------");  
          
        }  
          
        //添加student表的數據   
        public void addStudent_test(){  
              
            //把要插入的數據填入info對象中   
            info.setId(5);  
            info.setName("zh2208");  
            info.setSex("男");  
            info.setAge(24);  
            info.setAddress("上海");  
              
            impl.addStudent(sqlmapclient, info);  //參數就是sqlMap_student.xml中配置對應的id
        }  
          
        //刪除student表的數據   
        public void delStudent_test(){  
            impl.delStudent(sqlmapclient);  
        }  
          
        //刪除student表的指定ID數據   
        public void delStudentByID_test(){  
            //指定ID   
            info.setId(1);  
            impl.delStudentByID(sqlmapclient,info);  
              
        }  
          
        //更新student表的數據   
        public void updataStudent_test(){  
              
            //把要更新的數據填入info對象中   
            info.setId(6);  
            info.setName("zh2208up");  
            info.setSex("男");  
            info.setAge(20);  
            info.setAddress("上海up");  
            impl.updataStudent(sqlmapclient, info);  
        }  
          
        //查詢student表的所有數據   
        public void selectStudent_test(){  
              
            StudentDto stu_dto = new StudentDto();  
            //檢索結果保存到list中   
            ArrayList resultList = impl.selectStudent(sqlmapclient);  
            for(int i = 0; i < resultList.size();i++){  
                stu_dto = (StudentDto) resultList.get(i);  
                //打印對象中的信息   
                show(stu_dto);  
            }  
              
        }  
          
        //查詢student表的指定ID數據   
        public void selectStudentByID_test(){  
            StudentDto stu_dto = new StudentDto();  
            info.setId(1);  
            stu_dto = impl.selectStudentByID(sqlmapclient,info);  
      
            if(stu_dto != null){  
                show(stu_dto);  
            }else{  
                System.out.println("no data!!!!");  
            }  
        }  
          
        //打印查詢結果   
        public void show(StudentDto stu_dto){  
      
            System.out.print("學生ID :" + stu_dto.getId() + " ; ");  
            System.out.print("學生姓名 :" + stu_dto.getName() + " ; ");  
            System.out.print("學生性別 :" + stu_dto.getSex() + " ; ");  
            System.out.print("學生年齡 :" + stu_dto.getAge() + " ; ");  
            System.out.print("學生地址 :" + stu_dto.getAddress());  
            System.out.println();  
          
        }  
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM