1. 程式人生 > >mybatis與struts直接寫原生sql例子

mybatis與struts直接寫原生sql例子

package com.test.dtjc.tdsc0005.action;

import com.opensymphony.xwork2.ActionSupport;
import com.test.dtjc.tdsc0000.common.SQLAdapter;
import com.test.dtjc.tdsc0005.model.Tdsc0005Model;

import org.apache.struts2.ServletActionContext; //key   
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

public class Tdsc0005Action extends ActionSupport{
	private static final long serialVersionUID = 1L;
	@Autowired
	private SqlSessionTemplate sqlSessionTemplate;
	@SuppressWarnings("unchecked")
	public String execute() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String cjgsGuid=request.getParameter("cjgsGuid");//字串
		String sql = "";
		sql = sql+ 
		       " SELECT "
		     + "   dbms_lob.substr(GSNR,4000)  GSNR "
		     + " FROM "
		     + " T_CJGS "
		     + " WHERE "
		     + " CJGS_GUID = '"
		     + cjgsGuid+"'";
		List<Tdsc0005Model> gsnr= sqlSessionTemplate.selectList("superSelect",new SQLAdapter(sql));
		Map<String,String> map = new HashMap<String,String>();
		map.clear();
		for (Entry<String, Integer> entry : ((Map<String, Integer>) gsnr.get(0)).entrySet()) {
			map.put(entry.getKey(), String.valueOf(entry.getValue()));
		}
		//成交公示內容
		request.setAttribute("cjgsNr",  map.get("GSNR"));
		return "success";
	}

}


1、以上程式碼中從外部獲取引數的程式碼,以url,或頁面內部某id的值

HttpServletRequest request = ServletActionContext.getRequest();
		String cjgsGuid=request.getParameter("cjgsGuid");//字串

即從 HttpServletRequest 中取得頁面或URL傳入的值

2、拼寫sql語句

sql = sql+ 
		       " SELECT "
		     + "   dbms_lob.substr(GSNR,4000)  GSNR "
		     + " FROM "
		     + " T_CJGS "
		     + " WHERE "
		     + " CJGS_GUID = '"
		     + cjgsGuid+"'";

3、呼叫 mybatis 查詢

		List<Tdsc0005Model> gsnr= sqlSessionTemplate.selectList("superSelect",new SQLAdapter(sql));

4、查詢結果取得

		Map<String,String> map = new HashMap<String,String>();
		map.clear();
		for (Entry<String, Integer> entry : ((Map<String, Integer>) gsnr.get(0)).entrySet()) {
			map.put(entry.getKey(), String.valueOf(entry.getValue()));
		}

5、返回頁面顯示內容

		request.setAttribute("cjgsNr",  map.get("GSNR"));

6、跳轉頁面

return "success";