1、当某字段的记录不能重复时,可在数据库中创建唯一索引,这样就不用在业务代码中写判断。
2、可能不按照主键查询的话,添加单索引,也能添加组合索引,即传两个及以上的id
3、时间戳,数据记录时间,数据最后更新时间。记录时间只在创建时写入,之后不会改变,这样做为了方便之后的维护,而且更新时间可写在sql中,在代码中可不操作更新时间字段
4、mybatis
4.1 mybatis-generator 自动生成与数据库交互的代码
4.2 mybatis-plugin idea插件,实现接口与xml之间的互相跳转,找来找去
4.3 mybatis-pagehelper 分页组件,开源
5、在简单常量的分类时,可选择使用内部接口,复杂时还是用枚举或其他吧
6、解决浮点型商业运算中丢失精度使用Bigdecimal
//加
public static BigDecimal add(double d1,double d2){
BigDecimal b1 = new BigDecimal(Double.toString(d1));
BigDecimal b2 = new BigDecimal(Double.toString(d2));
return b1.add(b2);
}
//减
public static BigDecimal sub(double d1,double d2){
BigDecimal b1 = new BigDecimal(Double.toString(d1));
BigDecimal b2 = new BigDecimal(Double.toString(d2));
return b1.subtract(b2);
}
//乘
public static BigDecimal mul(double d1,double d2){
BigDecimal b1 = new BigDecimal(Double.toString(d1));
BigDecimal b2 = new BigDecimal(Double.toString(d2));
return b1.multiply(b2);
}
//除
public static BigDecimal div(double d1,double d2){
BigDecimal b1 = new BigDecimal(Double.toString(d1));
BigDecimal b2 = new BigDecimal(Double.toString(d2));
return b1.divide(b2,2,BigDecimal.ROUND_HALF_UP);//保留两位小数,四舍五入
}
实际使用时,使用Bigdecimal的String构造方法
例:
BigDecimal bigDecimal = new BigDecimal("0");
7、返回Json数据的话,定义返回格式类
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
//保证序列化json的时候,如果是null的对象,key也会消失
public class ServerResponse implements Serializable {
// 状态
private int status;
// 内容
private T data;
// 信息
private String msg;
private ServerResponse(int status) {
this.status = status;
}
private ServerResponse(int status, T data) {
this.status = status;
this.data = data;
}
private ServerResponse(int status, String msg) {
this.status = status;
this.msg = msg;
}
private ServerResponse(int status, T data, String msg) {
this.status = status;
this.data = data;
this.msg = msg;
}
@JsonIgnore
//使之不在json序列化结果当中
public boolean isSuccess(){
return this.status == ResponseCode.SUCCESS.getCode();
}
public int getStatus() {
return status;
}
public String getMsg() {
return msg;
}
public T getData() {
return data;
}
public static ServerResponse createBySuccess(){
return new ServerResponse(ResponseCode.SUCCESS.getCode());
}
public static ServerResponse createBySuccessMessage(String msg){
return new ServerResponse(ResponseCode.SUCCESS.getCode(),msg);
}
public static ServerResponse createBySuccess(T data){
return new ServerResponse(ResponseCode.SUCCESS.getCode(),data);
}
public static ServerResponse createBySuccess(T data,String msg){
return new ServerResponse(ResponseCode.SUCCESS.getCode(),data,msg);
}
public static ServerResponse createByError(){
return new ServerResponse(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getDesc());
}
public static ServerResponse createByErrorMessage(String errorMessage){
return new ServerResponse(ResponseCode.ERROR.getCode(),errorMessage);
}
public static ServerResponse createByErrorCodeMessage(int errorCode,String errorMessage){
return new ServerResponse(errorCode,errorMessage);
}
}