在应用SSM框架搭建网站时,一般会将SQL语句单独写成XML文件,方便进行sql语句的管理和代码的复用。
xml文件格式:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="xxx.xxx.xxx">
</mapper>
"xxx.xxx.xxx":此处应填写包含调用该xml文件中sql语句的方法的接口名;
单表操作的sql书写:
<delete id="deleteXXX">
delete from
order
where
id=#{Id}
</delete>
id:此处标签中的id为调用该标签中sql语句的方法名;
多表操作的sql书写:
<resultMap id="CCCC" type="XXX.XXX.XXX">
<id column="id" property="id" />
<result column="user_id" property="userId" />
<collection property="Items" ofType="XXX.XXX.XXX">
<id column="s.id" property="id" />
<result column="name" property="name" />
</collection>
</resultMap>
<select id="YYYY" resultMap="CCCC">
SELECT
o.id,
o.user_id
FROM order o
JOIN item i ON o.id = i.id
WHERE
oo.user_id=#{userId}
</select>
select标签内为方法为SQL语句,其中:
id中的YYYY为调用该SQL的方法;
resultMap中的CCCC为该语句在执行后返回的数据类型,此处的CCCC与resultMap标签中的id同名。
resultMap标签中:type和oftype值为返回数据对应的实体类的类名.