ibatis整理

来源:互联网 发布:xf adobecc2015 mac 编辑:程序博客网 时间:2024/06/07 10:59

IBATIS的优点





下面是使用iBATIS的一些优势:

  • 支持存储过程:iBATIS的SQL封装以存储过程的形式,使业务逻辑保持在数据库之外,应用程序更易于部署和测试,更便于移植。

  • 支持内嵌的SQL:预编译器不是必需的,并有完全访问所有的SQL语句的特性。

  • 支持动态SQL: iBATIS特性提供基于参数动态生成SQL查询。

  • 支持O / RM:iBATIS支持许多相同的功能作为一个O / RM工具,如延迟加载,连接抓取,缓存,运行时代码生成和继承











使用步骤:
1 下载ibatis jar包,放在lib下
2 数据库中创建EMPLOYEE表
3 创建普通Java对象类Employee.java
4 创建Employee.xml文件
<?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>
5 创建SqlMapConfig.xml文件
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE sqlMapConfigPUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN""http://ibatis.apache.org/dtd/sql-map-config-2.dtd"><sqlMapConfig>     <settings 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/testdb"/>          <property name="JDBC.Username" value="root"/>          <property name="JDBC.Password" value="root"/>        </dataSource>      </transactionManager>     <sqlMap resource="Employee.xml"/> </sqlMapConfig>
SQL语句映射的所有操作将被描述在"Employee.xml".
SqlMapConfig.xml和Employee.xml 存在于类路径
6 创建EmployeeIbatisDaoImpl.java文件
public class EmployeeIbatisDaoImpl{  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 ");  }} 








0 0