resttemplate.exchange远程调用

String url = "http://"+ dataPickerIpAndPort+"/myHouse/getMyHouse?userName="+userName+"&idCard="+idCard+"&buyer="+buyer+"&contractNum="+contractNum; 
try {
System.out.println("findCompanies's url:"+url);
body = restTemplate.exchange(
url
, HttpMethod.POST
, null
, new ParameterizedTypeReference<AnswerDTONew<MyHouseDTO>>() {
}).getBody();
if(body==null){
return new AnswerDTONew(true,"not found",new MyHouseDTO(), CommonState.ERROR);
}
}catch (Exception e){
return new AnswerDTONew(true,e.getMessage(),"", CommonState.ERROR);
}
@RequestMapping(value = "/myHouse/getMyHouse")
AnswerDTONew<MyHouseDTO> getMyHouse(@RequestParam(name = "idCard") String idCard,
@RequestParam(name = "buyer") String buyer,
@RequestParam(name = "contractNum") String contractNum);

使用重载避免过多修改客户代码

比如原先计算最大值有个方法,是根据字段id计算最大值

private Long getMaxId(String table){
List<Map<String, Object>> maps = jdbcTemplate.queryForList("select max(id) mid from " + table);
if(maps.size()>0){
Long mid = (Long) maps.get(0).get("MID");
return mid;
}else{
return 1L;
}
}

然后客户有很多调用了此代码。

后来有发现有需求要根据其他字段来计算最大值。

那么,是如果简单在上面方法上增加参数,就会导致调用方代码大量修改。

这时,可以保留上述方法,增加一个重载方法

private Long getMaxId(String table, String field){
List<Map<String, Object>> maps = jdbcTemplate.queryForList("select max("+field+") mid from " + table);
if(maps.size()>0){
Long mid = (Long) maps.get(0).get("MID");
return mid;
}else{
return 1L;
}
}

那么原来的方法,只需要调用次方法即可。

private Long getMaxId(String table){
return getMaxId(table,"id");
}

这样既避免了客户代码的大量修改,又避免了两个重载方法的代码重复冗余。

StringBuffer拼接sql的新写法

append,append,append重要的事情说三遍

例如:

StringBuffer insPersonRelation = new StringBuffer();
insPersonRelation.append("insert into houseproperty.personrelation")
.append("id,persontype,personid,register_id,register_type,personname)")
.append("values(")
.append(maxId).append(",'")
.append(persontype).append("','")
.append(personid)
.append(register_id).append("','")
.append(register_type).append("',")
.append("'").append(personName).append("'")
.append(")");

另一个java自定义异常

有时候为了简化业务判断,可以抛出自定义异常,然后在最顶层,根据异常信息返回不用的信息。

定义系统异常基类:

public class BusinessException extends Exception {
private static String baseMsg = "business exception:";
public BusinessException(String msg) {
super(baseMsg+msg);
}
}

子类1:

public class OpenIdIsEmptyException  extends BusinessException {
private static String msg = "openId is empty";
public OpenIdIsEmptyException() {
super(msg);
}
}

子类2:

public class UserIsNotExistException extends BusinessException {
private static String msg = "user is not exist";
public UserIsNotExistException() {
super(msg);
}
}

底层抛出

}else{
logger.info("userName:{} is not exist",userName);
throw new UserIsNotExistException();
}

方法抛出

throws OpenIdIsEmptyException, UserIsNotExistException 

顶层捕获

} catch (UserIsNotExistException e) {
e.printStackTrace();
logger.info("UserIsNotExistException"+e.getMessage());
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}