queryForObject返回的是一个一个单独的实例,queryForList返回的是一组实例,而queryForMap返回一个映射表
在使用这三个方法之前,首先需要在SqlMap文件中配置好相关的resultMap,这样才能将结果集顺利返回。也就是说,必须需要一个javaBean存在,然后是一个resultMap:
- #
<resultMap id="UserBeanMap" class="com.featheast.chap4.UserBean"> -
#
<resultproperty="id" column="id"/> -
#
<resultproperty="uid" column="uid"/> -
#
<resultproperty="pwd" column="pwd"/> -
#
<resultproperty="email" column="email"/> -
#
<resultproperty="name" column="name"/> -
#
<resultproperty="qq" column="qq"/> -
#
<resultproperty="year" column="year"/> -
#
<resultproperty="month" column="month"/> -
#
<resultproperty="day" column="day"/> - #
</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中一样,直接套用上去就可以了。下面给出一个例子:
- <insert
id="insertUser"> -
INSERT INTO userinfo( -
uid,pwd,email,name,qq,year,month,day -
)VALUES( -
#uid:VARCHAR#,#pwd:VARCHAR#,#email:VARCHAR#,#name:VARCHAR#,#qq:VARCHAR#,#year:VARCHAR#,#month:VARCHAR#,#day:VARCHAR# -
) - </insert>
以上是sql的map结果,是不是和JDBC一样呢。然后在JAVA中的调用:
- UserBean
user= newUserBean(); - user.setDay("31111");
- user.setEmail("featheast@123.com111");
- user.setMonth("10111");
- user.setName("featheast111");
- user.setPwd("123456111");
- user.setQq("30003000111");
- user.setUid("featheast111");
- user.setYear("2008111");
- sqlMap.insert("insertUser",user);
如果觉得每次都得在sql的map中写得太多而繁琐的话,可以用一个parametermap来代替:
- <parameterMap
class="com.featheast.chap4.UserBean" id="insertUserMap"> -
<parameterproperty="uid" jdbcType="VARCHAR"/> -
<parameterproperty="pwd" jdbcType="VARCHAR"/> -
<parameterproperty="email" jdbcType="VARCHAR"/> -
<parameterproperty="name" jdbcType="VARCHAR"/> -
<parameterproperty="qq" jdbcType="VARCHAR"/> -
<parameterproperty="year" jdbcType="VARCHAR"/> -
<parameterproperty="month" jdbcType="VARCHAR"/> -
<parameterproperty="day" jdbcType="VARCHAR"/> - </parameterMap>
如果你的数据库中有自动增长列,那么就把那一列在添加的语句中空出来就可以了。系统会自动补上的。
插入表情