1. 程式人生 > >[效能實驗]INS山寨版(2)-資料庫及基本功能實現

[效能實驗]INS山寨版(2)-資料庫及基本功能實現

資料庫設計

在這裡插入圖片描述

那麼,轉換為sql語句就是:
注意,都用的是pg資料庫

create or replace function global_temp_update_database()
-- returns integer as
 returns text as
$body$
declare
DECLARE sql_select_max varchar(400);
         starts_with_val int:=1;
         sql_create_sequence varchar(600);
         debug_str varchar(800):='';
         sequence_name varchar(60):='';
         sql_bind_sequence varchar(800):='';
         sp_sequence_name varchar(80):='';


  BEGIN

  -- 山寨 ins 模組。

CREATE TABLE if not EXISTS "ins_post" (
"id" serial primary key,
"publish_time" timestamp (0) without time zone,
"uid" integer null,
"title" varchar(200) not null ,
"view_num" integer null default 0 ,
"like_num" integer null default 0 ,
"images" varchar(250)[] null,
"description" varchar(600),
  CONSTRAINT "FKInstPost2Member" FOREIGN KEY (uid) REFERENCES member(id)
  MATCH SIMPLE ON UPDATE CASCADE ON DELETE SET NULL
);

BEGIN
    create index "InsPostPublishIndex" on ins_post(publish_time);
    EXCEPTION
    WHEN others THEN
    RAISE EXCEPTION '(%)', SQLERRM;
END
COMMENT ON TABLE "ins_post" IS '【ins模組】帖子列表';
COMMENT ON COLUMN "ins_post"."publish_time" IS '帖子釋出時間,注意,一旦釋出通常釋出時間是不會變更的。';
COMMENT ON COLUMN "ins_post"."view_num" IS '瀏覽人數';
COMMENT ON COLUMN "ins_post"."like_num" IS '點贊人數';



CREATE TABLE if not EXISTS "ins_like" (
"uid" integer not null,
"post_id" integer not null,
"status" boolean not null default true,
"create_time" timestamp (0) without time zone not null,
CONSTRAINT "FKInsLike2Member" FOREIGN KEY ("uid") REFERENCES member(id)
  MATCH SIMPLE ON UPDATE CASCADE ON DELETE CASCADE ,
  CONSTRAINT "FKInsLike2InsPost" FOREIGN KEY ("post_id") REFERENCES ins_post(id)
  MATCH SIMPLE ON UPDATE CASCADE ON DELETE CASCADE ,
);
BEGIN
    create unique index "InsLikeUniqueCondition" on ins_like(post_id,uid);
    EXCEPTION
    WHEN others THEN
    RAISE EXCEPTION '(%)', SQLERRM;
END


BEGIN
    create index "InsLikeIndex4PostIdAndStatus" on ins_like(post_id,status);
    EXCEPTION
    WHEN others THEN
    RAISE EXCEPTION '(%)', SQLERRM;
END


COMMENT ON TABLE "ins_like" IS '【ins模組】點贊表';
COMMENT ON COLUMN "ins_like"."status" IS '點贊狀態,true表示點贊,false表示取消點贊';


return 'Done';

    end
$body$
language plpgsql;

在資料庫裡面執行成功

在這裡插入圖片描述

骨架程式碼

好了,為了加快進度,特意生成了兩張表的crud----大家都這樣的,對吧,
生成的程式碼有控制器,模型,view object,儲存過程,service程式碼以及條件查詢condition當然還有後臺的view介面。
為了簡單說明,將模型儲存過程及service的程式碼作一番說明。
sql儲存過程:

ins post表

-- 當前資料庫指令碼、儲存過程、檢視均為自動工具生成,替換之前請確認是否已經做出改動了。




/***分頁儲存過程,高效能版本***/
CREATE OR REPLACE FUNCTION public."sp_ins_ins_post_pager"(
in pageindex integer,
in pagesize integer,
in cnd_json varchar,--條件複合物件,必須為json格式。
out outline_result varchar,
out list_result varchar
)
RETURNS record
AS $BODY$
declare pagerOutLine sys_type_pager_outline;
declare totalSize integer;
declare tmpStr varchar(400);
declare json_condition json;
declare cnd_id_eq integer;
begin
list_result:='[]';
-- 組裝條件語句
json_condition:='{}'::json;
if cnd_json is not null and char_length(cnd_json)>0 then
json_condition:=cnd_json::json;
end if;
--
-- cnd_id_eq:=json_extract_path(json_condition,'cnd_id_eq'); json_extract_path返回的是json物件,不能這樣用的
cnd_id_eq:=json_condition->>'cnd_id_eq';
        if cnd_id_eq=0 then
    cnd_id_eq:=null;
    end if;
    


-- 首先獲取記錄總數

select count(*) into totalSize from
/**中間表,begin**/
(
select * from "ins_post"
where 1=1

and
case when cnd_id_eq is not null then "id"=cnd_id_eq else 1=1 end


-- 請自行條件條件語句。
--         and
--             case when cnd_name_like is not null  and char_length(cnd_name_like) > 0
--                       then  "name" LIKE CONCAT('%',cnd_name_like,'%')  else 1=1 end
order by "id" desc

)  tbl_middle
/**中間表,end**/
;


-- 然後計算beginIndex,totalPages
pagerOutLine:=sys_func_cal_pager(pageIndex,pageSize,totalSize);
-- raise notice '好了,看看pagerOutline的資料:';
-- raise notice '看看pagerOutLine裡面的資料:%,真奇怪,那麼,totalSize 是:%',pagerOutLine,totalSize;
-- 定義返回的狀態。
pagerOutLine."state":=true;
pagerOutLine."stateCode":=0;
pagerOutLine."message":='';

-- 返回相關資料。

select row_to_json(t) into outline_result from
(select pagerOutLine."state",
pagerOutLine."stateCode",
pagerOutLine."pageIndex",
pagerOutLine."pageSize",
pagerOutLine.total,
pagerOutLine."totalPages",
pagerOutLine."message") t;
select array_to_json(array_agg(row_to_json(tbl_middle))) into list_result from
/**中間表,begin**/
(
/**中間表定義,begin**/
select * from "ins_post"
where 1=1

and
case when cnd_id_eq is not null then "id"=cnd_id_eq else 1=1 end


-- 請自行條件條件語句。
--         and
--             case when cnd_name_like is not null  and char_length(cnd_name_like) > 0
--                       then  "name" LIKE CONCAT('%',cnd_name_like,'%')  else 1=1 end

order by "id" desc
/**中間表定義,end**/
limit pagerOutLine."pageSize" offset pagerOutLine."beginIndex"
)  tbl_middle
/**中間表,end**/

  ;
-- 有可能找不到記錄,這時候就返回空陣列。
if list_result is null or char_length (list_result) < 1 then
list_result:='[]';
end if;

end;

$BODY$ LANGUAGE plpgsql volatile;


-- 儲存過程 單獨一條資料
CREATE OR REPLACE FUNCTION "sp_ins_ins_post_fetch"(
in id integer,
out model_json varchar
)

RETURNS  varchar
AS $BODY$
declare tmpId integer;
declare json_result varchar;
begin
tmpId=id;
json_result:='{}'::json;
select  ((row_to_json(t))) into model_json from (select * from  "ins_post" where "ins_post"."id"=tmpId) t;
end;
$BODY$ LANGUAGE plpgsql volatile;


/***新增記錄***/
-- 儲存過程 新增記錄
CREATE OR REPLACE FUNCTION "sp_ins_ins_post_insert"(
para_publish_time timestamp(0) without time zone,
para_uid integer,
para_title character varying(200),
para_view_num integer,
para_like_num integer,
--   (-_-) 注意,這個欄位是陣列來的,然而jdbc沒有陣列支援,這裡先用varchar代替,在呼叫時候將原本的陣列轉換一下即可。
para_images varchar,
para_description character varying(600),
out op_result varchar
)
RETURNS  varchar
AS $BODY$

declare tmpId integer;
declare tmpId_str varchar;
declare opResult sys_type_operation_outline;
declare logic_allow boolean;
declare c_v_publish_time timestamp(0) without time zone;
declare c_v_uid integer;
declare c_v_title character varying(200);
declare c_v_view_num integer;
declare c_v_like_num integer;
--   (-_-) 注意,這個欄位是陣列來的,然而jdbc沒有陣列支援,這裡先用varchar代替,在呼叫時候將原本的陣列轉換一下即可。
declare c_v_images character varying(250)[];
declare c_v_description character varying(600);

begin
logic_allow:=false;
-- 請先開啟相關操作。
if logic_allow = false then
opResult.message:=config('errors','logic_not_allow','message');
opResult."stateCode":=config('errors','logic_not_allow','code');
opResult."state":=false;
select row_to_json(t) into op_result from ( select opResult.state,opResult."stateCode",opResult.message  ) t;
return;
end if;

opResult.state:=false;
opResult."stateCode":=0;
opResult.message:='';
-- 正式的引數賦值
        c_v_publish_time:=para_publish_time;
        c_v_uid:=para_uid;
        c_v_title:=para_title;
        c_v_view_num:=para_view_num;
        c_v_like_num:=para_like_num;
c_v_images := string_to_array(para_images, ',')::character varying(250)[];
        c_v_description:=para_description;

INSERT INTO "ins_post"(
-- 主鍵不插入記錄。
 "publish_time"
 ,  "uid"
 ,  "title"
 ,  "view_num"
 ,  "like_num"
 ,  "images"
 ,  "description"
)
VALUES (
 c_v_publish_time
 ,  c_v_uid
 ,  c_v_title
 ,  c_v_view_num
 ,  c_v_like_num
 ,  c_v_images
 ,  c_v_description
);
if FOUND then
opResult.message:='儲存成功';
opResult."stateCode":=0;
opResult."state":=true;
else
opResult.message:='儲存失敗';
opResult."stateCode":=0;
opResult."state":=false;
end if;

if opResult.state=true then
select row_to_json(t) into op_result from ( select opResult.state,opResult."stateCode",opResult.message,currval(pg_get_serial_sequence('ins_post', 'id')) as data  ) t;
else
select row_to_json(t) into op_result from ( select opResult.state,opResult."stateCode",opResult.message  ) t;
end if;


end;
$BODY$ LANGUAGE plpgsql volatile;



/***更新記錄***/
-- 儲存過程 更新記錄
CREATE OR REPLACE FUNCTION "sp_ins_ins_post_update"(
para_publish_time timestamp(0) without time zone,
para_uid integer,
para_title character varying(200),
para_view_num integer,
para_like_num integer,
--   (-_-) 注意,這個欄位是陣列來的,然而jdbc沒有陣列支援,這裡先用varchar代替,在呼叫時候將原本的陣列轉換一下即可。
para_images varchar,
para_description character varying(600),
para_id integer,
out op_result varchar
)
RETURNS  varchar
AS $BODY$

declare tmpId integer;
declare tmpId_str varchar;
declare opResult sys_type_operation_outline;
declare logic_allow boolean;
declare record_primary_key integer;
declare c_v_publish_time timestamp(0) without time zone;
declare c_v_uid integer;
declare c_v_title character varying(200);
declare c_v_view_num integer;
declare c_v_like_num integer;
--   (-_-) 注意,這個欄位是陣列來的,然而jdbc沒有陣列支援,這裡先用varchar代替,在呼叫時候將原本的陣列轉換一下即可。
declare c_v_images character varying(250)[];
declare c_v_description character varying(600);

begin
logic_allow:=false;
-- 請先開啟相關操作。
if logic_allow = false then
opResult.message:=config('errors','logic_not_allow','message');
opResult."stateCode":=config('errors','logic_not_allow','code');
opResult."state":=false;
select row_to_json(t) into op_result from ( select opResult.state,opResult."stateCode",opResult.message  ) t;
return;
end if;

opResult.state:=false;
opResult."stateCode":=0;
opResult.message:='';


-- 正式的引數賦值
record_primary_key:=para_id;
            c_v_publish_time:=para_publish_time;
            c_v_uid:=para_uid;
            c_v_title:=para_title;
            c_v_view_num:=para_view_num;
            c_v_like_num:=para_like_num;
            c_v_images := string_to_array(para_images, ',')::character varying(250)[];
            c_v_description:=para_description;

update "ins_post" set
-- 主鍵不插入記錄。
 "publish_time"=c_v_publish_time
 ,  "uid"=c_v_uid
 ,  "title"=c_v_title
 ,  "view_num"=c_v_view_num
 ,  "like_num"=c_v_like_num
 ,  "images"=c_v_images
 ,  "description"=c_v_description
    where "id"=record_primary_key
;
if FOUND then
opResult.message:='儲存成功';
opResult."stateCode":=0;
opResult."state":=true;
else
opResult.message:='儲存失敗';
opResult."stateCode":=0;
opResult."state":=false;
end if;

if opResult.state=true then
select row_to_json(t) into op_result from ( select opResult.state,opResult."stateCode",opResult.message,record_primary_key as data  ) t;
else
select row_to_json(t) into op_result from ( select opResult.state,opResult."stateCode",opResult.message  ) t;
end if;


end;
$BODY$ LANGUAGE plpgsql volatile;

/***刪除記錄***/
-- 儲存過程 刪除記錄
CREATE OR REPLACE FUNCTION "sp_ins_ins_post_delete"(
para_id integer,
out op_result varchar
)
RETURNS  varchar
AS $BODY$

declare tmpId integer;
declare tmpId_str varchar;
declare opResult sys_type_operation_outline;
declare logic_allow boolean;
declare record_primary_key integer;

begin
logic_allow:=false;
-- 請先開啟相關操作。
if logic_allow = false then
opResult.message:=config('errors','logic_not_allow','message');
opResult."stateCode":=config('errors','logic_not_allow','code');
opResult."state":=false;
select row_to_json(t) into op_result from ( select opResult.state,opResult."stateCode",opResult.message  ) t;
return;
end if;

opResult.state:=false;
opResult."stateCode":=0;
opResult.message:='';


-- 正式的引數賦值
record_primary_key:=para_id;
delete from  "ins_post"
where "ins_post"."id"=record_primary_key
;
if FOUND then
opResult.message:='刪除成功';
opResult."stateCode":=0;
opResult."state":=true;
else
opResult.message:='刪除失敗';
opResult."stateCode":=0;
opResult."state":=false;
end if;

if opResult.state=true then
select row_to_json(t) into op_result from ( select opResult.state,opResult."stateCode",opResult.message,record_primary_key as data  ) t;
else
select row_to_json(t) into op_result from ( select opResult.state,opResult."stateCode",opResult.message  ) t;
end if;


end;
$BODY$ LANGUAGE plpgsql volatile;


ins like 表

-- 當前資料庫指令碼、儲存過程、檢視均為自動工具生成,替換之前請確認是否已經做出改動了。




/***分頁儲存過程,高效能版本***/
CREATE OR REPLACE FUNCTION public."sp_ins_ins_like_pager"(
in pageindex integer,
in pagesize integer,
in cnd_json varchar,--條件複合物件,必須為json格式。
out outline_result varchar,
out list_result varchar
)
RETURNS record
AS $BODY$
declare pagerOutLine sys_type_pager_outline;
declare totalSize integer;
declare tmpStr varchar(400);
declare json_condition json;
begin
list_result:='[]';
-- 組裝條件語句
json_condition:='{}'::json;
if cnd_json is not null and char_length(cnd_json)>0 then
json_condition:=cnd_json::json;
end if;
--



-- 首先獲取記錄總數

select count(*) into totalSize from
/**中間表,begin**/
(
select * from "ins_like"
where 1=1

-- 請自行條件條件語句。
--         and
--             case when cnd_name_like is not null  and char_length(cnd_name_like) > 0
--                       then  "name" LIKE CONCAT('%',cnd_name_like,'%')  else 1=1 end

)  tbl_middle
/**中間表,end**/
;


-- 然後計算beginIndex,totalPages
pagerOutLine:=sys_func_cal_pager(pageIndex,pageSize,totalSize);
-- raise notice '好了,看看pagerOutline的資料:';
-- raise notice '看看pagerOutLine裡面的資料:%,真奇怪,那麼,totalSize 是:%',pagerOutLine,totalSize;
-- 定義返回的狀態。
pagerOutLine."state":=true;
pagerOutLine."stateCode":=0;
pagerOutLine."message":='';

-- 返回相關資料。

select row_to_json(t) into outline_result from
(select pagerOutLine."state",
pagerOutLine."stateCode",
pagerOutLine."pageIndex",
pagerOutLine."pageSize",
pagerOutLine.total,
pagerOutLine."totalPages",
pagerOutLine."message") t;
select array_to_json(array_agg(row_to_json(tbl_middle))) into list_result from
/**中間表,begin**/
(
/**中間表定義,begin**/
select * from "ins_like"
where 1=1

-- 請自行條件條件語句。
--         and
--             case when cnd_name_like is not null  and char_length(cnd_name_like) > 0
--                       then  "name" LIKE CONCAT('%',cnd_name_like,'%')  else 1=1 end

/**中間表定義,end**/
limit pagerOutLine."pageSize" offset pagerOutLine."beginIndex"
)  tbl_middle
/**中間表,end**/

  ;
-- 有可能找不到記錄,這時候就返回空陣列。
if list_result is null or char_length (list_result) < 1 then
list_result:='[]';
end if;

end;

$BODY$ LANGUAGE plpgsql volatile;


/***新增記錄***/
-- 儲存過程 新增記錄
CREATE OR REPLACE FUNCTION "sp_ins_ins_like_insert"(
para_uid integer,
para_post_id integer,
para_status boolean,
para_create_time timestamp(0) without time zone,
out op_result varchar
)
RETURNS  varchar
AS $BODY$

declare tmpId integer;
declare tmpId_str varchar;
declare opResult sys_type_operation_outline;
declare logic_allow boolean;
declare c_v_uid integer;
declare c_v_post_id integer;
declare c_v_status boolean;
declare c_v_create_time timestamp(0) without time zone;

begin
logic_allow:=false;
-- 請先開啟相關操作。
if logic_allow = false then
opResult.message:=config('errors','logic_not_allow','message');
opResult."stateCode":=config('errors','logic_not_allow','code');
opResult."state":=false;
select row_to_json(t) into op_result from ( select opResult.state,opResult."stateCode",opResult.message  ) t;
return;
end if;

opResult.state:=false;
opResult."stateCode":=0;
opResult.message:='';
-- 正式的引數賦值
        c_v_uid:=para_uid;
        c_v_post_id:=para_post_id;
        c_v_status:=para_status;
        c_v_create_time:=para_create_time;

INSERT INTO "ins_like"(
 "uid"
 ,  "post_id"
 ,  "status"
 ,  "create_time"
)
VALUES (
 c_v_uid
 ,  c_v_post_id
 ,  c_v_status
 ,  c_v_create_time
);
if FOUND then
opResult.message:='儲存成功';
opResult."stateCode":=0;
opResult."state":=true;
else
opResult.message:='儲存失敗';
opResult."stateCode":=0;
opResult."state":=false;
end if;

if opResult.state=true then
select row_to_json(t) into op_result from ( select opResult.state,opResult."stateCode",opResult.message,'' as data  ) t;
else
select row_to_json(t) into op_result from ( select opResult.state,opResult."stateCode",opResult.message  ) t;
end if;


end;
$BODY$ LANGUAGE plpgsql volatile;





模型:

package net.w2p.DevBase.model.ins;
import java.util.Date;
import java.sql.*;
import java.util.List;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.sql.Timestamp;
/**

* @author MR white
* @version 2.00
* id
*/
public class PostModel {

public PostModel(){
this.setNULL();
}

public   Integer  id=0;
public void setId(Integer id){
    this.id=id;
}
public Integer getId(){
    return this.id;
}
public   Timestamp  publish_time=new Timestamp(new Date().getTime());
public void setPublish_time(Timestamp publish_time){
    this.publish_time=publish_time;
}
public Timestamp getPublish_time(){
    return this.publish_time;
}
public   Integer  uid=0;
public void setUid(Integer uid){
    this.uid=uid;
}
public Integer getUid(){
    return this.uid;
}
public   String  title="";
public void setTitle(String title){
    this.title=title;
}
public String getTitle(){
    return this.title;
}
public   Integer  view_num=0;
public void setView_num(Integer view_num){
    this.view_num=view_num;
}
public Integer getView_num(){
    return this.view_num;
}
public   Integer  like_num=0;
public void setLike_num(Integer like_num){
    this.like_num=like_num;
}
public Integer getLike_num(){
    return this.like_num;
}
public   String[]  images=new String[]{};
public void setImages(String[] images){
    this.images=images;
}
public String[] getImages(){
    return this.images;
}
public   String  description="";
public void setDescription(String description){
    this.description=description;
}
public String getDescription(){
    return this.description;
}


public void setNULL(){
    this.id=null;
    this.publish_time=null;
    this.uid=null;
    this.title=null;
    this.view_num=null;
    this.like_num=null;
    this.images=null;
    this.description=null;
}

public void resetDefaultVal(){
    this.id=0;
    this.publish_time=new Timestamp(new Date().getTime());
    this.uid=0;
    this.title="";
    this.view_num=0;
    this.like_num=0;
    this.images=new String[]{};
    this.description="";
}


}
package net.w2p.DevBase.model.ins;
import java.util.Date;
import java.sql.*;
import java.util.List;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.sql.Timestamp;
/**

* @author MR white
* @version 2.00
*/
public class LikePostModel {

public LikePostModel(){
this.setNULL();
}

public   Integer  uid=0;
public void setUid(Integer uid){
    this.uid=uid;
}
public Integer getUid(){
    return this.uid;
}
public   Integer  post_id=0;
public void setPost_id(Integer post_id){
    this.post_id=post_id;
}
public Integer getPost_id(){
    return this.post_id;
}
public   Boolean  status=false;
public void setStatus(Boolean status){
    this.status=status;
}
public Boolean getStatus(){
    return this.status;
}
public   Timestamp  create_time=new Timestamp(new Date().getTime());
public void setCreate_time(Timestamp create_time){
    this.create_time=create_time;
}
public Timestamp getCreate_time(){
    return this.create_time;
}


public void setNULL(){
    this.uid=null;
    this.post_id=null;
    this.status=null;
    this.create_time=null;
}

public void resetDefaultVal(){
    this.uid=0;
    this.post_id=0;
    this.status=false;
    this.create_time=new Timestamp(new Date().getTime());
}


}

service服務層
服務層用於呼叫儲存過程—額,提一句,這個網站分層中,資料庫的業務只會呼叫儲存過程,並不會將sql分散到java程式碼中去的:

package net.w2p.DevBase.service.ins;
import net.w2p.DevBase.model.ins.PostModel;
import net.w2p.DevBase.vo.ins.Post;
import net.w2p.DevBase.searcher.ins.PostCondition;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.SqlSession;
import org.apache.commons.lang.StringUtils;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
import net.w2p.Shared.common.*;
import net.w2p.Shared.queries.*;
import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.jdbc.core.*;
import net.w2p.Shared.mybatis.TypeHandlers.*;
import org.apache.ibatis.type.JdbcType;
/******************************************/

/**
* <p>Title: Postmodel</p>
*
* <p>Description: Post MODEL 處理類</p>
*
* <p>Copyright: Copyright (c) 2017</p>
*
* <p>Company: BLD</p>
*
* @author Mr White 電話:
* @vers
**/
@Service
public class PostService {

private static final String serial_name="ins_post";
private Logger logger=Logger.getLogger(this.getClass());
@Autowired
JdbcTemplate jdbcTemplate;
@Autowired
DoubleArrayTypeHandler doubleArrayTypeHandler;
@Autowired
IntegerArrayTypeHandler integerArrayTypeHandler;
@Autowired
ShortArrayTypeHandler shortArrayTypeHandler;
@Autowired
StringArrayTypeHandler stringArrayTypeHandler;
@Autowired
LongArrayTypeHandler longArrayTypeHandler;
@Autowired
BooleanArrayTypeHandler booleanArrayTypeHandler;
@Autowired
JsonArrayTypeHandler jsonArrayTypeHandler;
@Autowired
JsonTypeHandler jsonTypeHandler;

/**
* 獲取搜尋分頁列表
* @param condition 條件。
* ***/
public PagerResult<Post> pager(
    int pageindex,
    int pagesize,
    PostCondition condition,
    Boolean needCompleteInfo
    ){

    final HashMap<String,Integer> map_out_paras=new HashMap<>();
    PagerResult<Post> pagerResult=new PagerResult<>();
    final String sql="{ call \"sp_ins_ins_post_pager\"(?,?,?,?,?)}";


CallableStatementCreator stCreator=new CallableStatementCreator() {
        @Override
        public CallableStatement createCallableStatement(Connection con) throws SQLException {
        CallableStatement st=con.prepareCall(sql);
        int paraIndex=0;
        paraIndex++;st.setInt(paraIndex,pageindex);
        paraIndex++;st.setInt(paraIndex,pagesize);
        paraIndex++;st.setString(paraIndex,JSONObject.toJSONString(condition));
        paraIndex++;st.registerOutParameter(paraIndex,Types.VARCHAR);map_out_paras.put("outline_result",paraIndex);
        paraIndex++;st.registerOutParameter(paraIndex,Types.VARCHAR);map_out_paras.put("list_result",paraIndex);
        return st;
        }
        };

CallableStatementCallback<PagerResult<Post>> stCallback=new CallableStatementCallback<PagerResult<Post>>(){
@Override
public PagerResult<Post> doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {
PagerResult<Post> pager=new PagerResult<>();
List<Post> list=new ArrayList<>();
cs.execute();
ResultSet rs=(ResultSet)cs.getResultSet();
String outline_result=cs.getString(map_out_paras.get("outline_result"));
String list_result=cs.getString(map_out_paras.get("list_result"));
System.out.println(outline_result);
pager=JSONObject.parseObject(outline_result,PagerResult.class);
list=JSONObject.parseArray(list_result,Post.class);
pager.setData(new ArrayList<>());
for(Post item:list){
pager.getData().add(item);
}
//                if (rs.next()){
//                    String json_str=rs.getString(1);
//                    if(ValidateUtils.isEmpty(json_str)){
//return pager;
//                    }
//                    pager=JSONObject.parseObject(json_str,PagerResult.class);
//                }
if(rs!=null){
rs.close();
}
cs.getConnection().setAutoCommit(true);
return pager;
}
};
pagerResult=jdbcTemplate.execute(stCreator,stCallback);
if(needCompleteInfo){
completeInfo(pagerResult.getData());
}
return pagerResult;
}

/**
* 獲取搜尋分頁列表
* @param condition 條件。
* ***/
public PagerResult<Post> pager(
int pageindex,
int pagesize,
PostCondition condition

){
PagerResult<Post> pagerResult=new PagerResult<>();
pagerResult=pager(pageindex,pagesize,condition,true);
return pagerResult;
}

/***crud模式生成 begin***/

    /**
    * 獲取記錄詳情
    * @param id 主鍵id
    * ***/

public Post getDetail(Integer id){
return getDetail(id,true);
}

public Post getDetail(
Integer id
,Boolean needCompleteInfo
){

final HashMap<String,Integer> map_out_paras=new HashMap<>();
Post detailVo=null;
final String sql="{ call \"sp_ins_ins_post_fetch\"(?,?)}";

CallableStatementCreator stCreator=new CallableStatementCreator() {
@Override
public CallableStatement createCallableStatement(Connection con) throws SQLException {
CallableStatement st=con.prepareCall(sql);
int paraIndex=0;
paraIndex++; st.setObject(paraIndex,id);
paraIndex++;st.registerOutParameter(paraIndex,Types.VARCHAR);map_out_paras.put("model_json",paraIndex);
return st;
}
};

CallableStatementCallback<Post> stCallback=new CallableStatementCallback<Post>(){
    @Override
    public Post doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {
    Post res=new Post();
    cs.execute();
    ResultSet rs=(ResultSet)cs.getResultSet();
    String model_json=cs.getString(map_out_paras.get("model_json"));
    res=JSONObject.parseObject(model_json,Post.class);
    if(rs!=null){
    rs.close();
    }
    cs.getConnection().setAutoCommit(true);
    return res;
    }
    };
    detailVo=jdbcTemplate.execute(stCreator,stCallback);
ArrayList<Post> list=new ArrayList<Post>();
list.add(detailVo);
if(needCompleteInfo){
completeInfo(list);
}
    return detailVo;
    }


/***crud模式生成 end***/




    /*********crud begin***********/

/***
* 新增記錄
***/
public OpResult insert(PostModel model)
{
    int totalParaCount=7 + 1;//--儲存過程引數總個數。,其中1個out 引數
    String procName="sp_ins_ins_post_insert";
    final HashMap<String,Integer> map_out_paras=new HashMap<>();
    int theParamIndex=0;
    OpResult opResult=new OpResult();
    StringBuilder paraStr=new StringBuilder();
    String callable_para_str="";
    for(int i=0;i<totalParaCount;i++){
    paraStr.append('?');
    paraStr.append(',');
    }
    if(totalParaCount>0){
    paraStr.append(',');
    callable_para_str=(paraStr.toString().replaceFirst(",,",""));
    }
    final String sql="{ call \""+procName+"\"("+callable_para_str+")}";

    CallableStatementCreator stCreator=new CallableStatementCreator() {
    @Override
    public CallableStatement createCallableStatement(Connection con) throws SQLException {
    CallableStatement st=con.prepareCall(sql);
    int paraIndex=0;

paraIndex++; st.setTimestamp(paraIndex,model.publish_time);
paraIndex++; st.setObject(paraIndex,model.uid);
paraIndex++; st.setString(paraIndex,model.title);
paraIndex++; st.setObject(paraIndex,model.view_num);
paraIndex++; st.setObject(paraIndex,model.like_num);
paraIndex++; stringArrayTypeHandler.setParameter(st,paraIndex,model.images, JdbcType.VARCHAR);
paraIndex++; st.setString(paraIndex,model.description);
paraIndex++;st.registerOutParameter(paraIndex,Types.VARCHAR);map_out_paras.put("op_result",paraIndex);
return st;
}
};

    CallableStatementCallback<OpResult> stCallback=new CallableStatementCallback<OpResult>(){
    @Override
    public OpResult doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {
    OpResult op_result=new OpResult();
    cs.execute();
    ResultSet rs=(ResultSet)cs.getResultSet();
    String json_op_result=cs.getString(map_out_paras.get("op_result"));
    op_result=JSONObject.parseObject(json_op_result,OpResult.class);
    if(rs!=null){
    rs.close();
    }
    cs.getConnection().setAutoCommit(true);
    return op_result;
    }
    };
    opResult=jdbcTemplate.execute(stCreator,stCallback);
    return opResult;
}



    /***
    * 更新記錄
    ***/
public OpResult update(PostModel model)
{
        int totalParaCount=7  + 1 + 1;//--儲存過程引數總個數。其中一個out引數
    String procName="sp_ins_ins_post_update";
    final HashMap<String,Integer> map_out_paras=new HashMap<>();
    int theParamIndex=0;
    OpResult opResult=new OpResult();
    StringBuilder paraStr=new StringBuilder();
    String callable_para_str="";
    for(int i=0;i<totalParaCount;i++){
    paraStr.append('?');
    paraStr.append(',');
    }
    if(totalParaCount>0){
    paraStr.append(',');
    callable_para_str=(paraStr.toString().replaceFirst(",,",""));
    }
    final String sql="{ call \""+procName+"\"("+callable_para_str+")}";

    CallableStatementCreator stCreator=new CallableStatementCreator() {
    @Override
    public CallableStatement createCallableStatement(Connection con) throws SQLException {
    CallableStatement st=con.prepareCall(sql);
    int paraIndex=0;
paraIndex++; st.setTimestamp(paraIndex,model.publish_time);
paraIndex++; st.setObject(paraIndex,model.uid);
paraIndex++; st.setString(paraIndex,model.title);
paraIndex++; st.setObject(paraIndex,model.view_num);
paraIndex++; st.setObject(paraIndex,model.like_num);
paraIndex++; stringArrayTypeHandler.setParameter(st,paraIndex,model.images, JdbcType.VARCHAR);
paraIndex++; st.setString(paraIndex,model.description);
    paraIndex++; st.setObject(paraIndex,model.id);
    paraIndex++;st.registerOutParameter(paraIndex,Types.VARCHAR);map_out_paras.put("op_result",paraIndex);
    return st;
    }
    };

    CallableStatementCallback<OpResult> stCallback=new CallableStatementCallback<OpResult>(){
    @Override
    public OpResult doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {
    OpResult op_result=new OpResult();
    cs.execute();
    ResultSet rs=(ResultSet)cs.getResultSet();
    String json_op_result=cs.getString(map_out_paras.get("op_result"));
    op_result=JSONObject.parseObject(json_op_result,OpResult.class);

    if(rs!=null){
    rs.close();
    }
    cs.getConnection().setAutoCommit(true);
    return op_result;
    }
    };
    opResult=jdbcTemplate.execute(stCreator,stCallback);
    return opResult;
    }


    /***
    * 刪除記錄
    ***/

    public OpResult delete(
    Integer para_id
    ){
    int totalParaCount=1 + 1;//--儲存過程引數總個數。其中一個out引數
    String procName="sp_ins_ins_post_delete";
    final HashMap<String,Integer> map_out_paras=new HashMap<>();
    int theParamIndex=0;
    OpResult opResult=new OpResult();
    StringBuilder paraStr=new StringBuilder();
    String callable_para_str="";
    for(int i=0;i<totalParaCount;i++){
    paraStr.append('?');
    paraStr.append(',');
    }
    if(totalParaCount>0){
    paraStr.append(',');
    callable_para_str=(paraStr.toString().replaceFirst(",,",""));
    }
    final String sql="{ call \""+procName+"\"("+callable_para_str+")}";
    CallableStatementCreator stCreator=new CallableStatementCreator() {
    @Override
    public CallableStatement createCallableStatement(Connection con) throws SQLException {
    CallableStatement st=con.prepareCall(sql);
    int paraIndex=0;
    paraIndex++; st.setObject(paraIndex,para_id);
    paraIndex++;st.registerOutParameter(paraIndex,Types.VARCHAR);map_out_paras.put("op_result",paraIndex);
    return st;
    }
    };

    CallableStatementCallback<OpResult> stCallback=new CallableStatementCallback<OpResult>(){
    @Override
    public OpResult doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {
    OpResult op_result=new OpResult();
    cs.execute();
    ResultSet rs=(ResultSet)cs.getResultSet();
    String json_op_result=cs.getString(map_out_paras.get("op_result"));
    op_result=JSONObject.parseObject(json_op_result,OpResult.class);

    if(rs!=null){
    rs.close();
    }
    cs.getConnection().setAutoCommit(true);
    return op_result;
    }
    };
    opResult=jdbcTemplate.execute(stCreator,stCallback);
    return opResult;
    }





    /**********crud end**********/

private void completeInfo(ArrayList<Post> list){
if(list==null||list.size()<1){

return;
}


}


}

package net.w2p.DevBase.service.ins;
import net.w2p.DevBase.model.ins.LikePostModel;
import net.w2p.DevBase.vo.ins.LikePost;
import net.w2p.DevBase.searcher.ins.LikePostCondition;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.SqlSession;
import org.apache.commons.lang.StringUtils;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
import net.w2p.Shared.common.*;
import net.w2p.Shared.queries.*;
import java.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.jdbc.core.*;
import net.w2p.Shared.mybatis.TypeHandlers.*;
import org.apache.ibatis.type.JdbcType;
/******************************************/

/**
* <p>Title: LikePostmodel</p>
*
* <p>Description: LikePost MODEL 處理類</p>
*
* <p>Copyright: Copyright (c) 2017</p>
*
* <p>Company: BLD</p>
*
* @author Mr White 電話:
* @vers
**/
@Service
public class LikePostService {

private static final String serial_name="ins_like";
private Logger logger=Logger.getLogger(this.getClass());
@Autowired
JdbcTemplate jdbcTemplate;
@Autowired
DoubleArrayTypeHandler doubleArrayTypeHandler;
@Autowired
IntegerArrayTypeHandler integerArrayTypeHandler;
@Autowired
ShortArrayTypeHandler shortArrayTypeHandler;
@Autowired
StringArrayTypeHandler stringArrayTypeHandler;
@Autowired
LongArrayTypeHandler longArrayTypeHandler;
@Autowired
BooleanArrayTypeHandler booleanArrayTypeHandler;
@Autowired
JsonArrayTypeHandler jsonArrayTypeHandler;
@Autowired
JsonTypeHandler jsonTypeHandler;

/**
* 獲取搜尋分頁列表
* @param condition 條件。
* ***/
public PagerResult<LikePost> pager(
    int pageindex,
    int pagesize,
    LikePostCondition condition,
    Boolean needCompleteInfo
    ){

    final HashMap<String,Integer> map_out_paras=new HashMap<>();
    PagerResult<LikePost> pagerResult=new PagerResult<>();
    final String sql="{ call \"sp_ins_ins_like_pager\"(?,?,?,?,?)}";


CallableStatementCreator stCreator=new CallableStatementCreator() {
        @Override
        public CallableStatement createCallableStatement(Connection con) throws SQLException {
        CallableStatement st=con.prepareCall(sql);
        int paraIndex=0;
        paraIndex++;st.setInt(paraIndex,pageindex);
        paraIndex++;st.setInt(paraIndex,pagesize);
        paraIndex++;st.setString(paraIndex,JSONObject.toJSONString(condition));
        paraIndex++;st.registerOutParameter(paraIndex,Types.VARCHAR);map_out_paras.put("outline_result",paraIndex);
        paraIndex++;st.registerOutParameter(paraIndex,Types.VARCHAR);map_out_paras.put("list_result",paraIndex);
        return st;
        }
        };

CallableStatementCallback<PagerResult<LikePost>> stCallback=new CallableStatementCallback<PagerResult<LikePost>>(){
@Override
public PagerResult<LikePost> doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {
PagerResult<LikePost> pager=new PagerResult<>();
List<LikePost> list=new ArrayList<>();
cs.execute();
ResultSet rs=(ResultSet)cs.getResultSet();
String outline_result=cs.getString(map_out_paras.get("outline_result"));
String list_result=cs.getString(map_out_paras.get("list_result"));
System.out.println(outline_result);
pager=JSONObject.parseObject(outline_result,PagerResult.class);
list=JSONObject.parseArray(list_result,LikePost.class);
pager.setData(new ArrayList<>());
for(LikePost item:list){
pager.getData().add(item);
}
//                if (rs.next()){
//                    String json_str=rs.getString(1);
//                    if(ValidateUtils.isEmpty(json_str)){
//return pager;
//                    }
//                    pager=JSONObject.parseObject(json_str,PagerResult.class);
//                }
if(rs!=null){
rs.close();
}
cs.getConnection().setAutoCommit(true);
return pager;
}
};
pagerResult=jdbcTemplate.execute(stCreator,stCallback);
if(needCompleteInfo){
completeInfo(pagerResult.getData());
}
return pagerResult;
}

/**
* 獲取搜尋分頁列表
* @param condition 條件。
* ***/
public PagerResult<LikePost> pager(
int pageindex,
int pagesize,
LikePostCondition condition

){
PagerResult<LikePost> pagerResult=new PagerResult<>();
pagerResult=pager(pageindex,pagesize,condition,true);
return pagerResult;
}
/**非crud,無須生成**/




private void completeInfo(ArrayList<LikePost> list){
if(list==null||list.size()<1){

return;
}


}


}

初步執行邏輯:

在這裡插入圖片描述

在這裡插入圖片描述

好了,增刪改查定義好了,不過crud沒什麼用,最多是節省後臺操作而已。下面繼續開發相關介面及功能。

功能簡述

假設我們的用例圖如下—嗯,一切從簡,不是正式專案,實現為主。

在這裡插入圖片描述

那麼功能點就可以確定了,所以根據這幾個功能開發如下:

儲存過程:





/*業務邏輯,釋出帖子*/

CREATE OR REPLACE FUNCTION "sp_ins_ins_post_publish"(
para_uid integer,
para_title character varying,
--   (-_-) 注意,這個欄位是陣列來的,然而jdbc沒有陣列支援,這裡先用varchar代替,在呼叫時候將原本的陣列轉換一下即可。
para_images varchar,
para_description character varying,
out op_result varchar
)
RETURNS  varchar
AS $BODY$

declare tmpId integer;
declare tmpId_str varchar;
declare opResult sys_type_operation_outline;
declare logic_allow boolean;
declare c_v_publish_time timestamp(0) without time zone;
declare c_v_uid integer;
declare c_v_title character varying;
declare c_v_view_num integer;
declare c_v_like_num integer;
--   (-_-) 注意,這個欄位是陣列來的,然而jdbc沒有陣列支援,這裡先用varchar代替,在呼叫時候將原本的陣列轉換一下即可。
declare c_v_images character varying[];
declare c_v_description character varying;

begin
logic_allow:=true;
-- 請先開啟相關操作。
if logic_allow = false then
opResult.message:=config('errors','logic_not_allow','message');
opResult."stateCode":=config('errors','logic_not_allow','code');
opResult."state":=false;
select row_to_json(t) into op_result from ( select opResult.state,opResult."stateCode",opResult.message  ) t;
return;
end if;

opResult.state:=false;
opResult."stateCode":=0;
opResult.message:='';
-- 正式的引數賦值
        c_v_publish_time:=current_timestamp (0);
        c_v_uid:=para_uid;
        c_v_title:=para_title;
        c_v_view_num:=0;
        c_v_like_num:=0;
        c_v_images := string_to_array(para_images, ',')::character varying(250)[];
        c_v_description:=para_description;

INSERT INTO "ins_post"(
-- 主鍵不插入記錄。
 "publish_time"
 ,  "uid"
 ,  "title"
 ,  "view_num"
 ,  "like_num"
 ,  "images"
 ,  "description"
)
VALUES (
 c_v_publish_time
 ,  c_v_uid
 ,  c_v_title
 ,  c_v_view_num
 ,  c_v_like_num
 ,  c_v_images
 ,  c_v_description
);
if FOUND then
opResult.message:='儲存成功';
opResult."stateCode":=0;
opResult."state":=true;
else
opResult.message:='儲存失敗';
opResult."stateCode":=0;
opResult."state":=false;
end if;

if opResult.state=true then
select row_to_json(t) into op_result from ( select opResult.state,opResult."stateCode",opResult.message,currval(pg_get_serial_sequence('ins_post', 'id')) as data  ) t;
else
select row_to_json(t) into op_result from ( select opResult.state,opResult."stateCode",opResult.message  ) t;
end if;


end;
$BODY$ LANGUAGE plpgsql volatile;



-- 點贊或者取消點贊
CREATE OR REPLACE FUNCTION "sp_ins_ins_post_like_or_not_like"(
para_uid integer,
para_post_id integer,
para_status boolean,
out op_result varchar
)
RETURNS  varchar
AS $BODY$

declare tmpId integer;
declare tmpId_str varchar;
declare opResult sys_type_operation_outline;
declare logic_allow boolean;
declare c_v_uid integer;
declare c_v_post_id integer;
declare c_v_status boolean;
declare c_v_create_time timestamp(0) without time zone;

begin
logic_allow:=true;
-- 請先開啟相關操作。
if logic_allow = false then
opResult.message:=config('errors','logic_not_allow','message');
opResult."stateCode":=config('errors','logic_not_allow','code');
opResult."state":=false;
select row_to_json(t) into op_result from ( select opResult.state,opResult."stateCode",opResult.message  ) t;
return;
end if;

opResult.state:=false;
opResult."stateCode":=0;
opResult.message:='';
-- 正式的引數賦值
        c_v_uid:=para_uid;
        c_v_post_id:=para_post_id;
        c_v_status:=para_status;
        c_v_create_time:=current_timestamp(0);

INSERT INTO "ins_like"(
 "uid"
 ,  "post_id"
 ,  "status"
 ,  "create_time"
)
VALUES (
 c_v_uid
 ,  c_v_post_id
 ,  c_v_status
 ,  c_v_create_time
)
on conflict (uid,post_id) DO
update set "status"=EXCLUDED.status;
if FOUND then
opResult.message:='儲存成功';
opResult."stateCode":=0;
opResult."state":=true;
else
opResult.message:='儲存失敗';
opResult."stateCode":=0;
opResult."state":=false;
end if;

if opResult.state=true then
select row_to_json(t) into op_result from ( select opResult.state,opResult."stateCode",opResult.message,'' as data  ) t;
else
select row_to_json(t) into op_result from ( select opResult.state,opResult."stateCode",opResult.message  ) t;
end if;


end;
$BODY$ LANGUAGE plpgsql volatile;




/***最新帖子***/
CREATE OR REPLACE FUNCTION public."sp_ins_ins_post_newest_list"(
in pageindex integer,
in pagesize integer,
out outline_result varchar,
out list_result varchar
)
RETURNS record
AS $BODY$
declare pagerOutLine sys_type_pager_outline;
declare totalSize integer;
declare tmpStr varchar(400);
declare json_condition json;
declare cnd_id_eq integer;
begin
list_result:='[]';
-- 組裝條件語句
json_condition:='{}'::json;

-- 首先獲取記錄總數

select count(*) into totalSize from
/**中間表,begin**/
(
select * from "ins_post"
where 1=1

-- 請自行條件條件語句。
--         and
--             case when cnd_name_like is not null  and char_length(cnd_name_like) > 0
--                       then  "name" LIKE CONCAT('%',cnd_name_like,'%')  else 1=1 end
order by "publish_time" desc

)  tbl_middle
/**中間表,end**/
;


-- 然後計算beginIndex,totalPages
pagerOutLine:=sys_func_cal_pager(pageIndex,pageSize,totalSize);
-- raise notice '好了,看看pagerOutline的資料:';
-- raise notice '看看pagerOutLine裡面的資料:%,真奇怪,那麼,totalSize 是:%',pagerOutLine,totalSize;
-- 定義返回的狀態。
pagerOutLine."state":=true;
pagerOutLine."stateCode":=0;
pagerOutLine."message":='';

-- 返回相關資料。

select row_to_json(t) into outline_result from
(select pagerOutLine."state",
pagerOutLine."stateCode",
pagerOutLine."pageIndex",
pagerOutLine."pageSize",
pagerOutLine.total,
pagerOutLine."totalPages",
pagerOutLine."message") t;
select array_to_json(array_agg(row_to_json(tbl_middle))) into list_result from
/**中間表,begin**/
(
/**中間表定義,begin**/
select * from "ins_post"
where 1=1

order by "publish_time" desc
/**中間表定義,end**/
limit pagerOutLine."pageSize" offset pagerOutLine."beginIndex"
)  tbl_middle
/**中間表,end**/

  ;
-- 有可能找不到記錄,這時候就返回空陣列。
if list_result is null or char_length (list_result) < 1 then
list_result:='[]';
end if;

end;

$BODY$ LANGUAGE plpgsql volatile;



/***檢視人數最多的帖子***/
CREATE OR REPLACE FUNCTION public."sp_ins_ins_post_hottest_list"(
in pageindex integer,
in pagesize integer,
out outline_result varchar,
out list_result varchar
)
RETURNS record
AS $BODY$
declare pagerOutLine sys_type_pager_outline;
declare totalSize integer;
declare tmpStr varchar(400);
declare json_condition json;
declare cnd_id_eq integer;
begin
list_result:='[]';
-- 組裝條件語句
json_condition:='{}'::json;

-- 首先獲取記錄總數

select count(*) into totalSize from
/**中間表,begin**/
(
select * from "ins_post"
where 1=1



-- 請自行條件條件語句。
--         and
--             case when cnd_name_like is not null  and char_length(cnd_name_like) > 0
--                       then  "name" LIKE CONCAT('%',cnd_name_like,'%')  else 1=1 end
order by "view_num" desc

)  tbl_middle
/**中間表,end**/
;


-- 然後計算beginIndex,totalPages
pagerOutLine:=sys_func_cal_pager(pageIndex,pageSize,totalSize);
-- raise notice '好了,看看pagerOutline的資料:';
-- raise notice '看看pagerOutLine裡面的資料:%,真奇怪,那麼,totalSize 是:%',pagerOutLine,totalSize;
-- 定義返回的狀態。
pagerOutLine."state":=true;
pagerOutLine."stateCode":=0;
pagerOutLine."message":='';

-- 返回相關資料。

select row_to_json(t) into outline_result from
(select pagerOutLine."state",
pagerOutLine."stateCode",
pagerOutLine."pageIndex",
pagerOutLine."pageSize",
pagerOutLine.total,
pagerOutLine."totalPages",
pagerOutLine."message") t;
select array_to_json(array_agg(row_to_json(tbl_middle))) into list_result from
/**中間表,begin**/
(
/**中間表定義,begin**/
select * from "ins_post"
where 1=1

order by "view_num" desc
/**中間表定義,end**/
limit pagerOutLine."pageSize" offset pagerOutLine."beginIndex"
)  tbl_middle
/**中間表,end**/

  ;
-- 有可能找不到記錄,這時候就返回空陣列。
if list_result is null or char_length (list_result) < 1 then
list_result:='[]';
end if;

end;

$BODY$ LANGUAGE plpgsql volatile;



/***最受歡迎的,最多人喜歡的***/
CREATE OR REPLACE FUNCTION public."sp_ins_ins_post_popular_list"(
in pageindex integer,
in pagesize integer,
out outline_result varchar,
out list_result varchar
)
RETURNS record
AS $BODY$
declare pagerOutLine sys_type_pager_outline;
declare totalSize integer;
declare tmpStr varchar(400);
declare json_condition json;
declare cnd_id_eq integer;
begin
list_result:='[]';
-- 組裝條件語句
json_condition:='{}'::json;


-- 首先獲取記錄總數

select count(*) into totalSize from
/**中間表,begin**/
(
select * from "ins_post"
where 1=1

order by "like_num" desc,"publish_time" asc

)  tbl_middle
/**中間表,end**/
;


-- 然後計算beginIndex,totalPages
pagerOutLine:=sys_func_cal_pager(pageIndex,pageSize,totalSize);
-- raise notice '好了,看看pagerOutline的資料:';
-- raise notice '看看pagerOutLine裡面的資料:%,真奇怪,那麼,totalSize 是:%',pagerOutLine,totalSize;
-- 定義返回的狀態。
pagerOutLine."state":=true;
pagerOutLine."stateCode":=0;
pagerOutLine."message":='';

-- 返回相關資料。

select row_to_json(t) into outline_result from
(select pagerOutLine."state",
pagerOutLine."stateCode",
pagerOutLine."pageIndex",
pagerOutLine."pageSize",
pagerOutLine.total,
pagerOutLine."totalPages",
pagerOutLine."message") t;
select array_to_json(array_agg(row_to_json(tbl_middle))) into list_result from
/**中間表,begin**/
(
/**中間表定義,begin**/
select * from "ins_post"
where 1=1

order by "like_num" desc,"publish_time" asc
/**中間表定義,end**/
limit pagerOutLine."pageSize" offset pagerOutLine."beginIndex"
)  tbl_middle
/**中間表,end**/

  ;
-- 有可能找不到記錄,這時候就返回空陣列。
if list_result is null or char_length (list_result) < 1 then
list_result:='[]';
end if;

end;

$BODY$ LANGUAGE plpgsql volatile;




java呼叫邏輯:

package net.w2p.DevBase.biz.ins;

import com.alibaba.fastjson.JSONObject;
import net.w2p.DevBase.model.account.MemberModel;
import net.w2p.DevBase.model.account.MemberRegByAdmin;
import net.w2p.DevBase.model.account.MemberUpdateByAdmin;
import net.w2p.DevBase.model.ins.PostModel;
import net.w2p.DevBase.searcher.ins.PostCondition;
import net.w2p.DevBase.service.account.MemberService;
import net.w2p.DevBase.service.common.RegionService;
import net.w2p.DevBase.vo.account.Member;
import net.w2p.DevBase.vo.common.Region;
import net.w2p.DevBase.vo.common.RegionSimpleVO;
import net.w2p.DevBase.vo.ins.Post;
import net.w2p.Shared.common.DB.DataTableHelper;
import net.w2p.Shared.common.OpResult;
import net.w2p.Shared.common.PagerResult;
import net.w2p.Shared.common.ValidateUtils;
import net.w2p.Shared.mybatis.TypeHandlers.*;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.CallableStatementCallback;
import org.springframework.jdbc.core.CallableStatementCreator;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class PostBiz {
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    @Autowired
    DoubleArrayTypeHandler doubleArrayTypeHandler;
    @Autowired
    IntegerArrayTypeHandler integerArrayTypeHandler;
    @Autowired
    ShortArrayTypeHandler shortArrayTypeHandler;
    @Autowired
    StringArrayTypeHandler stringArrayTypeHandler;
    @Autowired
    LongArrayTypeHandler longArrayTypeHandler;
    @Autowired
    BooleanArrayTypeHandler booleanArrayTypeHandler;
    @Autowired
    JsonArrayTypeHandler jsonArrayTypeHandler;
    @Autowired
    JsonTypeHandler jsonTypeHandler;



    /***
     * 釋出帖子
     ***/
    public OpResult publish(
            Integer uid,
            String title,
            String[] images,
            String description
    )
    {
        int totalParaCount=4 + 1;//--儲存過程引數總個數。,其中1個out 引數
        String procName="sp_ins_ins_post_publish";
        final HashMap<String,Integer> map_out_paras=new HashMap<>();
        int theParamIndex=0;
        OpResult opResult=new OpResult();
        StringBuilder paraStr=new StringBuilder();
        String callable_para_str="";
        for(int i=0;i<totalParaCount;i++){
            paraStr.append('?');
            paraStr.append(',');
        }
        if(totalParaCount>0){
            paraStr.append(',');
            callable_para_str=(paraStr.toString().replaceFirst(",,",""));
        }
        final String sql="{ call \""+procName+"\"("+callable_para_str+")}";

        CallableStatementCreator stCreator=new CallableStatementCreator() {
            @Override
            public CallableStatement createCallableStatement(Connection con) throws SQLException {
                CallableStatement st=con.prepareCall(sql);
                int paraIndex=0;


                paraIndex++; st.setObject(paraIndex,uid);
                paraIndex++; st.setString(paraIndex,title);
                paraIndex++; stringArrayTypeHandler.setParameter(st,paraIndex,images, JdbcType.VARCHAR);
                paraIndex++; st.setString(paraIndex,description);
                paraIndex++;st.registerOutParameter(paraIndex,Types.VARCHAR);map_out_paras.put("op_result",paraIndex);
                return st;
            }
        };

        CallableStatementCallback<OpResult> stCallback=new CallableStatementCallback<OpResult>(){
            @Override
            public OpResult doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {
                OpResult op_result=new OpResult();
                cs.execute();
                ResultSet rs=(ResultSet)cs.getResultSet();
                String json_op_result=cs.getString(map_out_paras.get("op_result"));
                op_result=JSONObject.parseObject(json_op_result,OpResult.class);
                if(rs!=null){
                    rs.close();
                }
                cs.getConnection().setAutoCommit(true);
                return op_result;
            }
        };
        opResult=jdbcTemplate.execute(stCreator,stCallback);
        return opResult;
    }



    /***
     * 點贊或者取消點贊
     ***/
    public OpResult likeOrNot(
            Integer uid,
            Integer post_id,
            Boolean status
    )
    {
        int totalParaCount=3 + 1;//--儲存過程引數總個數。,其中1個out 引數
        String procName="sp_ins_ins_post_like_or_not_like";
        final HashMap<String,Integer> map_out_paras=new HashMap<>();
        int theParamIndex=0;
        OpResult opResult=new OpResult();
        StringBuilder paraStr=new StringBuilder();
        String callable_para_str="";
        for(int i=0;i<totalParaCount;i++){
            paraStr.append('?');
            paraStr.append(',');
        }
        if(totalParaCount>0){
            paraStr.append(',');
            callable_para_str=(paraStr.toString().replaceFirst(",,",""));
        }
        final String sql="{ call \""+procName+"\"("+callable_para_str+")}";

        CallableStatementCreator stCreator=new CallableStatementCreator() {
            @Override
            public CallableStatement createCallableStatement(Connection con) throws SQLException {
                CallableStatement st=con.prepareCall(sql);
                int paraIndex=0;


                paraIndex++; st.setObject(paraIndex,uid);
                paraIndex++; st.setObject(paraIndex,post_id);
                paraIndex++; st.setBoolean(paraIndex,status);
                paraIndex++;st.registerOutParameter(paraIndex,Types.VARCHAR);map_out_paras.put("op_result",paraIndex);
                return st;
            }
        };

        CallableStatementCallback<OpResult> stCallback=new CallableStatementCallback<OpResult>(){
            @Override
            public OpResult doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {
                OpResult op_result=new OpResult();
                cs.execute();
                ResultSet rs=(ResultSet)cs.getResultSet();
                String json_op_result=cs.getString(map_out_paras.get("op_result"));
                op_result=JSONObject.parseObject(json_op_result,OpResult.class);
                if(rs!=null){
                    rs.close();
                }
                cs.getConnection().setAutoCommit(true);
                return op_result;
            }
        };
        opResult=jdbcTemplate.execute(stCreator,stCallback);
        return opResult;
    }



    /**
     * 最新帖子
     *
     * ***/
    public PagerResult<Post> newestList(
            int pageindex,
            int pagesize
    ){

        final HashMap<String,Integer> map_out_paras=new HashMap<>();
        PagerResult<Post> pagerResult=new PagerResult<>();
        final String sql="{ call \"sp_ins_ins_post_newest_list\"(?,?,?,?)}";


        CallableStatementCreator stCreator=new CallableStatementCreator() {
            @Override
            public CallableStatement createCallableStatement(Connection con) throws SQLException {
                CallableStatement st=con.prepareCall(sql);
                int paraIndex=0;
                paraIndex++;st.setInt(paraIndex,pageindex);
                paraIndex++;st.setInt(paraIndex,pagesize);
                paraIndex++;st.registerOutParameter(paraIndex,Types.VARCHAR);map_out_paras.put("outline_result",paraIndex);
                paraIndex++;st.registerOutParameter(paraIndex,Types.VARCHAR);map_out_paras.put("list_result",paraIndex);
                return st;
            }
        };

        CallableStatementCallback<PagerResult<Post>> stCallback=new CallableStatementCallback<PagerResult<Post>>(){
            @Override
            public PagerResult<Post> doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {
                PagerResult<Post> pager=new PagerResult<>();
                List<Post> list=new ArrayList<>();
                cs.execute();
                ResultSet rs=(ResultSet)cs.getResultSet();
                String outline_result=cs.getString(map_out_paras.get("outline_result"));
                String list_result=cs.getString(map_out_paras.get("list_result"));
                System.out.println(outline_result);
                pager=JSONObject.parseObject(outline_result,PagerResult.class);
                list=JSONObject.parseArray(list_result,Post.class);
                pager.setData(new ArrayList<>());
                for(Post item:list){
                    pager.getData().add(item);
                }
//                if (rs.next()){
//                    String json_str=rs.getString(1);
//                    if(ValidateUtils.isEmpty(json_str)){
//return pager;
//                    }
//                    pager=JSONObject.parseObject(json_str,PagerResult.class);
//                }
                if(rs!=null){
                    rs.close();
                }
                cs.getConnection().setAutoCommit(true);
                return pager;
            }
        };
        pagerResult=jdbcTemplate.execute(stCreator,stCallback);
        completeInfo(pagerResult.getData());

        return pagerResult;
    }


    /**
     * 檢視人數最多的帖子列表
     *
     * ***/
    public PagerResult<Post> hottestList(
            int pageindex,
            int pagesize
    ){

        final HashMap<String,Integer> map_out_paras=new HashMap<>();
        PagerResult<Post> pagerResult=new PagerResult<>();
        final String sql="{ call \"sp_ins_ins_post_hottest_list\"(?,?,?,?)}";


        CallableStatementCreator stCreator=new CallableStatementCreator() {
            @Override
            public CallableStatement createCallableStatement(Connection con) throws SQLException {
                CallableStatement st=con.prepareCall(sql);
                int paraIndex=0;
                paraIndex++;st.setInt(paraIndex,pageindex);
                paraIndex++;st.setInt(paraIndex,pagesize);
                paraIndex++;st.registerOutParameter(paraIndex,Types.VARCHAR);map_out_paras.put("outline_result",paraIndex);
                paraIndex++;st.registerOutParameter(paraIndex,Types.VARCHAR);map_out_paras.put("list_result",paraIndex);
                return st;
            }
        };

        CallableStatementCallback<PagerResult<Post>> stCallback=new CallableStatementCallback<PagerResult<Post>>(){
            @Override
            public PagerResult<Post> doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {
                PagerResult<Post> pager=new PagerResult<>();
                List<Post> list=new ArrayList<>();
                cs.execute();
                ResultSet rs=(ResultSet)cs.getResultSet();
                String outline_result=cs.getString(map_out_paras.get("outline_result"));
                String list_result=cs.getString(map_out_paras.get("list_result"));
                System.out.println(outline_result);
                pager=JSONObject.parseObject(outline_result,PagerResult.class);
                list=JSONObject.parseArray(list_result,Post.class);
                pager.setData(new ArrayList<>());
                for(Post item:list){
                    pager.getData().add(item);
                }
//                if (rs.next()){
//                    String json_str=rs.getString(1);
//                    if(ValidateUtils.isEmpty(json_str)){
//return pager;
//                    }
//                    pager=JSONObject.parseObject(json_str,PagerResult.class);
//                }
                if(rs!=null){
                    rs.close();
                }
                cs.getConnection().setAutoCommit(true);
                return pager;
            }
        };
        pagerResult=jdbcTemplate.execute(stCreator,stCallback);
        completeInfo(pagerResult.getData());

        return pagerResult;
    }

    /**
     * 最受歡迎,最多人喜歡的帖子
     *
     * ***/
    public PagerResult<Post> popularList(
            int pageindex,
            int pagesize
    ){

        final HashMap<String,Integer> map_out_paras=new HashMap<>();
        PagerResult<Post> pagerResult=new PagerResult<>();
        final String sql="{ call \"sp_ins_ins_post_popular_list\"(?,?,?,?)}";


        CallableStatementCreator stCreator=new CallableStatementCreator() {
            @Override
            public CallableStatement createCallableStatement(Connection con) throws SQLException {
                CallableStatement st=con.prepareCall(sql);
                int paraIndex=0;
                paraIndex++;st.setInt(paraIndex,pageindex);
                paraIndex++;st.setInt(paraIndex,pagesize);
                paraIndex++;st.registerOutParameter(paraIndex,Types.VARCHAR);map_out_paras.put("outline_result",paraIndex);
                paraIndex++;st.registerOutParameter(paraIndex,Types.VARCHAR);map_out_paras.put("list_result",paraIndex);
                return st;
            }
        };

        CallableStatementCallback<PagerResult<Post>> stCallback=new CallableStatementCallback<PagerResult<Post>>(){
            @Override
            public PagerResult<Post> doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {
                PagerResult<Post> pager=new PagerResult<>();
                List<Post> list=new ArrayList<>();
                cs.execute();
                ResultSet rs=(ResultSet)cs.getResultSet();
                String outline_result=cs.getString(map_out_paras.get("outline_result"));
                String list_result=cs.getString(map_out_paras.get("list_result"));
                System.out.println(outline_result);
                pager=JSONObject.parseObject(outline_result,PagerResult.class);
                list=JSONObject.parseArray(list_result,Post.class);
                pager.setData(new Arra