您的位置:首页 > 其它

iBatis简单入门教程

2013-06-09 22:18 537 查看

iBatis简单入门教程

iBatis简介:

iBatis是apache的一个开源项目,一个O/RMapping解决方案,iBatis最大的特点就是小巧,上手很快。如果不需要太多复杂的功能,iBatis是能够满足你的要求又足够灵活的最简单的解决方案,现在的iBatis已经改名为Mybatis了。

官网为:http://www.mybatis.org/

搭建iBatis开发环境:

1、导入相关的jar包,ibatis-2.3.0.677.jar、mysql-connector-java-5.1.6-bin.jar

2、编写配置文件:

Jdbc连接的属性文件

总配置文件,SqlMapConfig.xml

关于每个实体的映射文件(Map文件)

Demo:

Student.java:

Java代码






packagecom.iflytek.entity;

importjava.sql.Date;

/**
*@authorxudongwang2011-12-31
*
*Email:xdwangiflytek@gmail.com
*
*/
publicclassStudent{
//注意这里需要保证有一个无参构造方法,因为包括Hibernate在内的映射都是使用反射的,如果没有无参构造可能会出现问题
privateintid;
privateStringname;
privateDatebirth;
privatefloatscore;

publicintgetId(){
returnid;
}

publicvoidsetId(intid){
this.id=id;
}

publicStringgetName(){
returnname;
}

publicvoidsetName(Stringname){
this.name=name;
}

publicDategetBirth(){
returnbirth;
}

publicvoidsetBirth(Datebirth){
this.birth=birth;
}

publicfloatgetScore(){
returnscore;
}

publicvoidsetScore(floatscore){
this.score=score;
}

@Override
publicStringtoString(){
return"id="+id+"\tname="+name+"\tmajor="+birth+"\tscore="
+score+"\n";
}

}



SqlMap.properties:

Properties代码





driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/ibatis
username=root
password=123



Student.xml:

Xml代码






<?xml
version="1.0"
encoding="UTF-8"?>

<!DOCTYPEsqlMapPUBLIC"-//ibatis.apache.org//DTDSQLMap2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap>
<!--通过typeAlias使得我们在下面使用Student实体类的时候不需要写包名-->
<typeAlias
alias="Student"
type="com.iflytek.entity.Student"
/>


<!--这样以后改了sql,就不需要去改java代码了-->
<!--id表示select里的sql语句,resultClass表示返回结果的类型-->
<select
id="selectAllStudent"
resultClass="Student">

select*from
tbl_student
</select>

<!--parameterClass表示参数的内容-->
<!--#表示这是一个外部调用的需要传进的参数,可以理解为占位符-->
<select
id="selectStudentById"
parameterClass="int"
resultClass="Student">

select*fromtbl_studentwhereid=#id#
</select>

<!--注意这里的resultClass类型,使用Student类型取决于queryForList还是queryForObject-->
<select
id="selectStudentByName"
parameterClass="String"
resultClass="Student">

selectname,birth,scorefromtbl_studentwherenamelike
'%$name$%'
</select>

<insert
id="addStudent"
parameterClass="Student">

insertinto
tbl_student(name,birth,score)values
(#name#,#birth#,#score#);
<selectKey
resultClass="int"
keyProperty="id">

select@@identityasinserted
<!--这里需要说明一下不同的数据库主键的生成,对各自的数据库有不同的方式:-->
<!--mysql:SELECTLAST_INSERT_ID()ASVALUE-->
<!--mssql:select@@IDENTITYasvalue-->
<!--oracle:SELECTSTOCKIDSEQUENCE.NEXTVALASVALUEFROMDUAL-->
<!--还有一点需要注意的是不同的数据库生产商生成主键的方式不一样,有些是预先生成(pre-generate)主键的,如Oracle和PostgreSQL。

有些是事后生成(post-generate)主键的,如MySQL和SQLServer所以如果是Oracle数据库,则需要将selectKey写在insert之前-->

</selectKey>
</insert>

<delete
id="deleteStudentById"
parameterClass="int">

<!--#id#里的id可以随意取,但是上面的insert则会有影响,因为上面的name会从Student里的属性里去查找-->
<!--我们也可以这样理解,如果有#占位符,则ibatis会调用parameterClass里的属性去赋值-->
deletefromtbl_studentwhereid=#id#
</delete>

<update
id="updateStudent"
parameterClass="Student">

updatetbl_studentset
name=#name#,birth=#birth#,score=#score#where
id=#id#
</update>

</sqlMap>

说明:

如果xml中没有ibatis的提示,则window-->Preference-->XML-->XMLCatalog--->点击add

选择uriURI:请选择本地文件系统上

iBatisDemo1/WebContent/WEB-INF/lib/sql-map-config-2.dtd文件;

KeyType:选择SchemaLocation;

Key:需要联网的,不建议使用;

SqlMapConfig.xml:

Xml代码






<?xml
version="1.0"
encoding="UTF-8"?>

<!DOCTYPEsqlMapConfigPUBLIC"-//ibatis.apache.org//DTDSQLMapConfig2.0//EN"

"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

<sqlMapConfig>
<!--引用JDBC属性的配置文件-->
<properties
resource="com/iflytek/entity/SqlMap.properties"
/>
<!--使用JDBC的事务管理-->
<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="com/iflytek/entity/Student.xml"
/>
</sqlMapConfig>

StudentDao:

Java代码






packagecom.iflytek.dao;

importjava.util.List;

importcom.iflytek.entity.Student;

/**
*@authorxudongwang2011-12-31
*
*Email:xdwangiflytek@gmail.com
*
*/
publicinterfaceStudentDao{

/**
*添加学生信息
*
*@paramstudent
*学生实体
*@return返回是否添加成功
*/
publicbooleanaddStudent(Studentstudent);

/**
*根据学生id删除学生信息
*
*@paramid
*学生id
*@return删除是否成功
*/
publicbooleandeleteStudentById(intid);

/**
*更新学生信息
*
*@paramstudent
*学生实体
*@return更新是否成功
*/
publicbooleanupdateStudent(Studentstudent);

/**
*查询全部学生信息
*
*@return返回学生列表
*/
publicList<Student>selectAllStudent();

/**
*根据学生姓名模糊查询学生信息
*
*@paramname
*学生姓名
*@return学生信息列表
*/
publicList<Student>selectStudentByName(Stringname);

/**
*根据学生id查询学生信息
*
*@paramid
*学生id
*@return学生对象
*/
publicStudentselectStudentById(intid);

}


StudentDaoImpl:

Java代码






packagecom.iflytek.daoimpl;

importjava.io.IOException;
importjava.io.Reader;
importjava.sql.SQLException;
importjava.util.List;

importcom.ibatis.common.resources.Resources;
importcom.ibatis.sqlmap.client.SqlMapClient;
importcom.ibatis.sqlmap.client.SqlMapClientBuilder;
importcom.iflytek.dao.StudentDao;
importcom.iflytek.entity.Student;

/**
*@authorxudongwang2011-12-31
*
*Email:xdwangiflytek@gmail.com
*
*/
publicclassStudentDaoImplimplementsStudentDao{

privatestaticSqlMapClientsqlMapClient=null;

//读取配置文件
static{
try{
Readerreader=Resources
.getResourceAsReader("com/iflytek/entity/SqlMapConfig.xml");
sqlMapClient=SqlMapClientBuilder.buildSqlMapClient(reader);
reader.close();
}catch(IOExceptione){
e.printStackTrace();
}
}

publicbooleanaddStudent(Studentstudent){
Objectobject=null;
booleanflag=false;
try{
object=sqlMapClient.insert("addStudent",student);
System.out.println("添加学生信息的返回值:"+object);
}catch(SQLExceptione){
e.printStackTrace();
}
if(object!=null){
flag=true;
}
returnflag;
}

publicbooleandeleteStudentById(intid){
booleanflag=false;
Objectobject=null;
try{
object=sqlMapClient.delete("deleteStudentById",id);
System.out.println("删除学生信息的返回值:"+object+",这里返回的是影响的行数");
}catch(SQLExceptione){
e.printStackTrace();
}
if(object!=null){
flag=true;

}
returnflag;

}

publicbooleanupdateStudent(Studentstudent){
booleanflag=false;
Objectobject=false;
try{
object=sqlMapClient.update("updateStudent",student);
System.out.println("更新学生信息的返回值:"+object+",返回影响的行数");
}catch(SQLExceptione){
e.printStackTrace();
}
if(object!=null){
flag=true;
}
returnflag;
}

publicList<Student>selectAllStudent(){
List<Student>students=null;
try{
students=sqlMapClient.queryForList("selectAllStudent");
}catch(SQLExceptione){
e.printStackTrace();
}
returnstudents;
}

publicList<Student>selectStudentByName(Stringname){
List<Student>students=null;
try{
students=sqlMapClient.queryForList("selectStudentByName",name);
}catch(SQLExceptione){
e.printStackTrace();
}
returnstudents;
}

publicStudentselectStudentById(intid){
Studentstudent=null;
try{
student=(Student)sqlMapClient.queryForObject(
"selectStudentById",id);
}catch(SQLExceptione){
e.printStackTrace();
}
returnstudent;
}
}



TestIbatis.java:

Java代码






packagecom.iflytek.test;

importjava.sql.Date;
importjava.util.List;

importcom.iflytek.daoimpl.StudentDaoImpl;
importcom.iflytek.entity.Student;

/**
*@authorxudongwang2011-12-31
*
*Email:xdwangiflytek@gmail.com
*
*/
publicclassTestIbatis{

publicstaticvoidmain(String[]args){
StudentDaoImplstudentDaoImpl=newStudentDaoImpl();

System.out.println("测试插入");
StudentaddStudent=newStudent();
addStudent.setName("李四");
addStudent.setBirth(Date.valueOf("2011-09-02"));
addStudent.setScore(88);
System.out.println(studentDaoImpl.addStudent(addStudent));

System.out.println("测试根据id查询");
System.out.println(studentDaoImpl.selectStudentById(1));

System.out.println("测试模糊查询");
List<Student>mohuLists=studentDaoImpl.selectStudentByName("李");
for(Studentstudent:mohuLists){
System.out.println(student);
}

System.out.println("测试查询所有");
List<Student>students=studentDaoImpl.selectAllStudent();
for(Studentstudent:students){
System.out.println(student);
}

System.out.println("根据id删除学生信息");
System.out.println(studentDaoImpl.deleteStudentById(1));

System.out.println("测试更新学生信息");
StudentupdateStudent=newStudent();
updateStudent.setId(1);
updateStudent.setName("李四1");
updateStudent.setBirth(Date.valueOf("2011-08-07"));
updateStudent.setScore(21);
System.out.println(studentDaoImpl.updateStudent(updateStudent));

}
}



iBatis的优缺点:

优点:

1、减少代码量,简单;

2、性能增强;

3、Sql语句与程序代码分离;

4、增强了移植性;

缺点:

1、和Hibernate相比,sql需要自己写;

2、参数数量只能有一个,多个参数时不太方便;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: