iBatis入门实例

转自:http://xdwangiflytek.iteye.com/blog/1332520


iBatis简介:

iBatis是apache的一个开源项目,一个O/R Mapping解决方案,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代码 收藏代码
  1. packagecom.iflytek.entity;
  2. importjava.sql.Date;
  3. /**
  4. *@authorxudongwang2011-12-31
  5. *
  6. *Email:xdwangiflytek@gmail.com
  7. *
  8. */
  9. publicclassStudent{
  10. //注意这里需要保证有一个无参构造方法,因为包括Hibernate在内的映射都是使用反射的,如果没有无参构造可能会出现问题
  11. privateintid;
  12. privateStringname;
  13. privateDatebirth;
  14. privatefloatscore;
  15. publicintgetId(){
  16. returnid;
  17. }
  18. publicvoidsetId(intid){
  19. this.id=id;
  20. }
  21. publicStringgetName(){
  22. returnname;
  23. }
  24. publicvoidsetName(Stringname){
  25. this.name=name;
  26. }
  27. publicDategetBirth(){
  28. returnbirth;
  29. }
  30. publicvoidsetBirth(Datebirth){
  31. this.birth=birth;
  32. }
  33. publicfloatgetScore(){
  34. returnscore;
  35. }
  36. publicvoidsetScore(floatscore){
  37. this.score=score;
  38. }
  39. @Override
  40. publicStringtoString(){
  41. return"id="+id+"\tname="+name+"\tmajor="+birth+"\tscore="
  42. +score+"\n";
  43. }
  44. }

SqlMap.properties:

Properties代码 收藏代码
  1. driver=com.mysql.jdbc.Driver
  2. url=jdbc:mysql://localhost:3306/ibatis
  3. username=root
  4. password=123

Student.xml:

Xml代码 收藏代码
  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <!DOCTYPEsqlMapPUBLIC"-//ibatis.apache.org//DTDSQLMap2.0//EN"
  3. "http://ibatis.apache.org/dtd/sql-map-2.dtd">
  4. <sqlMap>
  5. <!--通过typeAlias使得我们在下面使用Student实体类的时候不需要写包名-->
  6. <typeAliasalias="Student"type="com.iflytek.entity.Student"/>
  7. <!--这样以后改了sql,就不需要去改java代码了-->
  8. <!--id表示select里的sql语句,resultClass表示返回结果的类型-->
  9. <selectid="selectAllStudent"resultClass="Student">
  10. select*from
  11. tbl_student
  12. </select>
  13. <!--parameterClass表示参数的内容-->
  14. <!--#表示这是一个外部调用的需要传进的参数,可以理解为占位符-->
  15. <selectid="selectStudentById"parameterClass="int"resultClass="Student">
  16. select*fromtbl_studentwhereid=#id#
  17. </select>
  18. <!--注意这里的resultClass类型,使用Student类型取决于queryForList还是queryForObject-->
  19. <selectid="selectStudentByName"parameterClass="String"
  20. resultClass="Student">
  21. selectname,birth,scorefromtbl_studentwherenamelike
  22. '%$name$%'
  23. </select>
  24. <insertid="addStudent"parameterClass="Student">
  25. insertinto
  26. tbl_student(name,birth,score)values
  27. (#name#,#birth#,#score#);
  28. <selectKeyresultClass="int"keyProperty="id">
  29. select@@identityasinserted
  30. <!--这里需要说明一下不同的数据库主键的生成,对各自的数据库有不同的方式:-->
  31. <!--mysql:SELECTLAST_INSERT_ID()ASVALUE-->
  32. <!--mssql:select@@IDENTITYasvalue-->
  33. <!--oracle:SELECTSTOCKIDSEQUENCE.NEXTVALASVALUEFROMDUAL-->
  34. <!--还有一点需要注意的是不同的数据库生产商生成主键的方式不一样,有些是预先生成(pre-generate)主键的,如Oracle和PostgreSQL。
  35. 有些是事后生成(post-generate)主键的,如MySQL和SQLServer所以如果是Oracle数据库,则需要将selectKey写在insert之前-->
  36. </selectKey>
  37. </insert>
  38. <deleteid="deleteStudentById"parameterClass="int">
  39. <!--#id#里的id可以随意取,但是上面的insert则会有影响,因为上面的name会从Student里的属性里去查找-->
  40. <!--我们也可以这样理解,如果有#占位符,则ibatis会调用parameterClass里的属性去赋值-->
  41. deletefromtbl_studentwhereid=#id#
  42. </delete>
  43. <updateid="updateStudent"parameterClass="Student">
  44. updatetbl_studentset
  45. name=#name#,birth=#birth#,score=#score#whereid=#id#
  46. </update>
  47. </sqlMap>

说明:

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

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

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

Key Type:选择Schema Location;

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

SqlMapConfig.xml:

Xml代码 收藏代码
  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <!DOCTYPEsqlMapConfigPUBLIC"-//ibatis.apache.org//DTDSQLMapConfig2.0//EN"
  3. "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
  4. <sqlMapConfig>
  5. <!--引用JDBC属性的配置文件-->
  6. <propertiesresource="com/iflytek/entity/SqlMap.properties"/>
  7. <!--使用JDBC的事务管理-->
  8. <transactionManagertype="JDBC">
  9. <!--数据源-->
  10. <dataSourcetype="SIMPLE">
  11. <propertyname="JDBC.Driver"value="${driver}"/>
  12. <propertyname="JDBC.ConnectionURL"value="${url}"/>
  13. <propertyname="JDBC.Username"value="${username}"/>
  14. <propertyname="JDBC.Password"value="${password}"/>
  15. </dataSource>
  16. </transactionManager>
  17. <!--这里可以写多个实体的映射文件-->
  18. <sqlMapresource="com/iflytek/entity/Student.xml"/>
  19. </sqlMapConfig>

StudentDao:

Java代码 收藏代码
  1. packagecom.iflytek.dao;
  2. importjava.util.List;
  3. importcom.iflytek.entity.Student;
  4. /**
  5. *@authorxudongwang2011-12-31
  6. *
  7. *Email:xdwangiflytek@gmail.com
  8. *
  9. */
  10. publicinterfaceStudentDao{
  11. /**
  12. *添加学生信息
  13. *
  14. *@paramstudent
  15. *学生实体
  16. *@return返回是否添加成功
  17. */
  18. publicbooleanaddStudent(Studentstudent);
  19. /**
  20. *根据学生id删除学生信息
  21. *
  22. *@paramid
  23. *学生id
  24. *@return删除是否成功
  25. */
  26. publicbooleandeleteStudentById(intid);
  27. /**
  28. *更新学生信息
  29. *
  30. *@paramstudent
  31. *学生实体
  32. *@return更新是否成功
  33. */
  34. publicbooleanupdateStudent(Studentstudent);
  35. /**
  36. *查询全部学生信息
  37. *
  38. *@return返回学生列表
  39. */
  40. publicList<Student>selectAllStudent();
  41. /**
  42. *根据学生姓名模糊查询学生信息
  43. *
  44. *@paramname
  45. *学生姓名
  46. *@return学生信息列表
  47. */
  48. publicList<Student>selectStudentByName(Stringname);
  49. /**
  50. *根据学生id查询学生信息
  51. *
  52. *@paramid
  53. *学生id
  54. *@return学生对象
  55. */
  56. publicStudentselectStudentById(intid);
  57. }

StudentDaoImpl:

Java代码 收藏代码
  1. packagecom.iflytek.daoimpl;
  2. importjava.io.IOException;
  3. importjava.io.Reader;
  4. importjava.sql.SQLException;
  5. importjava.util.List;
  6. importcom.ibatis.common.resources.Resources;
  7. importcom.ibatis.sqlmap.client.SqlMapClient;
  8. importcom.ibatis.sqlmap.client.SqlMapClientBuilder;
  9. importcom.iflytek.dao.StudentDao;
  10. importcom.iflytek.entity.Student;
  11. /**
  12. *@authorxudongwang2011-12-31
  13. *
  14. *Email:xdwangiflytek@gmail.com
  15. *
  16. */
  17. publicclassStudentDaoImplimplementsStudentDao{
  18. privatestaticSqlMapClientsqlMapClient=null;
  19. //读取配置文件
  20. static{
  21. try{
  22. Readerreader=Resources
  23. .getResourceAsReader("com/iflytek/entity/SqlMapConfig.xml");
  24. sqlMapClient=SqlMapClientBuilder.buildSqlMapClient(reader);
  25. reader.close();
  26. }catch(IOExceptione){
  27. e.printStackTrace();
  28. }
  29. }
  30. publicbooleanaddStudent(Studentstudent){
  31. Objectobject=null;
  32. booleanflag=false;
  33. try{
  34. object=sqlMapClient.insert("addStudent",student);
  35. System.out.println("添加学生信息的返回值:"+object);
  36. }catch(SQLExceptione){
  37. e.printStackTrace();
  38. }
  39. if(object!=null){
  40. flag=true;
  41. }
  42. returnflag;
  43. }
  44. publicbooleandeleteStudentById(intid){
  45. booleanflag=false;
  46. Objectobject=null;
  47. try{
  48. object=sqlMapClient.delete("deleteStudentById",id);
  49. System.out.println("删除学生信息的返回值:"+object+",这里返回的是影响的行数");
  50. }catch(SQLExceptione){
  51. e.printStackTrace();
  52. }
  53. if(object!=null){
  54. flag=true;
  55. }
  56. returnflag;
  57. }
  58. publicbooleanupdateStudent(Studentstudent){
  59. booleanflag=false;
  60. Objectobject=false;
  61. try{
  62. object=sqlMapClient.update("updateStudent",student);
  63. System.out.println("更新学生信息的返回值:"+object+",返回影响的行数");
  64. }catch(SQLExceptione){
  65. e.printStackTrace();
  66. }
  67. if(object!=null){
  68. flag=true;
  69. }
  70. returnflag;
  71. }
  72. publicList<Student>selectAllStudent(){
  73. List<Student>students=null;
  74. try{
  75. students=sqlMapClient.queryForList("selectAllStudent");
  76. }catch(SQLExceptione){
  77. e.printStackTrace();
  78. }
  79. returnstudents;
  80. }
  81. publicList<Student>selectStudentByName(Stringname){
  82. List<Student>students=null;
  83. try{
  84. students=sqlMapClient.queryForList("selectStudentByName",name);
  85. }catch(SQLExceptione){
  86. e.printStackTrace();
  87. }
  88. returnstudents;
  89. }
  90. publicStudentselectStudentById(intid){
  91. Studentstudent=null;
  92. try{
  93. student=(Student)sqlMapClient.queryForObject(
  94. "selectStudentById",id);
  95. }catch(SQLExceptione){
  96. e.printStackTrace();
  97. }
  98. returnstudent;
  99. }
  100. }

TestIbatis.java:

Java代码 收藏代码
  1. packagecom.iflytek.test;
  2. importjava.sql.Date;
  3. importjava.util.List;
  4. importcom.iflytek.daoimpl.StudentDaoImpl;
  5. importcom.iflytek.entity.Student;
  6. /**
  7. *@authorxudongwang2011-12-31
  8. *
  9. *Email:xdwangiflytek@gmail.com
  10. *
  11. */
  12. publicclassTestIbatis{
  13. publicstaticvoidmain(String[]args){
  14. StudentDaoImplstudentDaoImpl=newStudentDaoImpl();
  15. System.out.println("测试插入");
  16. StudentaddStudent=newStudent();
  17. addStudent.setName("李四");
  18. addStudent.setBirth(Date.valueOf("2011-09-02"));
  19. addStudent.setScore(88);
  20. System.out.println(studentDaoImpl.addStudent(addStudent));
  21. System.out.println("测试根据id查询");
  22. System.out.println(studentDaoImpl.selectStudentById(1));
  23. System.out.println("测试模糊查询");
  24. List<Student>mohuLists=studentDaoImpl.selectStudentByName("李");
  25. for(Studentstudent:mohuLists){
  26. System.out.println(student);
  27. }
  28. System.out.println("测试查询所有");
  29. List<Student>students=studentDaoImpl.selectAllStudent();
  30. for(Studentstudent:students){
  31. System.out.println(student);
  32. }
  33. System.out.println("根据id删除学生信息");
  34. System.out.println(studentDaoImpl.deleteStudentById(1));
  35. System.out.println("测试更新学生信息");
  36. StudentupdateStudent=newStudent();
  37. updateStudent.setId(1);
  38. updateStudent.setName("李四1");
  39. updateStudent.setBirth(Date.valueOf("2011-08-07"));
  40. updateStudent.setScore(21);
  41. System.out.println(studentDaoImpl.updateStudent(updateStudent));
  42. }
  43. }

iBatis的优缺点:

优点:

1、减少代码量,简单;

2、性能增强;

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

4、增强了移植性;

缺点:

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

2、参数数量只能有一个,多个参数时不太方便;







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值