一、主配置文件
基本作用就是配置JDBC连接的有关信息,比如URL、用户名、密码等等
二、映射文件
基本作用就是编写SQL语句,同时给每个SQL语句定义一个唯一标识(ID),在程序中通过此ID来调用这条SQL语句。
整个唯一标识sql的id为namespace+id
三、sql的参数传递
1.简单参数
1 <delete id="delete" parameterType="int"> 2 delete from t_person where id=#{id} <!—无所谓写什么都可以 à 3 </delete>
2.多个参数:使用Map包装
1 <select id="selectLikeNameAndAgeBetween" parameterType="map" resultType="Person"> 2 <include refid="selectBasic"/> where name like #{name} and age between #{age1} and #{age2} 3 </select>
1 SqlSession session = factory.openSession(); 2 Map map=new HashMap(); 3 map.put("name", "%张%"); 4 map.put("age1", 0); 5 map.put("age2", 100); 6 List persons=session.selectList(Person.class.getName()+".selectLikeNameAndAgeBetween",map); 7 8 System.out.println(((Person)(persons.get(0))).getName()); 9 session.close();
四、动态sql
1 <select id="selectIf" parameterType="map" resultType="Person"> 2 select * from t_person 3 <if test="name !=null"> 4 where name like #{name} 5 </if> 6 <if test="age !=0"> 7 and age=#{age} 8 </if> 9 </select>
注:如果name==null,则sql拼写错误。。。
1 <select id="selectWhere" parameterType="map" resultType="Person"> 2 select * from t_person 3 <where> 4 <if test="name !=null"> 5 name like #{name} 6 </if> 7 <if test="age !=0"> 8 and age=#{age} 9 </if> 10 </where> 11 </select>
注意where的闭合!!!
choose类似于switch
1 <select id="selectChoose" parameterType="map" resultType="Person"> 2 select * from t_person 3 <choose> 4 <when test="name!=null"> 5 where name like #{name} 6 </when> 7 <otherwise> 8 where name like ‘%%‘ 9 </otherwise> 10 </choose> 11 <if test="age !=0"> 12 and age=#{age} 13 </if> 14 </select>
foreach相当于in
1 <select id="selectFor" parameterType="list" resultType="Person"> 2 select * from t_person where id in 3 <foreach collection="list" item="p" open="(" close=")" separator=","> 4 #{p} 5 </foreach> 6 </select>
1 SqlSession session = factory.openSession(); 2 List l=new ArrayList(); 3 l.add(1); 4 l.add(2); 5 l.add(3); 6 l.add(4); 7 List persons=session.selectList(Person.class.getName()+".selectFor",l); 8 9 System.out.println(((Person)(persons.get(1))).getName()); 10 session.close();
时间: 2024-10-05 15:30:44