status int ); insert into tb_brand (brand_name,company_name,ordered,description,status) VALUES("三只松鼠",'三只松面股份有限公司',5,"好吃不上火",0), ('华为','华为技术有限公司',100,'年为致力于把数字世界带入每个人、每个家庭、每个组织,均连万物互联的智能世界',1), ('小米','小米科技有服公司',50,"are you ok",1); select * from tb_brand;
<sqlid="selectAll"> id,brand_name as brandName,company_name as companyName,ordered,description,status </sql> <selectid="selectAll"resultType="com.dragonkeep.pojo.Brand"> select <includerefid="selectAll"></include> from tb_brand; </select>
<selectid="selectByCondition"resultMap="brandResultMap"> select * from tb_brand where status=#{status} and company_name like #{companyName} and brand_name like #{brandName}; </select>
<selectid="selectByCondition"resultMap="brandResultMap"> select * from tb_brand <where> <iftest="status!=null"> and status=#{status} </if> <iftest="companyName !=null and companyName!=''"> and company_name like #{companyName} </if> <iftest="brandName!=null and brandName!=''"> and brand_name like #{brandName}; </if> </where> </select>
注意:<where>能自动解决逻辑运算符的问题,<if>进行条件判断。
单条件下动态查询
如果在查询字段中,有多个选择一个字段进行匹配的话,可以使用<choose>和<when>.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
<selectid="selectByConditionSingle"resultMap="brandResultMap"> select * from tb_brand where <choose><!-- 类别switch语法--> <whentest="status!=null"> status=#{status} </when> <whentest="companyName !=null and companyName!=''"> company_name like #{companyName} </when> <whentest="brandName!=null and brandName!=''"> brand_name like #{brandName} </when> <otherwise> 1 = 1 </otherwise> </choose> </select>
添加数据
1 2 3 4
<insertid="add"> insert into tb_brand(brand_name,company_name,ordered,description,status) values (#{brandName},#{companyName},#{ordered},#{description},#{status}); </insert>
<insertid="add"useGeneratedKeys="true"keyProperty="id"> insert into tb_brand(brand_name,company_name,ordered,description,status) values (#{brandName},#{companyName},#{ordered},#{description},#{status}); </insert>
这样就可以在brand实例中使用getID获取到主键id的值。
修改数据
修改全部字段:
1 2 3 4 5 6 7 8 9 10
<updateid="update"> update tb_brand set brand_name=#{brandName}, company_name=#{companyName}, ordered=#{ordered}, description=#{description}, status=#{status} where id =#{id}; </update>