iBatis学习记录(2)

今天主要对iBatis的各种SQL语句进行了一些测试,iBatis的query一共有三种形式,分别是queryForObject, queryForList, queryForMap

queryForObject返回的是一个一个单独的实例,queryForList返回的是一组实例,而queryForMap返回一个映射表

在使用这三个方法之前,首先需要在SqlMap文件中配置好相关的resultMap,这样才能将结果集顺利返回。也就是说,必须需要一个javaBean存在,然后是一个resultMap:

  1. # <resultMap id=“UserBeanMap” class=“com.featheast.chap4.UserBean”>
  2. # <result property=“id” column=“id”/>
  3. # <result property=“uid” column=“uid”/>
  4. # <result property=“pwd” column=“pwd”/>
  5. # <result property=“email” column=“email”/>
  6. # <result property=“name” column=“name”/>
  7. # <result property=“qq” column=“qq”/>
  8. # <result property=“year” column=“year”/>
  9. # <result property=“month” column=“month”/>
  10. # <result property=“day” column=“day”/>
  11. # </resultMap>

比如如上是一个UserBean的resultMap,它包含了这个bean中的所有的属性,并且对应到了数据库表中的列。

1).queryForObject:

代码看上去是很简单的,下面是按照ID取出唯一的一个user元素

如果你试图返回一个多行的值到Object中,程序就会报错Error: executeQueryForObject returned too many results

2).queryForList:

在前面的一篇文章中已经采用了queryForList来作为实验。其实看看第一部分的代码,需要改的地方其实就是把函数名改为queryForList,然后取出各个List就好了。道理是一样的。

3).queryForMap:

唯一需要改变的地方就是要讲resultMap中的class改换为java.util.HashMap,其余的都可以按照正常的方法向下进行,的确非常易懂。

2.insert:

相比较select的复杂而言,insert就简单的多了,几乎和jdbc中一样,直接套用上去就可以了。下面给出一个例子:

  1. <insert id=“insertUser”>
  2. INSERT INTO userinfo(
  3. uid,pwd,email,name,qq,year,month,day
  4. )VALUES(
  5. #uid:VARCHAR#,#pwd:VARCHAR#,#email:VARCHAR#,#name:VARCHAR#,#qq:VARCHAR#,#year:VARCHAR#,#month:VARCHAR#,#day:VARCHAR#
  6. )
  7. </insert>

以上是sql的map结果,是不是和JDBC一样呢。然后在JAVA中的调用:

  1. UserBean user=new UserBean();
  2. user.setDay(“31111″);
  3. user.setEmail(“featheast@123.com111″);
  4. user.setMonth(“10111″);
  5. user.setName(“featheast111″);
  6. user.setPwd(“123456111″);
  7. user.setQq(“30003000111″);
  8. user.setUid(“featheast111″);
  9. user.setYear(“2008111″);
  10. sqlMap.insert(“insertUser”,user);

如果觉得每次都得在sqlmap中写得太多而繁琐的话可以用一个parametermap来代替

  1. <parameterMap class=“com.featheast.chap4.UserBean” id=“insertUserMap”>
  2. <parameter property=“uid” jdbcType=“VARCHAR”/>
  3. <parameter property=“pwd” jdbcType=“VARCHAR”/>
  4. <parameter property=“email” jdbcType=“VARCHAR”/>
  5. <parameter property=“name” jdbcType=“VARCHAR”/>
  6. <parameter property=“qq” jdbcType=“VARCHAR”/>
  7. <parameter property=“year” jdbcType=“VARCHAR”/>
  8. <parameter property=“month” jdbcType=“VARCHAR”/>
  9. <parameter property=“day” jdbcType=“VARCHAR”/>
  10. </parameterMap>

如果你的数据库中有自动增长列那么就把那一列在添加的语句中空出来就可以了。系统会自动补上的。

This entry was posted on Friday, December 26th, 2008 at 5:01 pm and is filed under IT, iBatis . You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

Comments are closed.

  • English Version

    • Cannot read Chinese? Please take a look at my English site, hope you can find more you need there!
  • 感谢支持

  • twitter

    facebook

    linkedin

  • Categories