Ibatis使用实践 - 1

本文介绍了一个基于Ibatis的简单CRUD应用案例,包括定义POJO类、DAO接口及其实现,配置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中的各接口方法成功执行
 

本文转自 tianya23 51CTO博客,原文链接:http://blog.51cto.com/tianya23/384686,如需转载请自行联系原作者
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值