@RequestMapping(value = "/getItemList")
@ResponseBody
public HashMap<String, Object> getItemList(@RequestParam HashMap<String, String> paraMap) {
try {
LinkedHashMap<String, String> orderby = new LinkedHashMap<>();
orderby.put("itemCode","asc");
List<HashMap<String, Object>> list = new LinkedList<>();
// sql语句
String sql="select distinct ItemCode,ItemName from cbhs_xmft_cagitem where ItemCode like :keyword or ItemName like :keyword ";
// SQL参数集合【排序,页码,页数,条件参数】
HashMap<String, Object> stringHashMap = new HashMap<>();
stringHashMap.put(PageUtil.ORDER_BY, "ItemCode@desc");
stringHashMap.put(PageUtil.PAGE_INDEX, StringUtil.isEmptyOrLength0(paraMap.get("page")) ? 1L : Integer.parseInt(paraMap.get("page")));
stringHashMap.put(PageUtil.PAGE_SIZE, StringUtil.isEmptyOrLength0(paraMap.get("limit")) ? 15L : Integer.parseInt(paraMap.get("limit")));
stringHashMap.put("keyword","%"+(StringUtil.isEmptyOrLength0(paraMap.get("keyword"))?"":paraMap.get("keyword"))+"%");
// 调用分页方法
CommonPage commonPage = PageUtil.newPageUtil(stringHashMap, sql, "").execSearch(new NamedParameterJdbcTemplate(jdbcTemplate.getDataSource()));
// sql查询结果集
LinkedList<Map<String, Object>> resultlist = commonPage.getResultlist();
// list集合key值转化 PingyinUtil.ToFirstChar为获取汉字的首拼音
for (int i = 0; i < resultlist.size(); i++) {
HashMap<String, Object> map = new HashMap<>();
map.put("code", resultlist.get(i).get("ItemCode"));
map.put("namereal", resultlist.get(i).get("ItemName"));
map.put("name", resultlist.get(i).get("ItemName") + "" + PingyinUtil.ToFirstChar(resultlist.get(i).get("ItemName").toString().replace("《", "").replace("》", "")));
list.add(i, map);
}
// 将数据传入前端 commonPage.getTotal()为数据总数
HashMap<String, Object> objectHashMap = createResult(true, "成功");
objectHashMap.put("data", list);
objectHashMap.put("code", 0);
objectHashMap.put("count", commonPage.getTotal());
return objectHashMap;
} catch (Exception e) {
log.error(e.getMessage(),e);
return createResult(false, "失败");
}
}
public class PageUtil {
private static final Logger log = LoggerFactory.getLogger(PageUtil.class);
public static final String ORDER_BY = "orderBy";
public static final String PAGE_INDEX = "pageIndex";
public static final String PAGE_SIZE = "pageSize";
private PageUtil.CommonPageExec commonPageExec;
public static PageUtil newPageUtil(Map<String, Object> paraMap, String sql, String countselect) {
PageUtil.CommonPageExec commonPage = new PageUtil.CommonPageExec();
commonPage.setCountselect(countselect);
commonPage.setSql(sql);
LinkedHashMap orderMap = new LinkedHashMap();
String orderBy = (String)paraMap.getOrDefault("orderBy", "");
if (!StringUtil.isEmptyOrLength0(orderBy)) {
String[] orderByAry = orderBy.split(",");
for(int i = 0; i < orderByAry.length; ++i) {
String[] orderByAryOne = orderByAry[i].split("@");
if (!StringUtil.isEmptyOrLength0(orderByAryOne[0])) {
orderMap.put(orderByAryOne[0], orderByAryOne.length != 1 && !StringUtil.isEmptyOrLength0(orderByAryOne[1]) ? orderByAryOne[1] : "desc");
}
}
}
commonPage.setOrderMap(orderMap);
commonPage.setPageIndex(StringUtil.isEmptyOrLength0(paraMap.get("pageIndex")) ? null : Long.valueOf(paraMap.get("pageIndex").toString()));
commonPage.setPageSize(StringUtil.isEmptyOrLength0(paraMap.get("pageSize")) ? null : Long.valueOf(paraMap.get("pageSize").toString()));
commonPage.setParaMap(paraMap);
return new PageUtil(commonPage);
}
private PageUtil(PageUtil.CommonPageExec commonPageExec) {
this.commonPageExec = commonPageExec;
}
public CommonPage execSearch(NamedParameterJdbcTemplate jdbcTemplate) {
this.commonPageExec.execSearch(jdbcTemplate);
return this.commonPageExec;
}
public static class CommonPageExec extends CommonPage {
public CommonPageExec() {
}
public void execSearch(NamedParameterJdbcTemplate jdbcTemplate) {
DBTYPE dbtype = DBTypeUtil.getDbtype(((JdbcTemplate)jdbcTemplate.getJdbcOperations()).getDataSource());
if (!StringUtil.isEmptyOrLength0(this.countselect)) {
String func_Sql_TotalTmp = this.sql.toLowerCase().replaceAll("\\s", " ").replaceFirst("select.*?\\s+from\\s+", "select count(1) as total from ");
int endIndex = func_Sql_TotalTmp.toLowerCase().lastIndexOf(" order by ");
func_Sql_TotalTmp = endIndex > 0 ? func_Sql_TotalTmp.substring(0, endIndex) : func_Sql_TotalTmp;
List<Map<String, Object>> dataList = jdbcTemplate.queryForList(func_Sql_TotalTmp, this.paraMap);
this.total = dataList.size() == 0 ? 0L : Long.parseLong(((Map)dataList.get(0)).get("total").toString());
} else {
Boolean isMaxLongClown = Boolean.FALSE;
String func_Sql_Tmp = this.sql.toString().toLowerCase().replaceAll("\\s", " ").replaceFirst("select.*?\\s+from\\s+", "select * from ").replace(" where ", " where 1=2 ");
func_Sql_Tmp = func_Sql_Tmp.substring(0, func_Sql_Tmp.indexOf(" where 1=2 ") + 12);
if (DBTYPE.sqlserver.equals(dbtype)) {
func_Sql_Tmp = this.sql.toString().toLowerCase().replaceAll("\\s", " ").replaceFirst("select.*?\\s+from\\s+", "select top 0 * from ");
}
try {
isMaxLongClown = (Boolean)jdbcTemplate.query(func_Sql_Tmp, this.paraMap, new ResultSetExtractor<Boolean>() {
public Boolean extractData(ResultSet resultSet) throws SQLException, DataAccessException {
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
for(int j = 1; j <= resultSetMetaData.getColumnCount(); ++j) {
if (resultSetMetaData.getColumnDisplaySize(j) > 3096) {
return Boolean.TRUE;
}
}
return Boolean.FALSE;
}
});
} catch (Throwable var8) {
;
}
StringBuilder func_Sql_Total = new StringBuilder();
String func_Sql_TotalTmp;
int endIndex;
if (isMaxLongClown) {
func_Sql_TotalTmp = this.sql.toString().toLowerCase();
if (DBTYPE.sqlserver.equals(dbtype)) {
endIndex = func_Sql_TotalTmp.toString().toLowerCase().lastIndexOf(" order by ");
func_Sql_TotalTmp = endIndex > 0 ? func_Sql_TotalTmp.substring(0, endIndex) : func_Sql_TotalTmp;
}
func_Sql_Total.append(" select count(1) as total from ( ");
func_Sql_Total.append(func_Sql_TotalTmp);
func_Sql_Total.append(" ) sqltotalTmp ");
} else {
func_Sql_TotalTmp = this.sql.toLowerCase().replaceAll("\\s", " ").replaceFirst("select.*?\\s+from\\s+", "select count(1) as total from ");
endIndex = func_Sql_TotalTmp.toString().toLowerCase().lastIndexOf(" order by ");
func_Sql_TotalTmp = endIndex > 0 ? func_Sql_TotalTmp.substring(0, endIndex) : func_Sql_TotalTmp;
func_Sql_Total.append(func_Sql_TotalTmp);
}
new LinkedList();
List<Map<String, Object>> dataList = jdbcTemplate.queryForList(func_Sql_Total.toString(), this.paraMap);
this.total = dataList.size() == 0 ? 0L : Long.parseLong(((Map)dataList.get(0)).get("total").toString());
}
this.execPageDataSelect(jdbcTemplate, dbtype);
}
private void execPageDataSelect(NamedParameterJdbcTemplate jdbcTemplate, DBTYPE dbtype) {
this.pageIndex = this.pageIndex != null && this.pageIndex >= 1L ? this.pageIndex : 1L;
this.pageSize = this.pageSize != null && this.pageSize >= 0L ? this.pageSize : 15L;
long start = (this.pageIndex - 1L) * this.pageSize;
start = start < 0L ? 0L : start;
final int skipNum = 0;
String searchSql = this.sql;
if (DBTYPE.mysql.equals(dbtype)) {
searchSql = this.sql + this.getStringOrderBy() + " limit " + start + " , " + this.pageSize;
} else if (DBTYPE.oracle.equals(dbtype)) {
StringBuilder tmpStringBuilder = new StringBuilder();
tmpStringBuilder.append("select * from ");
tmpStringBuilder.append(" ( ");
tmpStringBuilder.append(searchSql.replace("select ", "select rownum as rownum_id,"));
tmpStringBuilder.append(this.getStringOrderBy());
tmpStringBuilder.append(" ) ");
tmpStringBuilder.append(" where rownum_id between " + start + " and " + (start + this.pageSize));
searchSql = searchSql.trim().toLowerCase().indexOf("select") == 0 ? tmpStringBuilder.toString() : searchSql;
} else if (DBTYPE.sqlserver.equals(dbtype)) {
String tmpStr = searchSql.trim().startsWith("select") ? "select" : "";
tmpStr = searchSql.trim().startsWith("SELECT") ? "SELECT" : tmpStr;
if (tmpStr.length() > 0) {
String toLowerCase = searchSql.replaceFirst(tmpStr, "").trim().toLowerCase();
boolean hasDistinct = false;
if (toLowerCase.startsWith("distinct")) {
toLowerCase = toLowerCase.replaceFirst("distinct", "");
hasDistinct = true;
}
String searchSql1Tmp = "select top 0 " + toLowerCase;
final List<String> strFieldsList = new LinkedList();
jdbcTemplate.query(searchSql1Tmp, this.paraMap, new ResultSetExtractor<Object>() {
public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
ResultSetMetaData resultSetMetaData = rs.getMetaData();
for(int i = 0; i < resultSetMetaData.getColumnCount(); ++i) {
resultSetMetaData.getColumnLabel(i + 1);
resultSetMetaData.getColumnName(i + 1).toLowerCase();
strFieldsList.add(resultSetMetaData.getColumnName(i + 1).toLowerCase());
}
return null;
}
});
String rownumberOrderbyField = "";
if (this.orderMap.size() > 0) {
rownumberOrderbyField = this.getStringOrderBy().toString();
} else {
rownumberOrderbyField = " order by " + (strFieldsList.size() > 2 ? (String)strFieldsList.get(1) : (String)strFieldsList.get(0));
}
StringBuilder tmpStringBuilder = new StringBuilder();
tmpStringBuilder.append("select row_number() over ( ");
tmpStringBuilder.append(rownumberOrderbyField);
tmpStringBuilder.append(" ) rownumber , ");
if (hasDistinct) {
searchSql = searchSql.replaceFirst("distinct", "");
}
searchSql = searchSql.replaceFirst(tmpStr, tmpStringBuilder.toString());
StringBuilder tmpStringBuilder1 = new StringBuilder();
tmpStringBuilder1.append(" select ");
if (hasDistinct) {
tmpStringBuilder1.append(" distinct ");
}
tmpStringBuilder1.append(" * from (");
tmpStringBuilder1.append(searchSql);
tmpStringBuilder1.append(") tableabc where rownumber between ");
tmpStringBuilder1.append(start + 1L);
tmpStringBuilder1.append(" and ");
tmpStringBuilder1.append(start + this.pageSize);
searchSql = tmpStringBuilder1.toString();
}
}
PageUtil.log.info("searchSql: " + searchSql);
PageUtil.log.info("searchSqlArgs: " + JSON.toJSONString(this.paraMap));
LinkedList linkedList = (LinkedList)jdbcTemplate.query(searchSql, this.paraMap, new ResultSetExtractor<LinkedList<Map<String, Object>>>() {
public LinkedList<Map<String, Object>> extractData(ResultSet sqlRowSet) throws SQLException, DataAccessException {
return CommonPageExec.this.paraseOneStatementResult(sqlRowSet, skipNum);
}
});
PageUtil.log.debug(" sql end.");
}
private StringBuilder getStringOrderBy() {
StringBuilder orderby = new StringBuilder();
Iterator var2 = this.orderMap.entrySet().iterator();
while(var2.hasNext()) {
Entry<String, String> entry = (Entry)var2.next();
orderby.append(" ");
orderby.append((String)entry.getKey());
orderby.append(" ");
orderby.append((String)entry.getValue());
orderby.append(",");
}
if (orderby.length() > 0) {
orderby.insert(0, " order by ");
orderby.setLength(orderby.length() - 1);
}
return orderby;
}
private LinkedList<Map<String, Object>> paraseOneStatementResult(ResultSet sqlRowSet, int skipNumFinal) throws SQLException {
int tmpSkipCount = 0;
ResultSetMetaData metaData = sqlRowSet.getMetaData();
while(true) {
do {
if (!sqlRowSet.next()) {
return this.resultlist;
}
++tmpSkipCount;
} while(tmpSkipCount <= skipNumFinal);
Map<String, Object> oneData = new LinkedHashMap();
Object timestamp1;
for(int i = 1; i <= metaData.getColumnCount(); ++i) {
String columnName = metaData.getColumnLabel(i);
String dateString;
BigDecimal bigDecimal;
switch(metaData.getColumnType(i)) {
case -6:
case 4:
case 5:
long anInt = sqlRowSet.getLong(i);
bigDecimal = new BigDecimal(anInt);
oneData.put(columnName, bigDecimal);
break;
case 2:
case 3:
case 8:
double anInt = sqlRowSet.getDouble(i);
bigDecimal = new BigDecimal(anInt);
oneData.put(columnName, bigDecimal);
break;
case 6:
float anInt = sqlRowSet.getFloat(i);
BigDecimal bigDecimal = new BigDecimal((double)anInt);
oneData.put(columnName, bigDecimal);
break;
case 91:
Date anInt = sqlRowSet.getDate(i);
dateString = anInt == null ? "" : DateUtil.formatFromDate("yyyy-MM-dd HH:mm:ss", anInt);
oneData.put(columnName, dateString);
break;
case 92:
Time time = sqlRowSet.getTime(i);
dateString = time == null ? "" : DateUtil.formatFromDate("yyyy-MM-dd HH:mm:ss", new java.util.Date(time.getTime()));
oneData.put(columnName, dateString);
break;
case 93:
timestamp1 = sqlRowSet.getObject(i);
Timestamp timestamp = new Timestamp(0L);
if (timestamp1 instanceof TIMESTAMP) {
TIMESTAMP timestampTmp = (TIMESTAMP)timestamp1;
try {
timestamp = timestampTmp.timestampValue();
} catch (SQLException var16) {
var16.printStackTrace();
}
} else if (timestamp1 instanceof DATE) {
DATE timestampTmp = (DATE)timestamp1;
try {
timestamp = timestampTmp.timestampValue();
} catch (Exception var15) {
var15.printStackTrace();
}
} else if (timestamp1 instanceof TIMESTAMPTZ) {
TIMESTAMPTZ timestampTmp = (TIMESTAMPTZ)timestamp1;
try {
timestamp = timestampTmp.timestampValue();
} catch (Exception var14) {
var14.printStackTrace();
}
} else {
timestamp = sqlRowSet.getTimestamp(i);
}
String dateString = timestamp == null ? "" : DateUtil.formatFromDate("yyyy-MM-dd HH:mm:ss", new java.util.Date(timestamp.getTime()));
oneData.put(columnName, dateString);
break;
case 2004:
try {
Blob blob = (Blob)sqlRowSet.getObject(i);
oneData.put(columnName, blob == null ? "" : blob.toString());
} catch (Exception var13) {
var13.printStackTrace();
}
break;
case 2005:
try {
Clob colb = (Clob)sqlRowSet.getObject(i);
oneData.put(columnName, colb == null ? "" : colb.getSubString(1L, (int)colb.length()));
} catch (Exception var12) {
var12.printStackTrace();
}
break;
default:
String anInt = sqlRowSet.getString(i);
anInt = anInt == null ? "" : anInt;
oneData.put(columnName, anInt);
}
}
List list = new LinkedList(oneData.keySet());
Iterator iterator = list.iterator();
while(iterator.hasNext()) {
timestamp1 = iterator.next();
oneData.put(timestamp1.toString().toUpperCase(), oneData.get(timestamp1));
oneData.put(timestamp1.toString().toLowerCase(), oneData.get(timestamp1));
}
this.resultlist.add(oneData);
}
}
}
}
1,先引入包
在pom.xml文件中添加pinyin4j.jar信息系统会直接从官网下载
<dependency>
<groupId>net.sourceforge.pinyin4j</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>
2,写入方法
public class PingyinUtil {
// 汉字转全拼音
public static String ToPinyin(String chinese){
String pinyinStr = "";
char[] newChar = chinese.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < newChar.length; i++) {
if (newChar[i] > 128) {
try {
pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0];
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
}else{
pinyinStr += newChar[i];
}
}
return pinyinStr;
}
// 汉字转首部拼音
public static String ToFirstChar(String str){
String convert = "";
for (int j = 0; j < str.length(); j++) {
char word = str.charAt(j);
String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
if (pinyinArray != null) {
convert += pinyinArray[0].charAt(0);
} else {
convert += word;
}
}
return convert;
}
}