ibatis实践
1.iBatis的总配置文件是sqlMapConfig.xml,其代码如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig
PUBLIC"-//ibatis.apache.org//DTDSQLMapConfig2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd"><sqlMapConfig>
<!-- 加载属性文件-->
<propertiesresource="com/ibatis/sqlMap.properties"/>
<settings
cacheModelsEnabled="true"
enhancementEnabled="true"
lazyLoadingEnabled="true"
maxRequests="128"
maxSessions="10"
maxTransactions="5"
useStatementNamespaces="true"
defaultStatementTimeout="15"
statementCachingEnabled="true"
classInfoCacheEnabled="true"
/>
<transactionManagertype="JDBC">
<dataSourcetype="SIMPLE">
<propertyname="JDBC.Driver"value="${driver}"/>
<propertyname="JDBC.ConnectionURL"value="${url}"/>
<propertyname="JDBC.Username"value="${username}"/>
<propertyname="JDBC.Password"value="${password}"/>
</dataSource>
</transactionManager><!-- 加载sqlmap -->
<sqlMapresource="com/ibatis/Student.xml"/>
</sqlMapConfig>2.属性文件sqlMap.properties是配置数据库的文件,其代码如下:
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
username=crws
password=crws3.sqlMap文件Student.xml是具体的sql语句,其代码如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPEsqlMap
PUBLIC"-//ibatis.apache.org//DTDSQLMap2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMapnamespace="Student">
<typeAliasalias="Student"type="com.ibatis.Student"/>
<!--
<resultMapclass=""id="">
<resultproperty=""column=""/>
</resultMap>
-->
<!--查询所有记录-->
<selectid="selectAllStudent"resultclass="Student">
<!--
id代表下面的sql语句;resultClass的值Student代表com.ibatis.Student
-->
select*fromSTUDENT
</select>
<!--查询指定id的记录-->
<selectid="selectStudentById"parameterclass="int"resultclass="Student">
<!--
parameterClass代表要输入值的类型
-->
select*fromSTUDENTwheresid=#sid#
</select>
<!--插入一条记录-->
<insertid="insertStudent"parameterclass="Student">
insertintoSTUDENT(sid,sname,major,birth,score)
values(#sid#,#sname#,#major#,#birth#,#score#)
<!--
此处的#sid#不能写成#id#,因为此处没有getId()方法。
-->
</insert>
<!--删除指定id的记录-->
<deleteid="deleteStudentById"parameterclass="int">
deletefromSTUDENTwheresid=#sid#
<!--
此处的#sid#能写成#id#,因为只是作为参数传递的。
-->
</delete>
<!--修改记录-->
<updateid="updateStudent"parameterclass="Student">
updateSTUDENTset
sname=#sname#,
major=#major#,
birth=#birth#,
score=#score#
wheresid=#sid#
</update>
<!--模糊查询-->
<!--注意查询时的格式'%$...$%'-->
<selectid="selectStudentByName"parameterclass="String"resultclass="Student">
select*fromSTUDENT
wheresnamelike'%$sname$%'
</select>
<!--根据主键序列插入记录-->
<insertid="insertStudentBySequence"parameterclass="Student">
<selectKeyresultclass="int"keyProperty="sid">
selectstudentPKSequence.nextValfromdual
</selectKey>
insertintoSTUDENT(sid,sname,major,birth,score)
values(#sid#,#sname#,#major#,#birth#,#score#)
</insert>
</sqlMap>4.编写实体类Student.java,其代码如下:
package com.ibatis;
import java.util.Date;
public class Student {
//要保证有无参数的构造方法
privateintsid;
privateStringsname;
privateStringmajor;
privateDatebirth;
privateStringscore;
publicDategetBirth(){
returnbirth;
}
publicvoidsetBirth(Datebirth){
this.birth=birth;
}
publicStringgetMajor(){
returnmajor;
}
publicvoidsetMajor(Stringmajor){
this.major=major;
}
publicStringgetScore(){
returnscore;
}
publicvoidsetScore(Stringscore){
this.score=score;
}
publicintgetSid(){
returnsid;
}
publicvoidsetSid(intsid){
this.sid=sid;
}
publicStringgetSname(){
returnsname;
}
publicvoidsetSname(Stringsname){
this.sname=sname;
}
publicStringtoString(){
Stringcontent="sid:"+sid+"\tsname:"+sname+"\tmajor:"+major+"\tbirth:"+birth+"\tscore:"+score;
returncontent;
}
}
5.编写dao文件,其代码如下:package com.ibatis;
import java.util.List;
public interface IStudentDAO {
publicvoidaddStudent(Students);
publicvoidaddStudentBySequence(Students);
publicvoiddeleteStudentById(intid);
publicvoidupdateStudent(Students);
publicList<Student>queryAllStudent();
publicList<Student>queryStudentByName(Stringname);
publicStudentqueryStudentById(intid);
}6.编写dao实现类文件,其代码如下:
package com.ibatis;
import java.io.IOException;
importjava.io.Reader;
importjava.sql.SQLException;
importjava.util.List;
import java.sql.Date;import com.ibatis.common.resources.Resources;
importcom.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;public class IStudentDAOImpl implements IStudentDAO {
private static SqlMapClient sqlMapClient = null;
static{
try{
Stringresource="com/ibatis/sqlMapConfig.xml";
Readerreader=Resources.getResourceAsReader(resource);
sqlMapClient=SqlMapClientBuilder.buildSqlMapClient(reader);
reader.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
publicvoidaddStudent(Students){
//TODOAuto-generatedmethodstub
try{
sqlMapClient.insert("insertStudent",s);
}catch(SQLExceptione){
e.printStackTrace();
}
}public void addStudentBySequence(Student s) {
//TODOAuto-generatedmethodstub
//step1:从数据库序列中获取主键值
//step2:插入
try{
sqlMapClient.insert("insertStudentBySequence",s);
//插入成功,打印出结果
System.out.println(s.getSid());
}catch(SQLExceptione){
e.printStackTrace();
}
}public void deleteStudentById(int id) {
//TODOAuto-generatedmethodstub
try{
System.out.println(sqlMapClient.delete("deleteStudentById",id));
//删除操作返回影响的行数的数目
}catch(SQLExceptione){
e.printStackTrace();
}
}public List<Student> queryAllStudent() {
List<Student>studentList=null;
try{
studentList = sqlMapClient.queryForList("Student.selectAllStudent");//当使用namespace时,必须指定如上的格式
}catch(SQLExceptione){
e.printStackTrace();
}
returnstudentList;
}public Student queryStudentById(int id) {
//TODOAuto-generatedmethodstub
Students=null;
try{
s=(Student)sqlMapClient.queryForObject("selectStudentById",id);
}catch(SQLExceptione){
e.printStackTrace();
}
returns;
}public List<Student> queryStudentByName(String name) {
//TODOAuto-generatedmethodstub
List<Student>studentList=null;
try{
studentList=sqlMapClient.queryForList("selectStudentByName",name);
}catch(SQLExceptione){
e.printStackTrace();
}
returnstudentList;
}public void updateStudent(Student s) {
//TODOAuto-generatedmethodstub
try{
System.out.println(sqlMapClient.update("updateStudent",s));
//更改操作返回影响的行数的数目
}catch(SQLExceptione){
e.printStackTrace();
}
}
publicstaticvoidmain(String[]args){
IStudentDAOdao=newIStudentDAOImpl();
//删除指定id的学生
//dao.deleteStudentById(100);
//查询所有的学生
for(Studentstudent:dao.queryAllStudent()){
System.out.println(student);
}
//查询一个指定的学生
//System.out.println(dao.queryStudentById(1));
//增加一个学生
//Students=newStudent();
//s.setSid(100);
//s.setSname("li");
//s.setMajor("English");
//s.setBirth(Date.valueOf("2009-09-09"));
//s.setScore("90");
//dao.addStudent(s);
//更改学生
//Students=newStudent();
//s.setSid(1);
//s.setSname("li");
//s.setMajor("English");
//s.setBirth(Date.valueOf("2009-09-09"));
//s.setScore("90");
//dao.updateStudent(s);
//模糊查询
//for(Studentstudent:dao.queryStudentByName("i")){
//System.out.println(student);
//}
//通过序列插入数据
//Students=newStudent();
//s.setSid(1);
//s.setSname("li");
//s.setMajor("English");
//s.setBirth(Date.valueOf("2009-09-09"));
//s.setScore("90");
// dao.addStudentBySequence(s);}
}
短短几个文件,就构成了ibatis的简单应用,可以看到ibatis是轻量级的数据持久化方法,掌握也比较容易!