若要使用iBATIS執(zhí)行的任何CRUD(創(chuàng)建,寫入,更新和刪除)操作,需要創(chuàng)建一個(gè)的POJO(普通Java對象)類對應(yīng)的表。本課程介紹的對象,將“模式”的數(shù)據(jù)庫表中的行。
POJO類必須實(shí)現(xiàn)所有執(zhí)行所需的操作所需的方法。
我們已經(jīng)在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文件中創(chuàng)建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 */
可以定義方法來設(shè)置表中的各個(gè)字段。下一章節(jié)將告訴你如何獲得各個(gè)字段的值。
要定義使用iBATIS SQL映射語句中,我們將使用<insert>標(biāo)簽,這個(gè)標(biāo)簽定義中,我們會定義將用于在IbatisInsert.java文件的數(shù)據(jù)庫執(zhí)行SQL INSERT查詢“id”。
<?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:可以采取一個(gè)值作為字符串,整型,浮點(diǎn)型,double或根據(jù)要求任何類的對象。在這個(gè)例子中,我們將通過Employee對象作為參數(shù)而調(diào)用SqlMap類的insert方法。
如果您的數(shù)據(jù)庫表使用IDENTITY,AUTO_INCREMENT或串行列或已定義的SEQUENCE/GENERATOR,可以使用<selectKey>元素在的<insert>語句中使用或返回?cái)?shù)據(jù)庫生成的值。
文件將應(yīng)用程序級別的邏輯在Employee表中插入記錄:
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 "); } }
下面是步驟來編譯并運(yùn)行上述軟件。請確保已在進(jìn)行的編譯和執(zhí)行之前,適當(dāng)?shù)卦O(shè)置PATH和CLASSPATH。
創(chuàng)建Employee.xml如上所示。
創(chuàng)建Employee.java如上圖所示,并編譯它。
創(chuàng)建IbatisInsert.java如上圖所示,并編譯它。
執(zhí)行IbatisInsert二進(jìn)制文件來運(yùn)行程序。
會得到下面的結(jié)果,并創(chuàng)紀(jì)錄的將在EMPLOYEE表中創(chuàng)建。
$java IbatisInsert Going to insert record..... Record Inserted Successfully
去查看EMPLOYEE表,它應(yīng)該有如下結(jié)果:
mysql> select * from EMPLOYEE; +----+------------+-----------+--------+ | id | first_name | last_name | salary | +----+------------+-----------+--------+ | 1 | Zara | Ali | 5000 | +----+------------+-----------+--------+ 1 row in set (0.00 sec)