虽然apache已经不再维护iBATIS了。由于工作需要,我还是得学习它。这篇文章主要记录iBATIS的基本知识。这里我们,使用java + ibatis + mysql实现增删改查。
本文开发环境:
windows 7
springsource 2.9.1(eclipse 3.7)
jdk 1.7
mysql 5.5
-------------jar ------------
iBATIS 2.3.4.726
mysql-connector-java-5.1.20
最后项目的结构:
step 1:在mysql test数据库中,创建表EMPLOYEE:
- mysql> 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)
- );
step 2:创建SqlMapConfig.xml
在ibatis的主要配置文件中,我们:
使用jdbc访问数据库test;指定了访问数据库的用户名和密码信息;以及指定Employee.xml(在这个xml中定义所有与Employee相关的sql语句映射。)
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE sqlMapConfig
- PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
- "">
- <sqlMapConfig>
- <settings enhancementEnabled="true" useStatementNamespaces="true"/>
- <transactionManager type="JDBC">
- <dataSource type="SIMPLE">
- <property name="JDBC.Driver" value="com.mysql.jdbc.Driver" />
- <property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost:3306/test" />
- <property name="JDBC.Username" value="root" />
- <property name="JDBC.Password" value="root" />
- <property name="JDBC.AutoCommit" value="true" />
- </dataSource>
- </transactionManager>
- <sqlMap resource="com/phpcode8/ibatis/domain/Employee.xml"/>
- </sqlMapConfig>
step 3:创建Employee POJO类
- package com.phpcode8.ibatis.domain;
- public class Employee {
- private int id;
- private String first_name;
- private String last_name;
- private int salary;
-
- public Employee() {}
-
- public Employee(String fname, String lname, int salary) {
- this.first_name = fname;
- this.last_name = lname;
- this.salary = salary;
- }
-
-
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getFirst_name() {
- return first_name;
- }
- public void setFirst_name(String first_name) {
- this.first_name = first_name;
- }
- public String getLast_name() {
- return last_name;
- }
- public void setLast_name(String last_name) {
- this.last_name = last_name;
- }
- public int getSalary() {
- return salary;
- }
- public void setSalary(int salary) {
- this.salary = salary;
- }
- }
step 4:创建Employee.xml- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE sqlMap
- PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
- "">
- <sqlMap namespace="Employee">
- <!-- Use type aliases to avoid typing the full classname every time. -->
- <typeAlias alias="Employee" type="com.phpcode8.ibatis.domain.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>
- <select id="getAll" resultClass="Employee">
- SELECT * FROM EMPLOYEE
- </select>
- <update id="update" parameterClass="Employee">
- UPDATE EMPLOYEE
- SET first_name = #first_name#
- WHERE id = #id#
- </update>
- <delete id="delete" parameterClass="int">
- DELETE FROM EMPLOYEE
- WHERE id = #id#
- </delete>
- </sqlMap>
在上面的xml中我们为了使用iBATIS定义sql mapping语句,我们使用了标签,在insert标签中定义了一个id,这个id将会在HelloiBATIS.java中使用,它将用于向数据库中执行INSERT查询。
同理,使用
parameterClass可以取值 string,int,float,double或者其他class object。
step 5:创建java程序,调用iBATIS中定义的sql:
- package com.phpcode8.ibatis;
- import com.ibatis.common.resources.Resources;
- import com.ibatis.sqlmap.client.SqlMapClient;
- import com.ibatis.sqlmap.client.SqlMapClientBuilder;
- import com.phpcode8.ibatis.domain.Employee;
- import java.io.*;
- import java.sql.SQLException;
- import java.util.List;
- public class HelloiBATIS {
- /*
- 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)
- );
- */
- private static SqlMapClient sqlMapper;
- static {
- try {
- Reader reader = Resources.getResourceAsReader("com/phpcode8/ibatis/SqlMapConfig.xml");
- sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader);
- reader.close();
- } catch (IOException e) {
- // Fail fast.
- throw new RuntimeException("Something bad happened while building the SqlMapClient instance." + e, e);
- }
- }
-
- public static void main(String[] args) throws SQLException {
- insertEmployee();
- insertEmployee();
- insertEmployee();
- insertEmployee();
- insertEmployee();
- deleteEmployee(2);
- Employee newemp = new Employee();
- newemp.setId(5);
- newemp.setFirst_name("Update Firstname");
- updateEmployee(newemp);
- getAllEmployee();
- }
- public static void updateEmployee(Employee emp) throws SQLException {
- /* This would update one record in Employee table. */
- System.out.println("Going to update record.....");
- Employee rec = new Employee();
- rec.setId(emp.getId());
- rec.setFirst_name( emp.getFirst_name());
- sqlMapper.update("Employee.update", rec );
- System.out.println("Record updated Successfully ");
- }
- public static void getAllEmployee() throws SQLException {
- System.out.println("Going to read records.....");
- List <Employee> ems = (List<Employee>)
- sqlMapper.queryForList("Employee.getAll", null);
- Employee em = null;
- for (Employee e : ems) {
- System.out.print(" " + e.getId());
- System.out.print(" " + e.getFirst_name());
- System.out.print(" " + e.getLast_name());
- System.out.print(" " + e.getSalary());
- em = e;
- System.out.println("");
- }
- System.out.println("Records Read Successfully ");
- }
- public static void deleteEmployee(int id) throws SQLException {
- /* This would delete one record in Employee table. */
- System.out.println("Going to delete record.....");
-
- sqlMapper.delete("Employee.delete", id );
- System.out.println("Record deleted Successfully ");
- }
- public static void insertEmployee() throws SQLException {
- /* This would insert one record in Employee table. */
- System.out.println("Going to insert record.....");
- Employee em = new Employee("Zero", "Bli", 6000);
- sqlMapper.insert("Employee.insert", em);
- System.out.println("Record Inserted Successfully ");
- }
-
-
- }
在上面的程序中通过:
- Reader reader = Resources.getResourceAsReader("com/phpcode8/ibatis/SqlMapConfig.xml");
- sqlMapper = SqlMapClientBuilder.buildSqlMapClient(reader);
得到ibatis的配置文件,构建了一个SqlMapClient的实例。
sqlMapper.insert("Employee.insert", em);
这行代码中"Employee.insert对应的就是Employee.xml文件中的:
- <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>
step 6:执行HelloiBATIS,运行结果:
- Going to insert record.....
- Record Inserted Successfully
- Going to insert record.....
- Record Inserted Successfully
- Going to insert record.....
- Record Inserted Successfully
- Going to insert record.....
- Record Inserted Successfully
- Going to insert record.....
- Record Inserted Successfully
- Going to delete record.....
- Record deleted Successfully
- Going to update record.....
- Record updated Successfully
- Going to read records.....
- 1 Zero Bli 6000
- 3 Zero Bli 6000
- 4 Zero Bli 6000
- 5 Update Firstname Bli 6000
- Records Read Successfully
源代码提供下载:
.adslot-overlay {position: absolute; font-family: arial, sans-serif; background-color: rgba(0,0,0,0.65); border: 2px solid rgba(0,0,0,0.65); color: white !important; margin: 0; z-index: 2147483647; text-decoration: none; box-sizing: border-box; text-align: left;}.adslot-overlay-iframed {top: 0; left: 0; right: 0; bottom: 0;}.slotname {position: absolute; top: 0; left: 0; right: 0; font-size: 13px; font-weight: bold; padding: 3px 0 3px 6px; vertical-align: middle; background-color: rgba(0,0,0,0.45); text-overflow: ellipsis; white-space: nowrap; overflow: hidden;}.slotname span {text-align: left; text-decoration: none; text-transform: capitalize;}.revenue {position: absolute; bottom: 0; left: 0; right: 0; font-size: 11px; padding: 3px 0 3px 6px; vertial-align: middle; text-align: left; background-color: rgba(0,0,0,0.45); font-weight: bold; text-overflow: ellipsis; overflow: hidden; white-space: nowrap;}.revenue .name {color: #ccc;}.revenue .horizontal .metric {display: inline-block; padding-right: 1.5em;}.revenue .horizontal .name {padding-right: 0.5em;}.revenue .vertical .metric {display: block; line-height: 1.5em; margin-bottom: 0.5em;}.revenue .vertical .name, .revenue .vertical .value {display: block;}.revenue .square .metric, .revenue .button .metric {display: table-row;}.revenue .square .metric {line-height: 1.5em;}.revenue .square .name, .revenue .square .value, .revenue .button .value {display: table-cell;}.revenue .square .name {padding-right: 1.5em;}.revenue .button .name {display: block; margin-right: 0.5em; width: 1em; overflow: hidden; text-overflow: clip;}.revenue .button .name:first-letter {margin-right: 1.5em;}a.adslot-overlay:hover {border: 2px solid rgba(58,106,173,0.9);}a.adslot-overlay:hover .slotname {border-bottom: 1px solid rgba(81,132,210,0.9); background-color: rgba(58,106,173,0.9);}a.adslot-overlay:hover .revenue {border-top: 1px solid rgba(81,132,210,0.9); background-color: rgba(58,106,173,0.9);}div.adslot-overlay:hover {cursor: not-allowed; border: 2px solid rgba(64,64,64,0.9);}div.adslot-overlay:hover .slotname {border-bottom: 1px solid rgba(128,128,128,0.9); background-color: rgba(64,64,64,0.9);}div.adslot-overlay:hover .revenue {border-top: 1px solid rgba(128,128,128,0.9); background-color: rgba(64,64,64,0.9);}
.adslot-overlay {position: absolute; font-family: arial, sans-serif; background-color: rgba(0,0,0,0.65); border: 2px solid rgba(0,0,0,0.65); color: white !important; margin: 0; z-index: 2147483647; text-decoration: none; box-sizing: border-box; text-align: left;}.adslot-overlay-iframed {top: 0; left: 0; right: 0; bottom: 0;}.slotname {position: absolute; top: 0; left: 0; right: 0; font-size: 13px; font-weight: bold; padding: 3px 0 3px 6px; vertical-align: middle; background-color: rgba(0,0,0,0.45); text-overflow: ellipsis; white-space: nowrap; overflow: hidden;}.slotname span {text-align: left; text-decoration: none; text-transform: capitalize;}.revenue {position: absolute; bottom: 0; left: 0; right: 0; font-size: 11px; padding: 3px 0 3px 6px; vertial-align: middle; text-align: left; background-color: rgba(0,0,0,0.45); font-weight: bold; text-overflow: ellipsis; overflow: hidden; white-space: nowrap;}.revenue .name {color: #ccc;}.revenue .horizontal .metric {display: inline-block; padding-right: 1.5em;}.revenue .horizontal .name {padding-right: 0.5em;}.revenue .vertical .metric {display: block; line-height: 1.5em; margin-bottom: 0.5em;}.revenue .vertical .name, .revenue .vertical .value {display: block;}.revenue .square .metric, .revenue .button .metric {display: table-row;}.revenue .square .metric {line-height: 1.5em;}.revenue .square .name, .revenue .square .value, .revenue .button .value {display: table-cell;}.revenue .square .name {padding-right: 1.5em;}.revenue .button .name {display: block; margin-right: 0.5em; width: 1em; overflow: hidden; text-overflow: clip;}.revenue .button .name:first-letter {margin-right: 1.5em;}a.adslot-overlay:hover {border: 2px solid rgba(58,106,173,0.9);}a.adslot-overlay:hover .slotname {border-bottom: 1px solid rgba(81,132,210,0.9); background-color: rgba(58,106,173,0.9);}a.adslot-overlay:hover .revenue {border-top: 1px solid rgba(81,132,210,0.9); background-color: rgba(58,106,173,0.9);}div.adslot-overlay:hover {cursor: not-allowed; border: 2px solid rgba(64,64,64,0.9);}div.adslot-overlay:hover .slotname {border-bottom: 1px solid rgba(128,128,128,0.9); background-color: rgba(64,64,64,0.9);}div.adslot-overlay:hover .revenue {border-top: 1px solid rgba(128,128,128,0.9); background-color: rgba(64,64,64,0.9);}