若要使用iBATIS執行的任何CRUD(建立,寫入,更新和刪除)操做,須要建立一個的POJO(普通Java對象)類對應的表。本課程介紹的對象,將「模式」的數據庫表中的行。html
POJO類必須實現全部執行所需的操做所需的方法。java
咱們已經在MySQL下有EMPLOYEE表:mysql
1 CREATE TABLE EMPLOYEE ( 2 id INT NOT NULL auto_increment, 3 first_name VARCHAR(20) default NULL, 4 last_name VARCHAR(20) default NULL, 5 salary INT default NULL, 6 PRIMARY KEY (id) 7 );
咱們會在Employee.java文件中建立Employee類,以下所示:sql
1 public class Employee { 2 private int id; 3 private String first_name; 4 private String last_name; 5 private int salary; 6 7 /* Define constructors for the Employee class. */ 8 public Employee() {} 9 10 public Employee(String fname, String lname, int salary) { 11 this.first_name = fname; 12 this.last_name = lname; 13 this.salary = salary; 14 } 15 } /* End of Employee */
能夠定義方法來設置表中的各個字段。下一章節將告訴你如何得到各個字段的值。數據庫
要定義使用iBATIS SQL映射語句中,咱們將使用<insert>標籤,這個標籤訂義中,咱們會定義將用於在IbatisInsert.java文件的數據庫執行SQL INSERT查詢「id」。apache
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE sqlMap 3 PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" 4 "http://ibatis.apache.org/dtd/sql-map-2.dtd"> 5 6 <sqlMap namespace="Employee"> 7 <insert id="insert" parameterClass="Employee"> 8 9 insert into EMPLOYEE(first_name, last_name, salary) 10 values (#first_name#, #last_name#, #salary#) 11 12 <selectKey resultClass="int" keyProperty="id"> 13 select last_insert_id() as id 14 </selectKey> 15 16 </insert> 17 18 </sqlMap>
這裏parameterClass:能夠採起一個值做爲字符串,整型,浮點型,double或根據要求任何類的對象。在這個例子中,咱們將經過Employee對象做爲參數而調用SqlMap類的insert方法。ui
若是您的數據庫表使用IDENTITY,AUTO_INCREMENT或串行列或已定義的SEQUENCE/GENERATOR,能夠使用<selectKey>元素在的<insert>語句中使用或返回數據庫生成的值。this
文件將應用程序級別的邏輯在Employee表中插入記錄:spa
1 import com.ibatis.common.resources.Resources; 2 import com.ibatis.sqlmap.client.SqlMapClient; 3 import com.ibatis.sqlmap.client.SqlMapClientBuilder; 4 import java.io.*; 5 import java.sql.SQLException; 6 import java.util.*; 7 8 public class IbatisInsert{ 9 public static void main(String[] args) 10 throws IOException,SQLException{ 11 Reader rd = Resources.getResourceAsReader("SqlMapConfig.xml"); 12 SqlMapClient smc = SqlMapClientBuilder.buildSqlMapClient(rd); 13 14 /* This would insert one record in Employee table. */ 15 System.out.println("Going to insert record....."); 16 Employee em = new Employee("Zara", "Ali", 5000); 17 18 smc.insert("Employee.insert", em); 19 20 System.out.println("Record Inserted Successfully "); 21 22 } 23 }
下面是步驟來編譯並運行上述軟件。請確保已在進行的編譯和執行以前,適當地設置PATH和CLASSPATH。code
建立Employee.xml如上所示。
建立Employee.java如上圖所示,並編譯它。
建立IbatisInsert.java如上圖所示,並編譯它。
執行IbatisInsert二進制文件來運行程序。
會獲得下面的結果,並創紀錄的將在EMPLOYEE表中建立。
1 $java IbatisInsert 2 Going to insert record..... 3 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)
系列文章: