<selectid="getTeacher2"resultMap="TeacherStudent2"> select * from teacher where id = #{id} </select> <resultMapid="TeacherStudent2"type="Teacher"> <!--column是一对多的外键 , 写的是一的主键的列名--> <collectionproperty="students"javaType="ArrayList"ofType="Student"column="id"select="getStudentByTeacherId"/> </resultMap> <selectid="getStudentByTeacherId"resultType="Student"> select * from student where tid = #{id} </select>
<!--需求1: 根据作者名字和博客名字来查询博客! 如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查询 select * from blog where title = #{title} and author = #{author} --> <selectid="queryBlogIf"parameterType="map"resultType="blog"> select * from blog where <iftest="title != null"> title = #{title} </if> <iftest="author != null"> and author = #{author} </if> </select>
这样写我们可以看到,如果 author 等于 null,那么查询语句为 select * from user where title=#{title},但是如果title为空呢?那么查询语句为 select * from user where and author=#{author},这是错误的 SQL 语句,如何解决呢?请看下面的 where 语句!
Where
修改上面的SQL语句;
1 2 3 4 5 6 7 8 9 10 11
<selectid="queryBlogIf"parameterType="map"resultType="blog"> select * from blog <where> <iftest="title != null"> title = #{title} </if> <iftest="author != null"> and author = #{author} </if> </where> </select>
<selectid="queryBlogForeach"parameterType="map"resultType="blog"> select * from blog <where> <!-- collection:指定输入对象中的集合属性 item:每次遍历生成的对象 open:开始遍历时的拼接字符串 close:结束时拼接的字符串 separator:遍历对象之间需要拼接的字符串 select * from blog where 1=1 and (id=1 or id=2 or id=3) --> <foreachcollection="ids"item="id"open="and ("close=")"separator="or"> id=#{id} </foreach> </where> </select>
<ListenerclassName="org.apache.catalina.core.AprLifecycleListener"SSLEngine="on" /> <!-- Prevent memory leaks due to use of particular java/javax APIs--> <ListenerclassName="org.apache.catalina.core.JreMemoryLeakPreventionListener" /> <ListenerclassName="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" /> <ListenerclassName="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />