`
2277259257
  • 浏览: 501366 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

iBatis简单入门教程

 
阅读更多

http://my.oschina.net/zimingforever/blog/99374

 http://blog.csdn.net/kkdelta/article/details/7440712

 

 

 

iBatis简单入门教程

 

iBatis 简介:

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

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

 

搭建iBatis 开发环境:

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

2 、编写文件:

       POJO类---------------Student.java用来与数据库打交道的持久层对象,也是通过 ibatis要操作的对象

       sqlMap.xml-----------Student.xml :配置DAO中调用的节点id,sql语句中传入的参数,结果集的封装类

                              (Hibernate中:实体类<----->表的对应关系,参数赋值、结果集封装都由框架自动完成)

      Jdbc 连接配置--------SqlMap.properties:配置数据库的连接数据

      总配置文件------------SqlMapConfig.xml :引入所有的配置文件,配置框架的数据源等

3、DAO层iBatis应用:

    一、启动iBatis框架容器

    二、加载iBatis框架的配置文件

    三、调用iBatis框架接口、传入参数

    1)读取配置文件

      Reader reader = Resources .getResourceAsReader("com/iflytek/SqlMapConfig.xml");

    2)获取sqlMapClient 对象(该实例已创建数据库连接)

      sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);

     (类似Hibernate中的new Configuration().buildSessionFactory().openSession()获取session对象)

    3)开始数据库操作

      object = sqlMapClient.insert("addStudent", student);

      object = sqlMapClient.delete("deleteStudentById", id);

      object = sqlMapClient.update("updateStudent", student);

      students = sqlMapClient.queryForList("selectAllStudent");

      student = (Student) sqlMapClient.queryForObject("selectStudentById", id);

Demo

Student.java:

 复制代码 收藏代码

 

  1. public   class Student {
  2. // 注意这里需要保证有一个无参构造方法,因为包括Hibernate在内的映射都是使用反射的,如果没有无参构造可能会出现问题
  3. privateint id;
  4. private String name;
  5. private Date birth;
  6. privatefloat score;
  7. publicint getId() {
  8. return id;
  9. }
  10. publicvoid setId(int id) {
  11. this.id = id;
  12. }
  13. public String getName() {
  14. return name;
  15. }
  16. publicvoid setName(String name) {
  17. this.name = name;
  18. }
  19. public Date getBirth() {
  20. return birth;
  21. }
  22. publicvoid setBirth(Date birth) {
  23. this.birth = birth;
  24. }
  25. publicfloat getScore() {
  26. return score;
  27. }
  28. publicvoid setScore(float score) {
  29. this.score = score;
  30. }
  31. @Override
  32. public String toString() {
  33. return"id=" + id + "\tname=" + name + "\tmajor=" + birth + "\tscore="
  34. + score + "\n";
  35. }
  36. }

SqlMap.properties

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

Student.xml

 复制代码 收藏代码
  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.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.   <resultMap id="getStudents" class="Student" >  
  8.   <result column="id" property="id"              jdbcType="INT" />   
  9.   <result column="name" property="name"  jdbcType="VARCHAR" />  
  10.   <result column="address" property="address" jdbcType="VARCHAR" />  
  11. </resultMap>
  12. <!-- id表示select里的sql语句,resultClass:返回单个结果集,resultMap:返回多个结果集 -->
  13. <select id="selectAllStudent" resultMap="getStudents">
  14. select * from   tbl_student
  15. </select>
  1. <!-- parameterClass表示参数的内容 -->
  2. <!-- #表示这是一个外部调用的需要传进的参数,可以理解为占位符 -->
  3. <select id="selectStudentById" parameterClass="int" resultClass="Student">
  4. select * from tbl_student where id=#id#
  5. </select>
  6. <!-- 注意这里的resultClass类型,使用Student类型取决于queryForList还是queryForObject -->
  7. <select id="selectStudentByName"parameterClass="String" resultClass="Student">
  8. select name,birth,score from tbl_student where name like '%$name$%'
  9. </select>
  1. <insertid="addStudent"parameterClass="Student">返回数据库受影响的行数
  2. insert into tbl_student(name,birth,score) values (#name#,#birth#,#score#);
  3. <selectKeyresultClass="int"keyProperty="id">
  4. select @@identity as inserted
  5. <!-- 这里需要说明一下不同的数据库主键的生成,对各自的数据库有不同的方式: -->
  6. <!-- mysql:SELECT LAST_INSERT_ID() AS VALUE -->
  7. <!-- mssql:select @@IDENTITY as value -->
  8. <!-- oracle:SELECT STOCKIDSEQUENCE.NEXTVAL AS VALUE FROM DUAL -->
  9. <!-- 还有一点需要注意的是不同的数据库生产商生成主键的方式不一样,有些是预先生成 (pre-generate)主键的,如Oracle和PostgreSQL。
  10. 有些是事后生成(post-generate)主键的,如MySQL和SQL Server 所以如果是Oracle数据库,则需要将selectKey写在insert之前 -->
  11. </selectKey>
  12. </insert>
  1. <deleteid="deleteStudentById"parameterClass="int">//在ibatis中默认的删除语句是返回数据库受影响的行数
  2. <!-- #id#里的id可以随意取,但是上面的insert则会有影响,因为上面的name会从Student里的属性里去查找 -->
  3. <!-- 我们也可以这样理解,如果有#占位符,则ibatis会调用parameterClass里的属性去赋值 -->
  4. delete from tbl_student where id=#id#
  5. </delete>
  6. <updateid="updateStudent"parameterClass="Student">返回数据库受影响的行数
  7. update tbl_student set name=#name#,birth=#birth#,score=#score# where id=#id#
  8. </update>
  9. </sqlMap>

 

说明:

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

选择uri URI: 请选择本地文件系统上

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

Key Type: 选择Schema Location;

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

 

SqlMapConfig.xml

 复制代码 收藏代码
  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
  3. "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
  4. <sqlMapConfig>
  5. <settings
  6.     cacheModelsEnabled="true"     是否启用缓存
  7.     lazyLoadingEnabled="true"       是否启用延迟加载
  8.     enhancementEnabled="true"    是否启用字节码增强
  9.     errorTracingEnabled="true"      是否启用错误处理
  10.     maxRequests="32"                   最大并发请求数
  11.     maxSessions="10"                    最大Session数,即当前最大允许的并发SqlMapClient数
  12.     maxTransactions="5"                最大并发事务数
  13.     useStatementNamespaces="false"    是否启用名称空间
  14. />
  15. <!-- 引用JDBC属性的配置文件 -->
  16. <propertiesresource="com/iflytek/entity/SqlMap.properties"/>
  17. <!-- 定义IBatis的事务管理器类型,其类型有3种:(JDBC、JTA、EXTERNAL) -->
  18. <transactionManager  type="JDBC">
  19. <!-- 定义数据源,数据源的连接类型有3种:(SIMPLE、DBCP、JNDI) -->
  20. <dataSourcetype="SIMPLE">
  21. <propertyname="JDBC.Driver"value="${driver}"/>
  22. <propertyname="JDBC.ConnectionURL"value="${url}"/>
  23. <propertyname="JDBC.Username"value="${username}"/>
  24. <propertyname="JDBC.Password"value="${password}"/>
  25. <propertyname="Pool.MaximumActiveConnections"value="10"/>最大容量
  26. <propertyname="Pool.MaximumIdleConnections"value="5"/>允许挂起的最大连接
  27. <propertyname="Pool.MaximumCheckoutTime"value="120000"/>连接被某个任务所允许占用的最大时间
  28. <propertyname="Pool.TimeToWait"value="500"/>线程允许等待的最大时间
  29. </dataSource>
  30. </transactionManager>
  31. <!-- 这里可以写多个实体的映射文件 -->
  32. <sqlMapresource="com/iflytek/entity/Student.xml"/>
  33. </sqlMapConfig>
  34. 注意:transactionManager节点  IBatis的事务管理器:
  35. JDBC---通过传统JDBC Connection.commit/rollback实现事务支持
  36. JTA----使用容器提供的JTA服务实现全局事务管理
  37. EXTERNAL-------外部事务管理,如在EJB中使用ibatis,通过EJB的部署配置即可实现自动的事务管理机制.此时ibatis将把所有事务委托给外部容器进行管理。此外,通过Spring等轻量级容器实现事务的配置化管理也是一个不错的选择
  38. dataSource 节点:
  39. SIMPLE ------ibatis 内置的dataSource 实现,其中实现了一个简单的数据库连接池机制,对应ibatis 实现类为com.ibatis.sqlmap.engine.datasource.SimpleDataSourceFactory.
    JDBC 使用数据库自己的事务(局部事务),connect.beginTranstion(), connect.commit()等
  40. DBCP ---------基于Apache DBCP连接池组件实现的DataSource封装,当无容器提供DataSource服务时,建议使用该选项,对应ibatis实现类为com.ibatis.sqlmap.engine.datasource.DbcpDataSourceFactory.
  41. JTA :使用jta 事务管理器管理事务(全局事务),使用userTranstion对象
  42. JNDI ---------使用J2EE容器提供的DataSource实现, DataSource将通过指定的JNDI Name从容器中获取.对应ibatis实现类为com.ibatis.sqlmap.engine.datasource.JndiDataSourceFactory. Ibatis 不控制事务,事务交由外部控制,一般在CTM,或spring托管事务中使用

 

StudentDao

 复制代码 收藏代码

 

  1. public   interface StudentDao {
  2. /**
  3. * 添加学生信息
  4. * @param student  学生实体
  5. * @return 返回是否添加成功
  6. */
  7. public boolean addStudent(Student student);
  1. /**
  2. * 根据学生id删除学生信息
  3. * @param id  学生id
  4. * @return 删除是否成功
  5. */
  6. public  boolean deleteStudentById(int id);
  7. /**
  8. * 更新学生信息
  9. * @param student  学生实体
  10. * @return 更新是否成功
  11. */
  12. publicboolean updateStudent(Student student);
  13. /**
  14. * 查询全部学生信息
  15.  @return 返回学生列表
  16. */
  17. public List<Student> selectAllStudent();
  18. /**
  19. * 根据学生姓名模糊查询学生信息
  20.  @param name  学生姓名
  21. * @return 学生信息列表
  22. */
  23. public List<Student> selectStudentByName(String name);
  24. /**
  25. * 根据学生id查询学生信息
  26.  @param id 学生id
  27. * @return 学生对象
  28. */
  29. public Student selectStudentById(int id);
  30. }

StudentDaoImpl

 复制代码 收藏代码

 

  1. public class StudentDaoImpl implements StudentDao {
  2. privatestatic SqlMapClient sqlMapClient = null;
  3. // 读取配置文件
  4. static {
  5. try {
  6. Reader reader = Resources .getResourceAsReader("com/iflytek/entity/SqlMapConfig.xml");
  7. sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
  8. reader.close();
  9. } catch (IOException e) {
  10. e.printStackTrace();
  11. }
  12. }

 

  1. public  boolean addStudent(Student student) {
  2. Object object = null;
  3. boolean flag = false;
  4. try {
  5. object = sqlMapClient.insert("addStudent", student); //实际返回值是插入数据的行号
  6. System.out.println("添加学生信息的返回值:" + object);
  7. } catch (SQLException e) {
  8. e.printStackTrace();
  9. }
  10. if (object != null) {
  11. flag = true;
  12. }
  13. return flag;
  14. }

 

  1. public  boolean deleteStudentById(int id) {
  2. boolean flag = false;
  3. Object object = null;
  4. try {
  5. object = sqlMapClient.delete("deleteStudentById", id);
  6. System.out.println("删除学生信息的返回值:" + object + ",这里返回的是影响的行数");
  7. } catch (SQLException e) {
  8. e.printStackTrace();
  9. }
  10. if (object != null) {
  11. flag = true;
  12. }
  13. return flag;
  14. }

 

  1. public  boolean updateStudent(Student student) {
  2. boolean flag = false;
  3. Object object = false;
  4. try {
  5. object = sqlMapClient.update("updateStudent", student);
  6. System.out.println("更新学生信息的返回值:" + object + ",返回影响的行数");
  7. } catch (SQLException e) {
  8. e.printStackTrace();
  9. }
  10. if (object != null) {
  11. flag = true;
  12. }
  13. return flag;
  14. }

 

  1. public List<Student> selectAllStudent() {
  2. List<Student> students = null;
  3. try {
  4. students = sqlMapClient.queryForList("selectAllStudent");
  5. students = sqlMapClient.queryForList("selectAllStudent" , null); //批量查询(方式二)
  6. students = sqlMapClient.queryForList("selectAllStudent" , null ,0 ,40); //批量指定范围的查询(方式二)
  7. PaginatedList list=sqlMap.queryForPaginatedList (“getProductList”,null ,10 ); 
    list.nextPage(); 
    list.previousPage();     
    //批量分页查询
  8. } catch (SQLException e) {
  9. e.printStackTrace();
  10. }
  11. return students;
  12. }

 

  1. public List<Student> selectStudentByName(String name) {
  2. List<Student> students = null;
  3. try {
  4. students = sqlMapClient.queryForList("selectStudentByName",name);
  5. } catch (SQLException e) {
  6. e.printStackTrace();
  7. }
  8. return students;
  9. }

 

  1. public Student selectStudentById(int id) {
  2. Student student = null;
  3. try {
  4. student = (Student) sqlMapClient.queryForObject("selectStudentById", id);
  5. //sqlMapClient.queryForObject(“getStu”, parameterObject, student );在指定对象中存放查询结果
  6. } catch (SQLException e) {
  7. e.printStackTrace();
  8. }
  9. return student;
  10. }
  11. }

TestIbatis.java

 复制代码 收藏代码

 

  1. publicclass TestIbatis {
  2. publicstaticvoid main(String[] args) {
  3. StudentDaoImpl studentDaoImpl = new StudentDaoImpl();
  4. System.out.println("测试插入");
  5. Student addStudent = new Student();
  6. addStudent.setName("李四");
  7. addStudent.setBirth(Date.valueOf("2011-09-02"));
  8. addStudent.setScore(88);
  9. System.out.println(studentDaoImpl.addStudent(addStudent));
  10. System.out.println("测试根据id查询");
  11. System.out.println(studentDaoImpl.selectStudentById(1));
  12. System.out.println("测试模糊查询");
  13. List<Student> mohuLists = studentDaoImpl.selectStudentByName("李");
  14. for (Student student : mohuLists) {
  15. System.out.println(student);
  16. }
  17. System.out.println("测试查询所有");
  18. List<Student> students = studentDaoImpl.selectAllStudent();
  19. for (Student student : students) {
  20. System.out.println(student);
  21. }
  22. System.out.println("根据id删除学生信息");
  23. System.out.println(studentDaoImpl.deleteStudentById(1));
  24. System.out.println("测试更新学生信息");
  25. Student updateStudent = new Student();
  26. updateStudent.setId(1);
  27. updateStudent.setName("李四1");
  28. updateStudent.setBirth(Date.valueOf("2011-08-07"));
  29. updateStudent.setScore(21);
  30. System.out.println(studentDaoImpl.updateStudent(updateStudent));
  31. }
  32. }

iBatis 的优缺点:

优点:

1、减少代码量,简单;

2、性能增强;

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

4、增强了移植性;

缺点:

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

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

分享到:
评论

相关推荐

    iBatis简单入门教程.

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

    Ibatis入门例子,Ibatis教程

    简单的Ibatis入门例子,让你踏入Ibatis大门

    Ibatis入门教程

    Ibatis入门教程,简单介绍利用ibatis进行增删改查操作。

    ibatis教程入门

    适合初学者, 具体,简单,易懂 ibatis教程入门

    ibatis入门教程(快速上手版)ppt

    这版PPT仅供学习使用,是ibatis入门的知识,用PPT做的,很容上手。

    iBatis介绍及入门教程.doc

    iBatis是又一个O/R Mapping解决方案,j2ee的O/R方案真是多,和Hibernate相比,iBatis最大的特点就是小巧,上手很快。如果你不需要太多复杂的功能,iBatis是能满足你的要求又足够灵活的最简单的解决方案。

    IBATIS SQL Maps 入门教程.pdf

    本文是初学者的快速入门教程,涵盖了SQL Map的一个简单而典型的应用。

    IBatis入门教程

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

    Java_Web_核心框架之_iBATIS

    ibatis入门教程,即学即会,简单上手;

    iBATIS SQL Maps官方中文教程

    Ibatis官网教程,简单实用,实例很容易就看得懂个,很适合入门了初学者和参考使用。

    《Java Web开发教程——入门与提高篇(JSP+Servlet)》附赠电子资料——框架基础及实例

    本文档是《Java Web开发教程——入门与提高篇(JSP+Servlet)》一书的附赠电子资料,对Struts2、JSF、Hibernate、iBATIS和JPA等框架进行了简单介绍,并且给出了两个自定义简单框架,还包括3个实例,共149页。

    Ibatis学习指南,适合于初学者参考

    看了Ibatis很多的书,说了很多很多,过于复杂,本人先把Ibatis的增删改查所有的例子总结了一下,写了一个简单易懂的例子,对初学者入门学习有很大的帮助.简单易懂,下载解压后即可运行.

    springmybatis

    (读者注:其实这个应该叫做很基础的入门一下下,如果你看过Hibernate了那这个就非常的简单) (再加一条,其实大家可以看官方的教程更好些:http://mybatis.github.io/mybatis-3/,而且如果英文不是很好的那就看...

    iuhyiuhkjh908u0980

    入门级的东西. JBPM文档1、 加入JBPM支持包下载jbpm-starters-kit-3.1.4在项目的classPath中加入jbpm-3.1.4.jar、jbpm-identity-3.1.2.jar、jbpm-webapp-3.1.2.jar,jbpm-3.1.4.jar必须加入,是JBPM的核心包;bpm-...

Global site tag (gtag.js) - Google Analytics