ibatis入门教程一

这几天研究ibatis玩,参考一篇贴子进行安装配置:蓝雪森林

选择这个帖子来跟随配置是因为这个帖子看着比较干净,但是我仍旧在配置得过程中出现了好几个问题,所以我决定在这个帖子的基础上将更多细节加上,做一个傻瓜教程。

一、前期准备

虽然ibatis能处理多种数据库,不过初学者还是比较适应mysql,因此我选择mysql作为我的数据载体。另外我准备建的是一个普通的java 工程,并采用maven命令行来建立这个工程。所以在这之前,电脑上需要安装maven和mysql。

二、工程建立

①使用maven建立java工程框架

image

②编辑pom.xml文件引入ibatis和mysql的依赖包

   1: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   2:     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   3:     <modelVersion>4.0.0</modelVersion>
   4:  
   5:     <groupId>com.lipan.ibatis</groupId>
   6:     <artifactId>TestIbatis</artifactId>
   7:     <version>1.0-SNAPSHOT</version>
   8:     <packaging>jar</packaging>
   9:  
  10:     <name>TestIbatis</name>
  11:     <url>http://maven.apache.org</url>
  12:  
  13:     <properties>
  14:         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  15:     </properties>
  16:  
  17:     <dependencies>
  18:         <dependency>
  19:             <groupId>junit</groupId>
  20:             <artifactId>junit</artifactId>
  21:             <version>3.8.1</version>
  22:             <scope>test</scope>
  23:         </dependency>
  24:         <dependency>
  25:             <groupId>org.apache.ibatis</groupId>
  26:             <artifactId>ibatis-sqlmap</artifactId>
  27:             <version>2.3.4.726</version>
  28:         </dependency>
  29:         <dependency>
  30:             <groupId>mysql</groupId>
  31:             <artifactId>mysql-connector-java</artifactId>
  32:             <version>5.0.5</version>
  33:         </dependency>
  34:  
  35:     </dependencies>
  36: </project>

③下载依赖包并将maven工程转换为eclipse工程

image

image

④建立好的工程目录如下:

image

其中resource是后面新建的。

三、创建数据库表

可以选择命令行创建,也可以选择用可视化工具(比如Navicat Mysql来创建),我选择的是用Navicat来创建,最终创建的表的样子如下图所示。

image

其中,本地数据库localhost:3036中我建立了一个tbl_student的表,该表的主键是id,且有自增属性

四、填写ibatis配置文件

这里有三个配置文件:

SqlMap.properties 、SqlMapConfig.xml和Student.xml

ibatis要求首先描述数据库连接信息,这个可以在SqlMap.properties文件里面填写,同时SqlMapConfig.xml文件会读取SqlMap.properties中的信息来初始化数据库,针对每个数据库表,可以用一个专门的xml文件来描述具体的查询操作实现,这里我们建立的针对于tbl_student的xml文件称为Student.xml,接下来会给出其内容。为了组织清晰,在src目录下建立resources目录,用来存放这三个配置文件。

五、具体实现文件

这里有三个文件:

Student.java:与数据库实体对应的POJO类

   1: package com.lipan.ibatis;
   2:  
   3: import java.sql.Date;
   4: /**
   5:  * @author:lipan
   6:  * Email: areslipan@163.com
   7:  *
   8:  */
   9: public class Student {
  10:     
  11:     private int id;
  12:     private String name;
  13:     private Date birth;
  14:     private float score;
  15:     public int getId() {
  16:         return id;
  17:     }
  18:     public void setId(int id) {
  19:         this.id = id;
  20:     }
  21:     public String getName() {
  22:         return name;
  23:     }
  24:     public void setName(String name) {
  25:         this.name = name;
  26:     }
  27:     public Date getBirth() {
  28:         return birth;
  29:     }
  30:     public void setBirth(Date birth) {
  31:         this.birth = birth;
  32:     }
  33:     public float getScore() {
  34:         return score;
  35:     }
  36:     public void setScore(float score) {
  37:         this.score = score;
  38:     }
  39:     @Override
  40:     public String toString() {
  41:         return "id=" + id + "\tname=" + name + "\tmajor=" + birth + "\tscore="
  42:                 + score + "\n";
  43:     }
  44:     }

StudentDao.java:定义访问数据库的接口

   1: package com.lipan.dao;
   2:  
   3:  
   4:  
   5:  
   6: import java.util.List;
   7: import com.lipan.ibatis.Student;
   8: /**
   9: * @author xudongwang 2011-12-31
  10: *
  11: * Email:xdwangiflytek@gmail.com
  12: *
  13: */
  14: public interface StudentDao {
  15:     /**
  16:      * 添加学生信息
  17:      * 
  18:      * @param student
  19:      *            学生实体
  20:      * @return 返回是否添加成功
  21:      */
  22:     public boolean addStudent(Student student);
  23:  
  24:     /**
  25:      * 根据学生id删除学生信息
  26:      * 
  27:      * @param id
  28:      *            学生id
  29:      * @return 删除是否成功
  30:      */
  31:     public boolean deleteStudentById(int id);
  32:  
  33:     /**
  34:      * 更新学生信息
  35:      * 
  36:      * @param student
  37:      *            学生实体
  38:      * @return 更新是否成功
  39:      */
  40:     public boolean updateStudent(Student student);
  41:  
  42:     /**
  43:      * 查询全部学生信息
  44:      * 
  45:      * @return 返回学生列表
  46:      */
  47:     public List<Student> selectAllStudent();
  48:  
  49:     /**
  50:      * 根据学生姓名模糊查询学生信息
  51:      * 
  52:      * @param name
  53:      *            学生姓名
  54:      * @return 学生信息列表
  55:      */
  56:     public List<Student> selectStudentByName(String name);
  57:  
  58:     /**
  59:      * 根据学生id查询学生信息
  60:      * 
  61:      * @param id
  62:      *            学生id
  63:      * @return 学生对象
  64:      */
  65:     public Student selectStudentById(int id);
  66: }

StudentDaoImpl.java:访问数据库的具体实现,需要读取SqlMapConfig.xml的配置文件

   1: package com.lipan.daoImpl;
   2:  
   3: import java.io.IOException;
   4: import java.io.Reader;
   5: import java.sql.SQLException;
   6: import java.util.List;
   7: import com.ibatis.common.resources.Resources;
   8: import com.ibatis.sqlmap.client.SqlMapClient;
   9: import com.ibatis.sqlmap.client.SqlMapClientBuilder;
  10: import com.lipan.dao.StudentDao;
  11: import com.lipan.ibatis.Student;
  12: /**
  13: * @author lipan
  14: *
  15: * Email:areslipan@163.com
  16: *
  17: */
  18: public class StudentDaoImpl implements StudentDao {
  19:     private static SqlMapClient sqlMapClient = null;
  20:     // 读取配置文件
  21:     static {
  22:         try {
  23:             Reader reader = Resources
  24:                     .getResourceAsReader("SqlMapConfig.xml");
  25:                 
  26:                     //.getResourceAsReader("SqlMapConfig.xml");
  27:             sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
  28:             reader.close();
  29:         } catch (IOException e) {
  30:             e.printStackTrace();
  31:         }
  32:     }
  33:  
  34:     public boolean addStudent(Student student) {
  35:         Object object = null;
  36:         boolean flag = false;
  37:         try {
  38:             object = sqlMapClient.insert("addStudent", student);
  39:             System.out.println("添加学生信息的返回值:" + object);
  40:         } catch (SQLException e) {
  41:             e.printStackTrace();
  42:         }
  43:         if (object != null) {
  44:             flag = true;
  45:         }
  46:         return flag;
  47:     }
  48:  
  49:     public boolean deleteStudentById(int id) {
  50:         boolean flag = false;
  51:         Object object = null;
  52:         try {
  53:             object = sqlMapClient.delete("deleteStudentById", id);
  54:             System.out.println("删除学生信息的返回值:" + object + ",这里返回的是影响的行数");
  55:         } catch (SQLException e) {
  56:             e.printStackTrace();
  57:         }
  58:         if (object != null) {
  59:             flag = true;
  60:         }
  61:         return flag;
  62:     }
  63:  
  64:     public boolean updateStudent(Student student) {
  65:         boolean flag = false;
  66:         Object object = false;
  67:         try {
  68:             object = sqlMapClient.update("updateStudent", student);
  69:             System.out.println("更新学生信息的返回值:" + object + ",返回影响的行数");
  70:         } catch (SQLException e) {
  71:             e.printStackTrace();
  72:         }
  73:         if (object != null) {
  74:             flag = true;
  75:         }
  76:         return flag;
  77:     }
  78:  
  79:     public List<Student> selectAllStudent() {
  80:         List<Student> students = null;
  81:         try {
  82:             students = sqlMapClient.queryForList("selectAllStudent");
  83:         } catch (SQLException e) {
  84:             e.printStackTrace();
  85:         }
  86:         return students;
  87:     }
  88:  
  89:     public List<Student> selectStudentByName(String name) {
  90:         List<Student> students = null;
  91:         try {
  92:             students = sqlMapClient.queryForList("selectStudentByName", name);
  93:         } catch (SQLException e) {
  94:             e.printStackTrace();
  95:         }
  96:         return students;
  97:     }
  98:  
  99:     public Student selectStudentById(int id) {
 100:         Student student = null;
 101:         try {
 102:             student = (Student) sqlMapClient.queryForObject(
 103:                     "selectStudentById", id);
 104:         } catch (SQLException e) {
 105:             e.printStackTrace();
 106:         }
 107:         return student;
 108:     }
 109: }

 

六、测试文件

TestIbatis.java

   1: package com.lipan.ibatis;
   2:  
   3: import java.sql.Date;
   4: import java.util.List;
   5:  
   6: import com.lipan.daoImpl.StudentDaoImpl;
   7: /**
   8: * @author xudongwang 2011-12-31
   9: *
  10: * Email:xdwangiflytek@gmail.com
  11: *
  12: */
  13: public class TestIbatis {
  14: public static void main(String[] args) {
  15:         StudentDaoImpl studentDaoImpl = new StudentDaoImpl();
  16:         System.out.println("测试插入");
  17:         Student addStudent = new Student();
  18:         addStudent.setName("李四");
  19:         addStudent.setBirth(Date.valueOf("2011-09-02"));
  20:         addStudent.setScore(88);
  21:         //addStudent.setId(12);
  22:         System.out.println(studentDaoImpl.addStudent(addStudent));
  23:         System.out.println("测试根据id查询");
  24:         System.out.println(studentDaoImpl.selectStudentById(1));
  25:         System.out.println("测试模糊查询");
  26:         List<Student> mohuLists = studentDaoImpl.selectStudentByName("李");
  27:         for (Student student : mohuLists) {
  28:             System.out.println(student);
  29:         }
  30:         System.out.println("测试查询所有");
  31:         List<Student> students = studentDaoImpl.selectAllStudent();
  32:         for (Student student : students) {
  33:             System.out.println(student);
  34:         }
  35:         System.out.println("根据id删除学生信息");
  36:         System.out.println(studentDaoImpl.deleteStudentById(1));
  37:         System.out.println("测试更新学生信息");
  38:         Student updateStudent = new Student();
  39:         updateStudent.setId(1);
  40:         updateStudent.setName("李四1");
  41:         updateStudent.setBirth(Date.valueOf("2011-08-07"));
  42:         updateStudent.setScore(21);
  43:         System.out.println(studentDaoImpl.updateStudent(updateStudent));
  44:     
  45: }
  46: }

七、项目目录

image

八、注意

在读取SqlMapConfig.xml的时候,

Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");会提示 Could not find resource SqlMapConfig.xml,即便将这个路径编程绝对路径也会出错,原因是这个方法最终会调用Classloader.getResource()方法,个函数调用的是相对于classpath的绝对路径,所以load不进去。关于这个问题的详细理解,可以不断在代码中trace,也有个帖子专门讲这个问题。

posted @ 2014-06-20 16:44  曾见绝美的阳光  阅读(586)  评论(0编辑  收藏  举报