1.參數註入1.1用#{0},#{1}的形式,0代表第一個參數,1代表第二個參數 public List<RecordVo> queryList(String workerId, Integer topNum); <select id="queryList" resultType="com.demo ...
1.參數註入
1.1用#{0},#{1}的形式,0代表第一個參數,1代表第二個參數
public List<RecordVo> queryList(String workerId, Integer topNum);
<select id="queryList" resultType="com.demo.RecordVo">
SELECT ID id, WORKER_ID workerId, UPDATE_DATE updateDate
FROM USER_RECORDS t
WHERE t.WORKER_ID = #{0}
LIMIT #{1}
</select>
1.2Map或者封裝對象,workerId為map裡面的鍵;如果是對象則workerId為對象中的屬性,這種方法非常常用
public Integer queryCountByWorkerId(Map queryParam);
<select id="queryCountByWorkerId" parameterType="java.util.Map" resultType="java.lang.Integer">
SELECT COUNT(1)
FROM tableName F
WHERE F.WORKER_ID = #{workerId}
</select>
1.3註解
public Integer queryCountByWorkerId(@param(“workerId”)String workerId);
<select id="queryCountByWorkerId" parameterType="java.util.Map" resultType="java.lang.Integer">
SELECT COUNT(1)
FROM tableName F
WHERE F.WORKER_ID = #{workerId}
</select>
2.返回
2.1映射<!-- 實體類與表欄位對應 -->
<resultMap type="com.demo.DataModule" id="dataModule">
<result column="ID" property="id" />
<result column="CREATE_DATE" property="createDate" />
<result column="WORKERID" property="workerId" />
<result column="UPDATE_DATE" property="updateDate" />
<result column="STATUS" property="status" />
</resultMap>
<select id="queryAll" resultType="dataModule">
select ID,CREATE_DATE,WORKERID from tableName
</select>
這種方式查詢語句查詢的欄位直接就是資料庫裡面的欄位就好了,就定義映射的column
2.2直接返回對象
<select id="queryAll" resultType="com.demo.DataModule">
select ID id,CREATE_DATE createDate,WORKERID workerId from tableName
</select>
這裡查詢返回的欄位別名必須對應返回對象中的屬性
3.執行原生sql
3.1sql參數:
public class ParamVo {
private String sql;
//getter setter 省略
}
3.2介面:
/**
* @功能描述: 創建
* @param vo
* @return
*/
public int excuteCreateSql(ParamVo vo);
/**
* @功能描述: 查詢
* @param vo
* @return
*/
public List<Map<String, Object>> excuteSelectSql(ParamVo vo);
3.3xml:
<update id="excuteCreateSql">
${sql}
</update>
${}不編譯sql直接執行,如果用#{sql}可能報錯
<select id="excuteSelectSql" resultType="java.util.Map">
${sql}
</select>
這裡不知道返回類型用map或者hashmap作為返回
4.include:有時候兩個方法要返回的欄位都一樣或者where子句一樣,這樣為了避免重覆寫代碼,就抽出來用include
4.1定義子句相同部分
<sql id="queryChild">
FROM tableName1 F
RIGHT JOIN tableName2 C ON F.WORKER_ID = C.WORKER_ID
WHERE F.STATUS = 1 AND F.WORKER_ID = #{workerId}
ORDER BY C.CREATE_DATE DESC
</sql>
4.2引用
<select id="queryCountByWorkerId" parameterType="java.util.Map" resultType="java.lang.Integer">
SELECT COUNT(1)
<include refid="queryChild"/>
</select>
<select id="queryListByWorkerId" parameterType="java.util.Map" resultType="com.demo.RecordVo">
SELECT ID id, WORKER_ID workerId, UPDATE_DATE updateDate,......
<include refid="queryChild"/>
</select>
僅供參考,不足之處還請見諒,歡迎指正!轉載請標明出處。如有疑問,歡迎評論或者聯繫我郵箱[email protected]