Ibatis使用实践 - 1

Ibatis使用实践-1

  Ibatis使用轻巧方便,简单易学。基本原理是将程序中的sql抽取出来放入配置文件中,可以精确控制发出的SQL语句,对SQL的调优非常的方便。
  不过也存在一些, 传递的参数最多只能有一个, 在缓存的方面未做任何的处理, 而这些正好是hibernate更加强大的地方。

一、Ibatis资料参考如下:

1.官方网址:

http://ibatis.apache.org/

 2.ibatis生成工具 ibator:

主页:http://ibatis.apache.org/ibator.html

文档:http://ibatis.apache.org/docs/tools/ibator/

下载:http://people.apache.org/builds/ibatis/alpha/IbatorForEclipse1.2.1.zip

更新:http://ibatis.apache.org/tools/ibator (eclipse自动更新) 

实例:http://blog.csdn.net/tanlier1/archive/2007/09/13/1784074.aspx

       http://www.blogjava.net/jia8zy/archive/2007/08/19/137964.html

实例可能与最新版本有出入,最好还是按照文档来。

3.spring + ibatis

http://www.blogjava.net/ducklyl/archive/2007/11/20/161938.html

 

4.iBatis Java Mapper是iBatis+Spring的一个扩展,能够让你使用Java类和接口来代替用于object-SQL映射的XML文档。(利用java的annotations功能)

http://javamapper.sourceforge.net/

 

5.书籍文档下载:http://zhang-ly520.javaeye.com/blog/326203

ibatis in action 原版

ibatis in action 部分中文版

ibatis入门文档中文版

ibatis开发手册中文版

二、实例

1、定义POJO类:Student.java

package com.alibaba.ibatis.modules;

public class Student {
   private int id;
   private String name;
   private String address;
   private float score;

   public int getId() {
     return id;
  }

   public void setId( int id) {
     this.id = id;
  }

   public String getName() {
     return name;
  }

   public void setName(String name) {
     this.name = name;
  }

   public String getAddress() {
     return address;
  }

   public void setAddress(String address) {
     this.address = address;
  }

   public float getScore() {
     return score;
  }

   public void setScore( float score) {
     this.score = score;
  }

  @Override
   public String toString() {
     return "id: " + id + ", name: " + name + ", address: " + address
        + ", score: " + score;

  }
}

2、定义使用接口:StudentService.java

package com.alibaba.ibatis.service;

import java.util.List;

import com.alibaba.ibatis.modules.Student;

public interface StudentService {
   public void addStudent(Student student);
   public int updateStudent(Student student);
   public int deleteStudent(Student student);
   public Student getStudentById( int id);
   public List<Student> getStudentsLike(String likeName);
   public List<Student> getAllStudents();
}
增加StudentService的实现类:StudentServiceImpl.java
package com.alibaba.ibatis.service.impl;

import java.io.Reader;
import java.sql.SQLException;
import java.util.List;

import com.alibaba.ibatis.modules.Student;
import com.alibaba.ibatis.service.StudentService;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public class StudentServiceImpl implements StudentService {

   static SqlMapClient sqlMapClient = null;
   static {
    String resource = "SqlMapConfig.xml";
     try {
      Reader reader = Resources.getResourceAsReader(resource);
      sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  @Override
   public void addStudent(Student student) {
     try {
      sqlMapClient.insert( "insertStudent", student);
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

  @Override
   public int deleteStudent(Student student) {
     int effectedRow = 0;
     try {
      effectedRow = sqlMapClient.delete( "deleteStudent", student);
    } catch (SQLException e) {
      e.printStackTrace();
    }
     return effectedRow;
  }

  @SuppressWarnings( "unchecked")
  @Override
   public List<Student> getAllStudents() {
    List<Student> students = null;
     try {
      students = sqlMapClient.queryForList( "getAllStudents");
    } catch (SQLException e) {
      e.printStackTrace();
    }
     return students;
  }

  @Override
   public Student getStudentById( int id) {
    Student student = null;
     try {
      student = (Student) sqlMapClient.queryForObject( "getStudentById",
          id);
    } catch (SQLException e) {
      e.printStackTrace();
    }
     return student;
  }

  @Override
   public int updateStudent(Student student) {
     int effectedRow = 0;
     try {
      effectedRow = sqlMapClient.update( "updateStudent", student);
    } catch (SQLException e) {
      e.printStackTrace();
    }
     return effectedRow;
  }

  @SuppressWarnings( "unchecked")
  @Override
   public List<Student> getStudentsLike(String likeName) {
    List<Student> students = null;
     try {
      students = sqlMapClient.queryForList( "getStudentsLike", likeName);
    } catch (SQLException e) {
      e.printStackTrace();
    }
     return students;
  }

}

3、Ibatis的三个配置文件:

(1)与数据连接相关的配置文件jdbc.properties, 
(2)操作具体POJO的增删改查的配置文件
(3)总控文件
 
(1)与数据连接相关的配置文件:jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/ibatis
username=ibatis
password=ibatis
Pool.MaximumActiveConnections=10
Pool.MaximumIdleConnections=5
Pool.MaximumCheckoutTime=120000
Pool.TimeToWait=500
(2)操作具体POJO的增删改查的配置文件:student.xml, 其中对模糊查询的情况需要特别的注意:必须使用$来做占位符,如: SELECT * FROM student where name like '%$name$%'
<? 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 ="modules.student" >
   < typeAlias alias ="Student" type ="com.alibaba.ibatis.modules.Student" />

   < insert id ="insertStudent" parameterClass ="Student" >
    INSERT INTO
    student(id, name, address, score)
    VALUES(#id#,#name#,#address#,#score#)
   </ insert >

   < select id ="getStudentById" parameterClass ="int" resultClass ="Student" >
    SELECT * FROM student where id = #id#
   </ select >

   < select id ="getAllStudents" resultClass ="Student" >
    SELECT * FROM student
   </ select >
  
   < select id ="getStudentsLike" resultClass ="Student" parameterClass ="String" >
    SELECT * FROM student where name like '%$name$%'
   </ select >

   < update id ="updateStudent" parameterClass ="Student" >
    UPDATE student set
    name = #name#, address = #address#, score = #score# where id = #id#
   </ update >

   < delete id ="deleteStudent" parameterClass ="Student" >
    DELETE FROM
    student where id = #id# and name = #name# and address = #address# and
    score = #score#
   </ delete >

</ sqlMap >        
 
(3)总控文件:SqlMapConfig.xml
<? xml version ="1.0" encoding ="UTF-8" ?>

<!DOCTYPE sqlMapConfig                        
                PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"                        
                "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

< sqlMapConfig >
   < properties resource ="jdbc.properties" />
   < 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}" />
       < property name ="Pool.MaximumActiveConnections" value ="${Pool.MaximumActiveConnections}" />
       < property name ="Pool.MaximumIdleConnections" value ="${Pool.MaximumIdleConnections}" />
       < property name ="Pool.MaximumCheckoutTime" value ="${Pool.MaximumCheckoutTime}" />
       < property name ="Pool.TimeToWait" value ="${Pool.TimeToWait}" />
     </ dataSource >
   </ transactionManager >

   < sqlMap resource ="com/alibaba/modules/student.xml" />
</ sqlMapConfig >        
4、引入相应的依赖包:pom.xml
< dependency >
       < groupId >com.alibaba.external </ groupId >
       < artifactId >sourceforge.ibatis </ artifactId >
       < version >2.3.4 </ version >
     </ dependency >
     < dependency >
       < groupId >com.alibaba.external </ groupId >
       < artifactId >jdbc.mysql.mysql-connector </ artifactId >
       < version >5.1.6 </ version >
     </ dependency >
经测试,service中的各接口方法成功执行
 
 
 
 
 

你可能感兴趣的:(ibatis,职场,休闲)