今天抽空写了step by step的 step 1,首先用了一个最简单的例子来说明ibatis的灵活与方便.
一些说明,
1.例子使用eclipse进行开发,所以附件的包里有eclipse的.classpath和.project文件,为了简单清晰,我尽量简化了相关的配置
2.附件带有所有需要的jar并在win2k+jdk1.4.2和fedora core 1 + jdk1.4.2上测试通过
下面正式开始....
首先建立一个简单的bean:account
| private int id; private string firstname; private string lastname; private string emailaddress; ... getters & setters |
然后写一个xml文件,就是sql mapping的配置了,比如叫account.xml
| <?xml version="1.0" encoding="utf-8"?> <!doctype sql-map public "-//ibatis.com//dtd sql map 1.0//en" "http://www.ibatis.com/dtd/sql-map.dtd";> <sql-map name="account"> <!--随便写了几个例子--> <mapped-statement name="getaccountbyname" result-class="man.argan.ibatis.domain.account"> select acc_id as id, acc_first_name as firstname, acc_last_name as lastname, acc_email as emailaddress from account where acc_first_name like #value# or acc_last_name like #value# </mapped-statement> .... </sql-map> |
这样我们需要的和业务相关的 配置就这么多了,在程序里面,我们就可以进行使用了
| account account = null; account = new account(); account = (account) sqlmap.executequeryforobject( "getaccountidandname", new integer(1), account); println("getaccountidandname/t-->account: " + account); account = (account) sqlmap.executequeryforobject("getaccountemail", new integer(4)); println("getaccountemail/t-->account: " + account); list list = sqlmap.executequeryforlist("getaccountbyname", "%阿%"); println("getaccountbyname/t-->list: " + list); |
当然,我们还需要一些关于数据库的配置,比较简单:
| <?xml version="1.0" encoding="utf-8"?> <!doctype sql-map-config public "-//ibatis.com//dtd sql map config 1.0//en" "http://www.ibatis.com/dtd/sql-map-config.dtd";> <sql-map-config> <properties resource="man/argan/ibatis/sqlmap/maps/sqlmapconfig.properties" /> <datasource name="basic" default = "true" factory-class="com.ibatis.db.sqlmap.datasource.simpledatasourcefactory"> <property name="jdbc.driver" value="${driver}"/> <property name="jdbc.connectionurl" value="${url}"/> <property name="jdbc.username" value="${username}"/> <property name="jdbc.password" value="${password}"/> </datasource> <sql-map resource="man/argan/ibatis/sqlmap/maps/account.xml" /> </sql-map-config> |
这个配置文件其实是相当于sql map的一个总控配置,我们读取配置的入口就在这里了,ibatis提供了非常方便的读取方式:
| public class sqlmapconfig { protected static final sqlmap sqlmap; static { try { // -- 取得配置信息 reader reader = resources .getresourceasreader("man/argan/ibatis/sqlmap/maps/sqlmapconfig.xml"); // 从配置信息里构造出sql map sqlmap = xmlsqlmapbuilder.buildsqlmap(reader); } catch (exception e) { // 如果读取配置信息出错,无法处理,只好抛出 throw new nestedruntimeexception("初始化sql map config 错误:" + e, e); } } public static sqlmap getsqlmap() { return sqlmap; } } |
基本上,我们需要做的就这些了,做好这些工作之后,我们就可以写一个方法来进行测试了,这时候,你可以试试改变一下配置文件里的sql语句,再运行一下,可以轻松体验一下ibatis的强大与灵活了.
点这里下载全部程序.
闽公网安备 35060202000074号