要使用iBATIS执行任何创建,读取,更新和删除(CRUD)操作,您需要创建与该表对应的普通旧Java对象(POJO)类.此类描述将"建模"数据库表行的对象.
POJO类将具有执行所需操作所需的所有方法的实现.
让我们假设我们在MySQL中有以下EMPLOYEE表 :
CREATE TABLE EMPLOYEE ( id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL, PRIMARY KEY (id) );
我们将在Employee.java文件中创建一个Employee类,如下所示 :
public class Employee { private int id; private String first_name; private String last_name; private int salary; /* Define constructors for the Employee class. */ public Employee() {} public Employee(String fname, String lname, int salary) { this.first_name = fname; this.last_name = lname; this.salary = salary; } } /* End of Employee */
您可以定义在表格中设置单个字段的方法.下一章将介绍如何获取各个字段的值.
要使用iBATIS定义SQL映射语句,我们将使用<插入>标记和在这个标记定义中,我们将定义一个"id",它将在IbatisInsert.java文件中用于在数据库上执行SQL INSERT查询.
<?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="Employee"> <insert id="insert" parameterClass="Employee"> insert into EMPLOYEE(first_name, last_name, salary) values (#first_name#, #last_name#, #salary#) <selectKey resultClass="int" keyProperty="id"> select last_insert_id() as id </selectKey> </insert> </sqlMap>
这里 parameterClass : 可以取值为 string,int,float,double ,或者任何类对象基于要求.在这个例子中,我们将调用Employee对象作为参数,同时调用SqlMap类的 insert 方法.
如果您的数据库表使用IDENTITY,AUTO_INCREMENT或SERIAL列或您已经定义了SEQUENCE/GENERATOR,您可以使用< selectKey> < insert>中的元素使用或返回该数据库生成的值的语句.
此文件将具有应用程序级逻辑以在Employee中插入记录table :
import com.ibatis.common.resources.Resources; import com.ibatis.sqlmap.client.SqlMapClient; import com.ibatis.sqlmap.client.SqlMapClientBuilder; import java.io.*; import java.sql.SQLException; import java.util.*; public class IbatisInsert{ public static void main(String[] args)throws IOException,SQLException{ Reader rd = Resources.getResourceAsReader("SqlMapConfig.xml"); SqlMapClient smc = SqlMapClientBuilder.buildSqlMapClient(rd); /* This would insert one record in Employee table. */ System.out.println("Going to insert record....."); Employee em = new Employee("Zara", "Ali", 5000); smc.insert("Employee.insert", em); System.out.println("Record Inserted Successfully "); } }
以下是编译和运行的步骤上面提到的软件.在继续进行编译和执行之前,请确保已正确设置PATH和CLASSPATH.
如上所示创建Employee.xml.
如上所示创建Employee.java并进行编译.
如上所示创建IbatisInsert.java并编译它.
执行IbatisInsert二进制文件来运行程序.
您将得到以下结果,并且将在EMPLOYEE表中创建一条记录.
$java IbatisInsert Going to insert record..... Record Inserted Successfully
如果你检查EMPLOYEE表,它应该显示以下结果 :
mysql> select * from EMPLOYEE; +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 1 | Zara | Ali | 5000 | +----+------------+-----------+--------+ 1 row in set (0.00 sec)