ibatis入门实例讲解
之前大家上网的ibatis官方网站:http://www.ibatis.com现在已经不再存在了,已经被MyBatis所替代http://www.mybatis.org/,我现在使用了还是之前的ibatis2.3.4,所以这个例子也是针对2.3.4版本讲解的
首先呢,打开资源包,可以看到里面有一个simple_exzample的文件夹,在MyEclipse8.5中新建一个JAVA项目,将刚才的文件夹中内容复制到项目SRC下,这样的话呢,可以看到这样一个目录
这个MyTest是我后来加上的测试实实例,当然这些代码还不足以让程序测试出结果来
看看ibatis的SQL语句配置类MySqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-config-2.dtd"> <sqlMapConfig> <!-- Configure a built-in transaction manager. If you're using an app server, you probably want to use its transaction manager and a managed datasource --> <transactionManager type="JDBC" commitRequired="false"> <dataSource type="SIMPLE"> <property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/> <property name="JDBC.ConnectionURL" value="jdbc:mysql://127.0.0.1:3306/ibatis"/> <property name="JDBC.Username" value="root"/> <property name="JDBC.Password" value="root"/> </dataSource> </transactionManager> <!-- List the SQL Map XML files. They can be loaded from the classpath, as they are here (com.domain.data...) --> <sqlMap resource="com/mydomain/data/Account.xml"/> <!-- List more here... <sqlMap resource="com/mydomain/data/Order.xml"/> <sqlMap resource="com/mydomain/data/Documents.xml"/> --> </sqlMapConfig>
这里我修改了下数据源为jdbc形式的,使用的是MySQL数据库,所以要添加数据库驱动包,还有ibatis核心包,在看看数据库表该怎么建立,这得查看下Account.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="Account"> <!-- Use type aliases to avoid typing the full classname every time. --> <typeAlias alias="Account" type="com.mydomain.domain.Account"/> <!-- Result maps describe the mapping between the columns returned from a query, and the class properties. A result map isn't necessary if the columns (or aliases) match to the properties exactly. --> <resultMap id="AccountResult" class="Account"> <result property="id" column="ACC_ID"/> <result property="firstName" column="ACC_FIRST_NAME"/> <result property="lastName" column="ACC_LAST_NAME"/> <result property="emailAddress" column="ACC_EMAIL"/> </resultMap> <!-- Select with no parameters using the result map for Account class. --> <select id="selectAllAccounts" resultMap="AccountResult"> select * from ACCOUNT </select> <!-- A simpler select example without the result map. Note the aliases to match the properties of the target result class. --> <select id="selectAccountById" parameterClass="int" resultClass="Account"> select ACC_ID as id, ACC_FIRST_NAME as firstName, ACC_LAST_NAME as lastName, ACC_EMAIL as emailAddress from ACCOUNT where ACC_ID = #id# </select> <!-- Insert example, using the Account parameter class --> <insert id="insertAccount" parameterClass="Account"> insert into ACCOUNT ( ACC_FIRST_NAME, ACC_LAST_NAME, ACC_EMAIL )values ( #firstName#, #lastName#, #emailAddress# ) </insert> <!-- Update example, using the Account parameter class --> <update id="updateAccount" parameterClass="Account"> update ACCOUNT set ACC_FIRST_NAME = #firstName#, ACC_LAST_NAME = #lastName#, ACC_EMAIL = #emailAddress# where ACC_ID = #id# </update> <!-- Delete example, using an integer as the parameter class --> <delete id="deleteAccountById" parameterClass="int"> delete from ACCOUNT where ACC_ID = #id# </delete> </sqlMap>
上面的<ResultMap>标签中有指定每个Account属性对应的数据库的列名,所以就新建数据库了
这样数据建立完成后,我们就可以测试了,这回就用到了SimpleExample.java类了
package com.mydomain.data; import com.ibatis.sqlmap.client.SqlMapClient; import com.ibatis.sqlmap.client.SqlMapClientBuilder; import com.ibatis.common.resources.Resources; import com.mydomain.domain.Account; import java.io.Reader; import java.io.IOException; import java.util.List; import java.sql.SQLException; /** * This is not a best practices class. It's just an example * to give you an idea of how iBATIS works. For a more complete * example, see JPetStore 5.0 at http://www.ibatis.com. */ public class SimpleExample { /** * SqlMapClient instances are thread safe, so you only need one. * In this case, we'll use a static singleton. So sue me. ;-) */ private static SqlMapClient sqlMapper; /** * It's not a good idea to put code that can fail in a class initializer, * but for sake of argument, here's how you configure an SQL Map. */ static { try { Reader reader = Resources.getResourceAsReader("com/mydomain/data/MySqlMapConfig.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 List selectAllAccounts () throws SQLException { return sqlMapper.queryForList("selectAllAccounts"); } public static Account selectAccountById (int id) throws SQLException { return (Account) sqlMapper.queryForObject("selectAccountById", id); } public static void insertAccount (Account account) throws SQLException { sqlMapper.insert("insertAccount", account); } public static void updateAccount (Account account) throws SQLException { sqlMapper.update("updateAccount", account); } public static void deleteAccount (int id) throws SQLException { sqlMapper.delete("deleteAccountById", id); } }
像上面的增删改查中用到的代替SQL语句的映射KEY,也是可以加上相应的XML文件的配置名称的,如: return sqlMapper.queryForList("Account.selectAllAccounts")那么这个Account就是
Account.xml的名称了
真正想看到测试结果得另写个JUNIT测试类,添加junit的jar包,这里我写了MyTest.java
package com.mydomain.data; import java.sql.SQLException; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Test; import com.mydomain.domain.Account; public class MyTest { @Test public void selectAllAccounts(){ try { List list=SimpleExample.selectAllAccounts(); System.out.println(Arrays.toString(list.toArray())); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void selectAccountById(){ try { Account account=SimpleExample.selectAccountById(1); System.out.println(account); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void insertAccount(){ Account account=new Account(); account.setFirstName("tom"); account.setLastName("jam"); account.setEmailAddress("china"); try { SimpleExample.insertAccount(account); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void updateAccount(){ try { Account account=SimpleExample.selectAccountById(2); account.setFirstName("gates"); SimpleExample.updateAccount(account); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void deleteAccount(){ try { SimpleExample.deleteAccount(1); } catch (SQLException e) { e.printStackTrace(); } } }
怎么样,ibatis也不是很难吧,将所有的SQL语句统一管理起来,十分方便,对于写复杂的SQL语句也可以直接来写
顺便介绍下MyBatis
MyBatis来源于iBATIS,iBATIS是一个由Clinton Begin在2001年发起的开放源代码项目,iBATIS一词来源于“internet”和“abatis”的组合。该项目最初侧重于密码软件的开发,现在是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAO),它是著名的ORM开发框架,分为Java和.NET版本,有着众多的追随者。
iBATIS更名为MyBatis并迁移到Google Code,此次项目迁移后,将启用新的网站http://www.mybatis.org/,由于目前只是改了名字,因此仍然可直接浏览iBatis的文档。
MyBatis开发团队希望脱离Apache而独立发展,并保证不会修改授权协议(Apache License)、代码完全兼容、包名不会更改、也不会删除 Apache站上的任何相关资源。
改名后的第一次版本MyBatis 3.0.1已经发布,基于iBatis 3.0版本,该版本非常稳定,已经有很多用户使用了数周时间,修复了一些小bug。欲下载 MyBatis 3.0.1请到它新的网站http://www.mybatis.org/。 目前版本是3.0.2