ibaits 入門案例及原始碼
Ibaits學習總結
1. 搭建環境:匯入相關的jar包
Ø 匯入oracle驅動jar包
Ø 匯入ibaits驅動jar包
2. 配置檔案
Ø Jdbc連結屬性檔案,如 SqlMap.properties檔案
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
username=ibaits
password=ibaits
Ø 總配置檔案,如 SqlMapConfig.xml 檔案
<sqlMapConfig>
<!--
連結屬性檔案
<properties resource="com/hdw/conf/SqlMap.properties"/>
<!-- jdbc事務管理 -->
<transactionManagertype="JDBC" >
<!-- 資料來源 -->
<dataSourcetype="SIMPLE">
<!-- EL表示式引用屬性檔案SqlMap.properties裡面的值 -->
<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>
<!-- 連結對映檔案Students.xml讀取表的資訊 -->
<sqlMapresource="com/hdw/conf/Students.xml"/>
</sqlMapConfig>
Ø 關於每個實體的對映檔案(map檔案)如:Students.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 namespace="Student">
<typeAlias alias="Student"type="com.hdw.dao.Student"/>
<resultMap id="StudentResult"class="Student">
<result property="sid"column="SID" />
<result property="sname"column="SNAME"/>
<result property="major"column="MAJOR"/>
<result property="birth"column="BIRTH"/>
<result property="score"column="SCORE"/>
</resultMap>
<!-- Select with no parameters using the result mapfor Account class. -->
<select id="queryAllStudent"resultMap="StudentResult">
select * from STUDENT
</select>
</sqlMap>
注:1、resultMap屬於直接對映,可以把結果集中的資料庫欄位與實體類中的屬性一一對應,這樣通過select語句得到的結果就會準確的對上號
2、resultclass屬於隱身對映,雖然你指定resultclass=“”,具體某一個類,但是select語句得到的結果是一條實力記錄,但如果資料庫欄位與類的屬性名字不一致,這個時候就會出現對映錯誤,有一種方式可以解決就是在寫select語句時,給每個欄位用as運算子取名字與屬性一樣:例如:select realname as name...其中realname是欄位列名,name是屬性欄位名
3、resultmap比resultclass效能要高。儘量使用resultmap
3. 讀取配置
public staticSqlMapClient sqlMapClient = null;
static
{
try
{
//從類路徑中載入sqlmap配置檔案
Reader reader = Resources.getResourceAsReader("com/hdw/conf/SqlMapConfig.xml");
//建立SqlMapClient介面的變數例項
sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
reader.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
4. 基本的CRUD操作
5.
Ibaits
優缺點
優點:與JDBC相比較
l
減少的60%的程式碼量
l
簡單
l
架構及效能強
l
Sql
語句與程式碼分離
l
簡化專案的分工
l
增強了移植性
缺點:
l
需要手動新增sql語句
l
引數數量只有一個
java程式碼實現:
StudentDAOImp.java實現類
package com.hdw.sever.serverImp;
import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.util.List;
import com.hdw.dao.Student;
import com.hdw.sever.StudentDAO;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
publicclass StudentDAOImpimplements StudentDAO
{
publicstatic SqlMapClient sqlMapClient = null;
String QUERY_ALL_STUDENT = "queryAllStudent";
static
{
try
{
//從類路徑中載入sqlmap配置檔案
Readerreader = Resources.getResourceAsReader("com/hdw/conf/SqlMapConfig.xml");
//建立SqlMapClient介面的變數例項
sqlMapClient =SqlMapClientBuilder.buildSqlMapClient(reader);
reader.close();
}
catch (IOException e)
{
// TODOAuto-generated catch block
e.printStackTrace();
}
}
@Override
publicList<Student> queryAllStudent()
{
List<Student>studentList = null;
try
{
studentList= sqlMapClient.queryForList(QUERY_ALL_STUDENT);
}
catch (SQLExceptione)
{
e.printStackTrace();
}
return studentList;
}
}
StudentDAO.java介面類
package com.hdw.sever;
import java.util.List;
import com.hdw.dao.Student;
public interface StudentDAO
{
publicList<Student> queryAllStudent();
}
Student.java 資料例項類
package com.hdw.dao;
import java.util.Date;
publicclass Student
{
privateintsid;
private String sname;
private String major;
private Date birth;
privatefloatscore;
publicint getSid() {
returnsid;
}
publicvoid setSid(int sid) {
this.sid = sid;
}
public StringgetSname() {
returnsname;
}
publicvoid setSname(Stringsname) {
this.sname = sname;
}
public StringgetMajor() {
returnmajor;
}
publicvoid setMajor(Stringmajor) {
this.major = major;
}
public Date getBirth(){
returnbirth;
}
publicvoid setBirth(Datebirth) {
this.birth = birth;
}
publicfloat getScore() {
returnscore;
}
publicvoid setScore(float score) {
this.score = score;
}
@Override
public StringtoString() {
Stringcontent = "sid="+sid+"\tsname="+sname+"\tmajor="+major+"\tbirth="+birth+"\tscore="+score;
return content;
}
}
MyDoMain.java測試類
package com.hdw.mydata;
import java.util.List;
import com.hdw.dao.Student;
import com.hdw.sever.StudentDAO;
import com.hdw.sever.serverImp.StudentDAOImp;
publicclass MyDoMain
{
/**
* @param args
*/
publicstaticvoid main(String[]args)
{
// TODOAuto-generated method stub
StudentDAOstudentdao = new StudentDAOImp();
List<Student> listStudent = studentdao.queryAllStudent();
for(Studentstudent:listStudent)
{
System.out.println(student);
}
}
}
Ibaits入門案例
SqlMap.properties 檔案
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@127.0.0.1:1521:ORCL
username=ibaits
password=ibaits
SqlMapConfig.xml檔案
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig
PUBLIC"-//ibatis.apache.org//DTD SQL Map Config2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<properties resource="com/hdw/conf/SqlMap.properties"/>
<transactionManager type="JDBC"commitRequired="false" >
<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="com/hdw/conf/Students.xml"/>
</sqlMapConfig>
Students.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 namespace="Student">
<typeAlias alias="Student"type="com.hdw.dao.Student"/>
<resultMap id="StudentResult" class="Student">
<result property="sid" column="SID"/>
<result property="sname" column="SNAME"/>
<result property="major" column="MAJOR"/>
<result property="birth" column="BIRTH"/>
<result property="score" column="SCORE"/>
</resultMap>
<!-- Select with no parameters using the result mapfor Student class. -->
<select id="queryAllStudent" resultMap="StudentResult">
select * from STUDENT
</select>
<!-- Select with parameters using the result map for Student class,"parameterClass"is type of passing parameters, not case-sensitive
"resultMap" is type of return result, "#" is placeholder-->
<select id="queryStudentById" parameterClass="int" resultMap="StudentResult">
select sid,sname,major,birth,scorefrom STUDENT where sid=#sid#
</select>
<!-- insert a student object -->
<insert id="addStudent" parameterClass="Student">
insert into STUDENT(
sid,
sname,
major,
birth,
score
)
values(
#sid#,#sname#,#major#,#birth#,#score#
)
</insert>
<!-- delete student by id -->
<delete id="deleteStudentById" parameterClass="int">
delete from STUDENT where sid=#sid#
</delete>
<!-- update student by id -->
<update id="updateStudentById" parameterClass="Student">
update STUDENT set sname=#sname#,
major=#major#,
birth=#birth#,
score=#score#
where sid=#sid#
</update>
<!-- selectstudent by name , "$" is placeholder not "#"-->
<select id="selectStudentByName" parameterClass="String" resultMap="StudentResult">
select * from STUDENT where snamelike '%$sname$%'
</select>
<!-- atomatic generation of primary keys ,"keyProperty" is parameter of java object -->
<insert id="addStudentBySequence" parameterClass="Student">
<selectKey resultClass="int" keyProperty="sid">
select studentpksequence.nextValfrom dual
</selectKey>
insert into STUDENT(
sid,
sname,
major,
birth,
score
)
values(
#sid#,#sname#,#major#,#birth#,#score#
)
</insert>
</sqlMap>
資料實體類 Student.java
package com.hdw.dao;
import java.util.Date;
publicclass Student
{
privateintsid;
private String sname;
private String major;
private Date birth;
privatefloatscore;
publicint getSid() {
returnsid;
}
publicvoid setSid(int sid) {
this.sid = sid;
}
public String getSname() {
returnsname;
}
publicvoid setSname(String sname) {
this.sname = sname;
}
public String getMajor() {
returnmajor;
}
publicvoid setMajor(String major) {
this.major = major;
}
public Date getBirth() {
returnbirth;
}
publicvoid setBirth(Date birth) {
this.birth = birth;
}
publicfloat getScore() {
returnscore;
}
publicvoid setScore(float score) {
this.score = score;
}
@Override
public String toString() {
String content = "sid="+sid+"\tsname="+sname+"\tmajor="+major+"\tbirth="+birth+"\tscore="+score;
return content;
}
}
介面類 StudentDAO.java
package com.hdw.sever;
import java.util.List;
importcom.hdw.dao.Student;
public interfaceStudentDAO
{
public void addStudent(Student student);
public void addStudentBySequence(Student student);
public void deleteStudentById(int sid);
public void updateStudentById(Student student);
public List<Student> queryAllStudent();
public List<Student> queryStudentByName(String sname);
public Student queryStudentById(int sid);
}
實現類StudentDAOImp.java
package com.hdw.sever.serverImp;
importjava.io.IOException;
import java.io.Reader;
importjava.sql.SQLException;
import java.util.List;
importcom.hdw.dao.Student;
importcom.hdw.sever.StudentDAO;
importcom.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
importcom.ibatis.sqlmap.client.SqlMapClientBuilder;
public class StudentDAOImpimplements StudentDAO
{
public static SqlMapClient sqlMapClient = null;
String QUERY_ALL_STUDENT = "queryAllStudent";
String QUERY_STUDENT_BYID = "queryStudentById";
String ADD_STUDENT ="addStudent";
String DELETE_STUDENT_BYID = "deleteStudentById";
String UPDATE_STUDENT_BYID = "updateStudentById";
String SELECT_STUDENT_BYNAME = "selectStudentByName";
String ADD_STUDENT_BYSEQUENCE = "addStudentBySequence";
static
{
try
{
//從類路徑中載入sqlmap配置檔案
Reader reader =Resources.getResourceAsReader("com/hdw/conf/SqlMapConfig.xml");
//建立SqlMapClient介面的變數例項
sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
reader.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void addStudent(Student student)
{
try
{
sqlMapClient.insert(ADD_STUDENT,student);
}
catch(SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void addStudentBySequence(Student student)
{
try
{
sqlMapClient.insert(ADD_STUDENT_BYSEQUENCE,student);
System.out.println("generated ID numberatomatically, sid = "+student.getSid());
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void deleteStudentById(int sid)
{
try
{
int flag =sqlMapClient.delete(DELETE_STUDENT_BYID,sid);
if( flag > 0)
{
System.out.println("deleted successfully,delete message " +flag+" .");
}
else
{
System.out.println("thismessage don't exist, delete failed .");
}
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void updateStudentById(Student student)
{
try
{
int updateFlag =sqlMapClient.update(UPDATE_STUDENT_BYID,student);
if( updateFlag > 0)
{
System.out.println("update successfully,update message is " +student.toString()+" .");
}
else
{
System.out.println("thismessage don't exist, updated failed .");
}
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}