参数是否必填写法 1 使用字段 required
@ApiImplicitParams({
@ApiImplicitParam(name = Constant.PAGE, value = "当前页码,从1开始", paramType = "query", required = true, dataType = "int"),
@ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
@ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType = "String"),
@ApiImplicitParam(name = Constant.ORDER, value = "排序方式,可选值(asc、desc)", paramType = "query", dataType = "String")
})
@PreAuthorize("hasAuthority('sbc:savingsbusinessaccountbalancecalculateinformationhour:page')")
public Result<PageData<SavingsBusinessAccountBalanceCalculateInformationHourDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params) {
PageData<SavingsBusinessAccountBalanceCalculateInformationHourDTO> page = savingsBusinessAccountBalanceCalculateInformationHourService.page(params);
return new Result<PageData<SavingsBusinessAccountBalanceCalculateInformationHourDTO>>().ok(page);
}
参数是否必填写法 2 使用字段 required
Result<List<IncomeDetailsDTO>> listIncomeDetails(@ApiParam(value = "产品id") @RequestParam(required = false) Long productId) {
Long customerId = (Long) request.getAttribute(AuthorizationInterceptor.USER_KEY);
return customFinancingRedemptionOrderFeignClient.listIncomeDetails(customerId, productId);
}
update
update(new NCustomerEntity(), new LambdaUpdateWrapper<NCustomerEntity>(){{
set(NCustomerEntity::getTransactionPin, customerTransactionPinUpdateDTO.getTransactionPin());
eq(NCustomerEntity::getId, customerTransactionPinUpdateDTO.getCustomerId());
}});
Java导出超大Excel文件,防止内存溢出,文件拆分数据到不同sheet页
public static void main(String[] args) throws Exception {
int totalRowNumber = 1000000; //写入的excel数据行数
// List<CustomTimeDepositAccountBalanceReportDTO> list = customTimeDepositAccountBalanceReportService.list(params);
// ExcelUtils.exportExcelToTarget(response, null, "理财账户报表", list, CustomTimeDepositAccountBalanceReportExcel.class);
String title = "mySheet";
int number = 0;// 每个页面的行数
int sheetNum = 1;//sheet标题编号
//定义Row和Cell变量, Rows从0开始.
Row row;
Cell cell;
SXSSFWorkbook wb = null;
FileOutputStream out = null;
try {
long startTime = System.currentTimeMillis();
wb = new SXSSFWorkbook();//默认100行,超100行将写入临时文件
wb.setCompressTempFiles(false); //是否压缩临时文件,否则写入速度更快,但更占磁盘,但程序最后是会将临时文件删掉的
Sheet sheet = createSheet(wb, title + sheetNum);
sheetNum++;
for (int rowNumber = 0; rowNumber < totalRowNumber; rowNumber++) {
number++;
if ((rowNumber % 100000 == 0) && rowNumber != 0) {
sheet = createSheet(wb, title + sheetNum);
number = 1;
sheetNum++;
}
//页面数据赋值
row = sheet.createRow(number);
row.createCell(0).setCellValue(Math.random());
row.createCell(1).setCellValue(Math.random());
row.createCell(2).setCellValue(Math.random());
}
//将excel写入文件
out = new FileOutputStream("d:\\temp\\0223-2理财账户报表" + ".xlsx");
wb.write(out);
long endTime = System.currentTimeMillis();
System.out.println("process " + totalRowNumber + " spent time:" + (endTime - startTime) + " ms.");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (wb != null) {
wb.dispose();// 删除临时文件,很重要,否则磁盘可能会被写满
}
try {
if(out != null) out.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(wb != null) wb.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static Sheet createSheet(SXSSFWorkbook workbook, String title) {
Sheet sheet = workbook.createSheet(title);
// 设置表头
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("序号");
headerRow.createCell(1).setCellValue("编码");
headerRow.createCell(2).setCellValue("名称");
return sheet;
}
Ipv4
/**
* IPv4地址转换成数字
* @param ip
*/
public long ipv4ToNumber(String ip) {
long rs = 0;
if (ip == null || ip.isEmpty()) {
return rs;
}
String[] ips = ip.split("\\.");
for (int i = 0; i < ips.length; i++) {
rs += Integer.parseInt(ips[i]) * Math.pow(256, (3 - i));
}
return rs;
}
/**
* 数字转换成IPv4地址
* @param number
* @return
*/
public String numberToIpv4(long number) {
StringBuilder ip = new StringBuilder();
ip.append(number>>>24).append(".");
ip.append((number>>>16)&0xFF).append(".");
ip.append((number>>>8)&0xFF).append(".");
ip.append(number&0xFF);
return ip.toString();
}
Ipv6 16进制
/**
* IPv6地址转换成数字
* @param ip
* @return
*/
public static BigInteger ipv6ToNumber(String ip) {
String[] ips = ip.split(":");
BigInteger rs = new BigInteger("0");
for (int i = 0; i < ips.length; i++) {
BigInteger a = BigInteger.valueOf(Integer.parseInt(ips[i], 16));
BigInteger b = BigInteger.valueOf(65536).pow(7 - i);
BigInteger c = a.multiply(b);
rs = rs.add(c);
}
return rs;
}
/**
* 数字转换成IPV6地址
* @param number
* @return
*/
public static String numberToIpv6(BigInteger number) {
String ip = "";
List<String> ips = new ArrayList<String>();
for (int i = 0; i < 8; i++) {
ips.add(Integer.toHexString(number.divideAndRemainder(BigInteger.valueOf(65536))[1].intValue()));
number = number.shiftRight(16);
}
for (int i = ips.size() - 1; i >= 0; i--) {
ip = ip.concat(ips.get(i));
if (i > 0) {
ip = ip.concat(":");
}
}
return ip;
}
集合的类型转换
public List<SysCountryDTO> listSysCountry() {
QueryWrapper<SysCountryEntity> wrapper = new QueryWrapper<>();
wrapper.eq("isShow", 1);
List<SysCountryEntity> list = baseDao.selectList(wrapper);
return ConvertUtils.sourceToTarget(list, SysCountryDTO.class);
}
实体类正则验证
##实体类
/**
* 注册表单
*
* @author Mark sunlightcs@gmail.com
*/
@Data
@ApiModel(value = "注册表单")
public class RegisterDTO {
@ApiModelProperty(value = "手机号")
@NotBlank(message="手机号不能为空")
private String mobile;
@ApiModelProperty(value = "密码")
@NotBlank(message="密码不能为空")
@Length(min = 8, max = 16,message = "密码长度错误")
@Pattern(regexp = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$", message = "密码格式错误")
private String password;
}
##调用
@PostMapping("register")
@ApiOperation("注册")
public Result register(@RequestBody RegisterDTO dto){
//表单校验
ValidatorUtils.validateEntity(dto);
return userService.register(dto);
}
Bean Validation 中内置的 constraint
注解 作用
@Valid 被注释的元素是一个对象,需要检查此对象的所有字段值
@Null 被注释的元素必须为 null
@NotNull 被注释的元素必须不为 null
@AssertTrue 被注释的元素必须为 true
@AssertFalse 被注释的元素必须为 false
@Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max, min) 被注释的元素的大小必须在指定的范围内
@Digits (integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
@Past 被注释的元素必须是一个过去的日期
@Future 被注释的元素必须是一个将来的日期
@Pattern(value) 被注释的元素必须符合指定的正则表达式
https://www.bmabk.com/index.php/post/28047.html
mybatis plus
##left join
public PageData<OpenapiUserAuthenticationDataPageDTO> pageNew(Map<String, Object> params) {
//分页
String page = (String)params.get("page");
String limit = (String)params.get("limit");
Page<OpenapiUserAuthenticationDataPageDTO> pageParam = new Page<>(Integer.parseInt(page), Integer.parseInt(limit));
//sql 查询数据
IPage<OpenapiUserAuthenticationDataPageDTO> pageDate = baseDao.selectJoinPage(pageParam,
OpenapiUserAuthenticationDataPageDTO.class,
openapiUserAuthenticationDataMPJ().like(StringUtils.isNotBlank((String)params.get("userName")), OpenapiUserEntity::getUserName, (String)params.get("userName"))
.like(StringUtils.isNotBlank((String)params.get("mobile")), OpenapiUserEntity::getMobile, (String)params.get("mobile"))
.like(StringUtils.isNotBlank((String)params.get("userNationId")), OpenapiUserEntity::getUserNationId, (String)params.get("userNationId"))
.like(StringUtils.isNotBlank((String)params.get("enableFlag")), OpenapiUserEntity::getEnableFlag, (String)params.get("enableFlag"))
.like(StringUtils.isNotBlank((String)params.get("mobile")), OpenapiUserAuthenticationDataEntity::getContactMobile, (String)params.get("mobile"))
.like(StringUtils.isNotBlank((String)params.get("documentTypeId")), OpenapiUserAuthenticationDataEntity::getDocumentTypeId, (String)params.get("documentTypeId"))
.like(StringUtils.isNotBlank((String)params.get("documentNumber")), OpenapiUserAuthenticationDataEntity::getDocumentNumber, (String)params.get("documentNumber"))
.like(StringUtils.isNotBlank((String)params.get("approvalStatus")), OpenapiUserAuthenticationDataEntity::getApprovalStatus, (String)params.get("approvalStatus"))
.orderByDesc(OpenapiUserAuthenticationDataEntity::getCreateDate));
return getPageData(pageDate, OpenapiUserAuthenticationDataPageDTO.class);
}
public OpenapiUserAuthenticationDataPageDTO getInfoById(Long id) {
OpenapiUserAuthenticationDataPageDTO openapiUserAuthenticationDataPageDTO = baseDao.selectJoinOne(OpenapiUserAuthenticationDataPageDTO.class,
openapiUserAuthenticationDataMPJ().eq(OpenapiUserAuthenticationDataEntity::getId, id)
);
return openapiUserAuthenticationDataPageDTO;
}
/**
* 关联用户查询sql
* @return
*/
public MPJLambdaWrapper<OpenapiUserAuthenticationDataEntity> openapiUserAuthenticationDataMPJ(){
MPJLambdaWrapper<OpenapiUserAuthenticationDataEntity> mpj = new MPJLambdaWrapper<OpenapiUserAuthenticationDataEntity>()
.selectAll(OpenapiUserAuthenticationDataEntity.class)
.leftJoin(OpenapiUserEntity.class, OpenapiUserEntity::getId, OpenapiUserAuthenticationDataEntity::getUserId)
.selectAs(OpenapiUserEntity::getMobile, OpenapiUserAuthenticationDataPageDTO::getMobile)
.selectAs(OpenapiUserEntity::getPassword, OpenapiUserAuthenticationDataPageDTO::getPassword)
.selectAs(OpenapiUserEntity::getStatus, OpenapiUserAuthenticationDataPageDTO::getStatus)
.selectAs(OpenapiUserEntity::getBankId, OpenapiUserAuthenticationDataPageDTO::getBankId)
.selectAs(OpenapiUserEntity::getLastLoginTime, OpenapiUserAuthenticationDataPageDTO::getLastLoginTime)
.selectAs(OpenapiUserEntity::getThisLoginTime, OpenapiUserAuthenticationDataPageDTO::getThisLoginTime)
.selectAs(OpenapiUserEntity::getUserName, OpenapiUserAuthenticationDataPageDTO::getUserName)
.selectAs(OpenapiUserEntity::getUserLevelId, OpenapiUserAuthenticationDataPageDTO::getUserLevelId)
.selectAs(OpenapiUserEntity::getUserLevelName, OpenapiUserAuthenticationDataPageDTO::getUserLevelName)
.selectAs(OpenapiUserEntity::getUserTypeId, OpenapiUserAuthenticationDataPageDTO::getUserTypeId)
.selectAs(OpenapiUserEntity::getUserTypeName, OpenapiUserAuthenticationDataPageDTO::getUserTypeName)
.selectAs(OpenapiUserEntity::getUserNationName, OpenapiUserAuthenticationDataPageDTO::getUserNationName)
.selectAs(OpenapiUserEntity::getUserNationId, OpenapiUserAuthenticationDataPageDTO::getUserNationId)
.selectAs(OpenapiUserEntity::getDocumentTypeId, OpenapiUserAuthenticationDataPageDTO::getDocumentTypeId)
.selectAs(OpenapiUserEntity::getDocumentTypeName, OpenapiUserAuthenticationDataPageDTO::getDocumentTypeName)
.selectAs(OpenapiUserEntity::getDocumentNumber, OpenapiUserAuthenticationDataPageDTO::getDocumentNumber)
.selectAs(OpenapiUserEntity::getUserTag, OpenapiUserAuthenticationDataPageDTO::getUserTag);
return mpj;
}
##子查询
Mybatis–plus之QueryWrapper用法
##基础用法
QueryWrapper<实体类> qw = new QueryWrapper<>();
qw.in("字段", 数组);
qw.and(Wrapper -> Wrapper.eq(字段::get.(), "1").or().eq(字段::get.(), "2"));
qw.eq();
qw.select().orderByAsc();
qw.select().orderByDesc();
qw.lambda().like();
new LambdaQueryWrapper<实体类>().gt();
new LambdaQueryWrapper<实体类>().isNotNull();
new QueryWrapper<实体类>().in().groupBy()
##or查询
.eq("from_app_type", "wx")
.or(qw->qw.eq("zf_code", "M106944").eq("channel","test"))
//sql条件部分
WHERE
( from_app_type = ? OR ( ( zf_code = ? AND channel = ? ) ) )
//sql条件部分
WHERE
(from_app_type = ? OR zf_code = ?)
.eq("from_app_type", "wx")
.or()
.eq("zf_code", "M106944")
//实测代码例子
LambdaQueryWrapper<SysDeptEntity> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(SysDeptEntity::getOrganizationType, "ZH");
queryWrapper.eq(SysDeptEntity::getDelFlag,DelFlagEnum.NORMAL.value());
queryWrapper.or(qw->qw.eq(SysDeptEntity::getOrganizationType, "FH").eq(SysDeptEntity::getDelFlag,DelFlagEnum.NORMAL.value()));
baseDao.selectList(queryWrapper);
//sql条件部分
WHERE
( organization_type = 'ZH' AND del_flag = '0' OR ( organization_type = 'FH' AND del_flag = '0'))
//
QueryWrapper<TProductEntity> wrapper = new QueryWrapper<>();
wrapper.and(qw->qw.like(StringUtils.isNotBlank(highlightsTitleFirst), "highlights_title_first", highlightsTitleFirst).or().like(StringUtils.isNotBlank(highlightsTitleFirst), "highlights_content_second", highlightsTitleFirst).or().like(StringUtils.isNotBlank(highlightsTitleFirst), "highlights_title_third", highlightsTitleFirst));
//sql条件部分格式
WHERE
(
del_flag = 0
AND (
highlights_title_first LIKE ?
OR highlights_content_second LIKE ?
OR highlights_title_third LIKE ?))
##将字符转成集合 用in查询
String additionalBankIssuance = (String) params.get("additionalBankIssuance");
if (StringUtils.isNotEmpty(additionalBankIssuance)) {
List<String> tradeSceneCodeList = Arrays.asList(additionalBankIssuance.split(","));
wrapper.in( tradeSceneCodeList != null, "trade_scene_code", tradeSceneCodeList);
}
##时间查询
String startDate = (String) params.get("startDate");
String endDate = (String) params.get("endDate");
if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
wrapper.ge("trade_time", startDate+" 00:00:00");
wrapper.le("trade_time", endDate+" 23:59:59");
}
selectObjs 使用
排序
//历史收益
BigDecimal timeDepositAccountBalance = BigDecimal.ZERO;
QueryWrapper<TCustomTimeDepositAccountEntity> wrapper = new QueryWrapper<TCustomTimeDepositAccountEntity>() {{
eq("customer_id", customerId);
eq("currency_type_code", currencyTypeCode);
eq("is_lock", 0);
eq("is_enable", 1);
eq("del_flag", 0);
select("select IFNULL(sum(issued_income),0) as balance");
}};
List<Object> list = baseDao.selectObjs(wrapper);
if (CollectionUtils.isNotEmpty(list)) {
timeDepositAccountBalance = (BigDecimal)list.get(0);
}
mysql CASE WHEN 使用
customer_status 状态为103 国籍为柬埔寨的属于柬埔寨人民,其他数据外国人 在查询的时候做判断
//eg:
select case sex when sex='1' then '男' when sex='2' then '女' else '其他' end as '性别' from people;
select case sex when sex='2' then '女' when sex='1' then '男' else '其他' end as '性别' from people;
//实际用法
SELECT
CASE cut.customer_status WHEN cut.customer_status = '103' THEN cut.national WHEN cut.national = '国外' THEN '外国人' ELSE '外国人' END AS oldNational,
FROM
t_custom_time_deposit_purchase_order ord
LEFT JOIN t_custom_time_deposit_account acc ON acc.account_no = ord.to_account_no
LEFT JOIN t_custom_time_deposit_purchase_order_customer cut ON cut.order_id = ord.id
AND acc.customer_id = cut.customer_id
LEFT JOIN t_custom_time_deposit_purchase_order_product pro ON pro.product_id = ord.product_id
AND pro.order_id = ord.id
Java 实体转化成Map
SysLanguageEntity entity = new SysLanguageEntity();
Map<String, Object> map = map = new HashMap<>();
Gson gson = new Gson();
String jsonEntity = JSONUtil.toJsonStr(entity);
map = gson.fromJson(jsonEntity, map.getClass());
JAVA 删除Map中元素(JDK8)
// 通过value移除
map.values().removeIf(value -> !value.contains("1"));
// 通过key移除
map.keySet().removeIf(key -> key != 1);
// 通过键/值的输入/组合删除
map.entrySet().removeIf(entry -> entry.getKey() != 1);
serialVersionUID
private static final long serialVersionUID = -6279791315828947873L;
serialVersionUID作用:
相当于java类的身份证。主要用于版本控制。
serialVersionUID作用是序列化时保持版本的兼容性,即在版本升级时反序列化仍保持对象的唯一性。
序列化时为了保持版本的兼容性,即在版本升级时反序列化仍保持对象的唯一性。
有两种生成方式:
一个是默认的1L,比如:private static final long serialVersionUID = 1L;
一个是根据类名、接口名、成员方法及属性等来生成一个64位的哈希字段,比如:
private static final long serialVersionUID = xxxxL;
当你一个类实现了Serializable接口,如果没有定义serialVersionUID,Eclipse会提供这个
提示功能告诉你去定义 。在Eclipse中点击类中warning的图标一下,Eclipse就会
自动给定两种生成的方式。如果不想定义它,在Eclipse的设置中也
可以把它关掉的,设置如下:
Window ==> Preferences ==> Java ==> Compiler ==> Error/Warnings ==>
Potential programming problems
将Serializable class without serialVersionUID的warning改成ignore即可。
## redis缓存的使用
```java
public int verify(Long customerId, String pwd) {
//获取密码校验次数
customerVerifyKey = customerId + "_verify";//引号中是方法名用来区分
int count = Integer.parseInt(redisUtils.get(customerVerifyKey) == null ? "0" : redisUtils.get(customerVerifyKey).toString()); //用get方法获取redis存储的参数
if (count >= 3) {
return 3;
//throw new RenException("当前账户已被锁定,请在2小时候再操作!");
}
CustomerDTO customerDTO = get(customerId); //获取用户信息
if (customerDTO != null) {
//密码错误
String cpwd = customerDTO.getTransactionPin();
String opwd = DigestUtils.sha256Hex(pwd);
log.debug("密码校验:" + customerDTO.getTransactionPin() + "==" + pwd);
if (!cpwd.equals(opwd)) {
count += 1; //密码错误加1
if (count == 3) {
redisUtils.set(customerVerifyKey, count, 60 * 60 * 2L);//冻结customerVerifyKey 2小时有效期
} else {
Calendar calendar = Calendar.getInstance();
int timeLength = 60 * 60 * (24 - calendar.get(Calendar.HOUR_OF_DAY));//计算当天还有多长时间,保证当天的错误计数在缓存中不会过期
redisUtils.set(customerVerifyKey, count, timeLength);//2小时有效期
}
return 1;
}
redisUtils.delete(customerVerifyKey);//删除缓存
return 0;
}
return 1;
}
后端接口测试
object 转换成List
//调接口计算汇率
Map<String, Object> map = ExchangeRateUtils.exchangeRate(参数1, 参数2);
// 转list实体对象
List<ExchangeRateDTO> userList = new Gson().fromJson(new Gson().toJson(map.get("data")), new TypeToken<List<ExchangeRateDTO>>(){}.getType());
BigDecimal exchange= userList.get(0).getExchange();
map没人
{
"code": "0",
"msg": "success",
"data": [
{
"currencyF": "USD",
"currencyF_Name": "美元",
"currencyT": "CNY",
"currencyT_Name": "人民币",
"currencyFD": "1",
"exchange": "6.6885",
"result": "6.6885",
"updateTime": "2022-05-20 15:49:40"
},
{
"currencyF": "CNY",
"currencyF_Name": "人民币",
"currencyT": "USD",
"currencyT_Name": "美元",
"currencyFD": "1",
"exchange": "0.1495",
"result": "0.1495",
"updateTime": "2022-05-20 15:49:40"
}
]
}
重写page方法
public Result<PageData<ProductIncomeRuleDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params) {
PageData<ProductIncomeRuleDTO> page = new PageData();
//查询总数Total
List<ProductIncomeRuleDTO> list1 = productIncomeRuleService.pageNew(params);
page.setTotal(list1.size());
Object StrPage = params.get("page");//页码
Object StrLimit = params.get("limit");//每页数量
String str1 = StrPage.toString();
String str2 = StrLimit.toString();
int i1 = Integer.parseInt(str1);
int i2 = Integer.parseInt(str2);
i1 = (i1-1)*10;
params.put("pageNew",i1);
params.put("limitNew",i2);
List<ProductIncomeRuleDTO> list = productIncomeRuleService.pageNew(params);
page.setList(list);
return new Result<PageData<ProductIncomeRuleDTO>>().ok(page);
数组修改xml
controller层
public Result putOnTheShelfUpdate(@RequestBody Long[] ids, @RequestParam Integer isOnShelf) {
}
service
public void putOnTheShelfUpdate(Long[] ids, Integer isOnShelf) {
baseDao.onShelfByIds(ids, isOnShelf);
}
dao层
void onShelfByIds(@Param("ids") Long[] ids, @Param("isOnShelf") Integer isOnShelf);
xml
<update id="onShelfByIds">
update 表名
set is_on_shelf = #{isOnShelf}
where id in
<foreach collection="ids" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</update>
判断 BigDecimal 与 0的大小比较
BigDecimal big1 = new BigDecimal(4.42524233436);
BigDecimal big2 = new BigDecimal(-2.12435255542);
BigDecimal big3 = new BigDecimal(0);
// -1小于,0相等,1大于
int result = big1.compareTo(big2);
System.out.println(result);// 1
//与0比较 特殊 -1小于,0相等,1大于
if (big1.compareTo(BigDecimal.ZERO) == 1) {
System.out.println("大于0");
}
if (big2.compareTo(BigDecimal.ZERO) == -1) {
System.out.println("小于0");
}
if (big3.compareTo(BigDecimal.ZERO) == 0) {
System.out.println("等于0");
}`
判断 BigDecimal 类型有几位小数
/**
* 判断有几位小数
* @param purchaseStepAmount
* @return int
*/
@Override
public int getNumberOfDecimalPlace(BigDecimal purchaseStepAmount) {
final String s = purchaseStepAmount.toPlainString();
System.out.println(s);
final int index = s.indexOf('.');
if (index < 0) {
return 0;
}
return s.length() - 1 - index;
}
BigDecimal的加减乘除运算
BigDecimal resultTotalAssets =BigDecimal.ZERO; //初始化赋值
BigDecimal totalAssets = balanceStatistics.getBalance().setScale(4, BigDecimal.ROUND_HALF_UP);//向上取整
BigDecimal totalAssets1 = totalAssets.multiply(exchange);//乘
resultTotalAssets = resultTotalAssets.add(totalAssets); //加
resultTotalAssets = resultTotalAssets.subtract(totalAssets);//减
resultTotalAssets = resultTotalAssets.divide(totalAssets)//除
BigDecimal qty = new BigDecimal((double) sumprice);
//BigDecimal 定义金额 比double精准
if(qty .compareTo(qty1) == -1){
System.out.println("qty小于qty1");
}
时间的增加与减少
//获取时间加一年或加一月或加一天
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);//设置起时间
System.out.println("111111111::::"+cal.getTime());
cal.add(Calendar.YEAR, 1);//增加一年
cal.add(Calendar.DATE, n);//增加一天
cal.add(Calendar.DATE, -10);//减10天
cal.add(Calendar.MONTH, n);//增加一个月
System.out.println("输出::"+cal.getTime());
验证
/**通道已使用*/
private final int CHANNEL_IS_USED = 1;
public Result update(ChannelTypeUpdateDTO dto) {
if (dto == null) {
return new Result().error("更新信息为空");
}
ChannelTypeEntity channelTypeEntity = baseDao.selectById(dto.getId());
if (channelTypeEntity == null) {
return new Result().error("数据不存在");
}
String dtoCode = dto.getCode();
String dtoName = dto.getName();
String dbCode = channelTypeEntity.getCode();
String dbName = channelTypeEntity.getName();
boolean isUsed = dto.getIsUsed() == CHANNEL_IS_USED ? true : false;
if (isUsed && !dtoCode.equals(dbCode)) { //使用状态不能修改code
return new Result().error(String.format("通道使用中:%s, 不允许修改通道代码!", dtoCode));
}
if (!isUsed && !dtoCode.equals(dbCode) && existsByCode(dtoCode)) {
return new Result().error(String.format("通道代码:%s 已创建,请更换其它通道代码!", dtoName));
}
if (!dtoName.equals(dbName) && existsByName(dtoName)) { //修改名称验证是否重复
return new Result().error(String.format("通道名称:%s 已创建,请更换其它名称!", dtoName));
}
//更新..........................
}
git命令行
git branch -a
git branch -l
git remote -v