当前位置: 首页 > news >正文

Java开发笔记Ⅲ (一些零碎记录)

一些报错处理

找不到注入的对象

可以在 dao 层 的接口上添加 @Repository 注解

common 模块报错 Unable to find main class

由于common中只有一些常量与工具类,不需要主类,故出现该错误时只需删除pom文件中的build标签即可解决

网关模块报错 Failed to configure a DataSource: ‘url’ attribute is not specified and no embedded datasource could be configured.

原因是没有配置数据库相关信息,然而网关不需要与数据库交互,解决方法是在启动类上修改

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)

关闭对数据库配置的自动装配即可

@Value注解获取不到配置值

原因:@Value注解不能给静态变量赋值

解决方法:编写Setter方法代替

    private static int port;private static String username;/*** 设置port** @param port port*/@Value("${spring.rabbitmq.port}")public void setPort(int port) {RabbitMqConnectionFactory.port = port;}/*** 设置username** @param username username*/@Value("${spring.rabbitmq.username}")public void setUsername(String username) {RabbitMqConnectionFactory.username = username;}

运行@Test方法时,不能使用Scanner类在控制台输入数据

帮助—编辑自定义虚拟机选项,追加以下配置,重启Idea即可(help — Edit Custom VM Options)

-Deditable.java.test.console=true

运维过程中发现数据输入错误

某标准字段因误输入多了个空格,导致多个表数据错误,现要用sql语句修正该字段数据,如何在数据库中找到所有错误数据并修正呢?(Oracle数据库)

SELECT'UPDATE ' || TABLE_NAME || ' SET ' || COLUMN_NAME || ' = ''正确数据值'' WHERE ' || COLUMN_NAME || ' = ''错误数据值'';'
FROM ALL_TAB_COLUMNS
WHERE COLUMN_NAME = '列名'	# COLUMN_NAME like '%模糊查找列名%'AND OWNER = '数据库名'

执行该语句后会自动生成更新语句,复制粘贴到执行面板,检查后执行即可

软删除和唯一约束冲突

数据库规范要求,业务上唯一的字段必须在数据库中建立约束,但是又想记录被删除的数据,做软删除,这就导致了删除了的数据会与未删除的数据发生冲突。

解决方案是将软删除加入唯一键列,例如,设置username和isdeleted为联合唯一,然后删除数据时将isdeleted赋值为主键,MyBatis的实现方法如下:

/*** 删除标记*/
@TableLogic(value = "0", delval = "id")
@TableField(fill = FieldFill.INSERT)
protected Integer isDeleted;

hutool CollUtil 取交集,并集和差集

有个需求,实现班级学生的调整

image-20240617121543137

其实挺简单的,点击确定时候调用接口把该班级之前存储的学生删除,再把当前选中的学生存起来就行。但是因为用的是软删除,每次调整学生班级的时候,数据表里会多出好多没用的数据。

这里使用 hutoolCollUtil 进行集合操作,分开处理重复的数据与新增的数据。

CollUtil.intersection 取交集

CollUtil.subtract 取差集

CollUtil.disjunction 取交集的补集

CollUtil.union 取并集

具体实现如下

// 重复的(不需要操作的)
List<Long> repeatList = new ArrayList<>(CollUtil.intersection(新学生列表, 原学生列表));
if (!repeatList.equals(原学生列表)) {// 要删除的List<Long> deleteList = new ArrayList<>(CollUtil.subtract(原学生列表, repeatList));LambdaQueryWrapper<GradeStudentEntity> wrapper = new LambdaQueryWrapper<>();wrapper.eq(GradeStudentEntity::getGradeId, vo.getGradeId());if (ObjectUtil.isNotEmpty(deleteList)) {wrapper.in(GradeStudentEntity::getStudentId, deleteList);}remove(wrapper);
}
// 要新增的
List<Long> addList = new ArrayList<>(CollUtil.subtract(新学生列表, 原学生列表));
if (!addList.isEmpty()) {List<GradeStudentEntity> list = new ArrayList<>();for (Long studentId : addList) {GradeStudentEntity entity = new GradeStudentEntity();entity.setStudentId(studentId);entity.setGradeId(vo.getGradeId());list.add(entity);}saveBatch(list);
}

MyBatis 一对多映射

​ 主子表的关系,想要一条sql查出来

mapper.xml如下

    <resultMap type="com.power.milk.vo.MilksetVO" id="milkSetVoMap"><result property="id" column="id"/><result property="name" column="name"/><result property="price" column="price"/><result property="image" column="image"/><result property="description" column="description"/><result property="status" column="status"/><collection property="flavorItems" ofType="com.power.milk.vo.MilkFlavorVO"><result property="id" column="f_id"/><result property="name" column="f_name"/><result property="description" column="f_description"/><result property="number" column="f_number"/></collection></resultMap><select id="getList"  resultMap="milkSetVoMap">select m.* ,j.name AS CategoryName,mf.id as f_id,mf.name as f_name,mf.description as f_description,mf.number as f_numberfrom milkset m left join milk_flavor mf on mf.milk_or_set = 2 and mf.milk_or_set_id = m.id and mf.is_deleted = 0where m.is_deleted = 0</select>

然后再写下 MilksetVO 类

package com.power.milk.vo;import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.power.milk.common.utils.DateUtils;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;/*** 套餐** @author Power* @since 2024-04-10*/
@Data
@ApiModel(description = "套餐")
public class MilksetVO implements Serializable {private static final long serialVersionUID = 1L;@ApiModelProperty(value = "主键")@JsonSerialize(using = ToStringSerializer.class)private Long id;@ApiModelProperty(value = "牛奶分类id")@JsonSerialize(using = ToStringSerializer.class)private Long categoryId;@ApiModelProperty(value = "套餐名称")private String name;@ApiModelProperty(value = "套餐价格")private BigDecimal price;@ApiModelProperty(value = "图片")private String image;@ApiModelProperty(value = "套餐明细Json文本")private String flavorItemsJson;@ApiModelProperty(value = "套餐明细")private List<FlavorInMilk> flavorItems = new ArrayList<>();}

en…可能不太规范,但是确实实现了

img

Spring Boot 运行单元测试时使用不同配置文件

学习RabbitMQ的时候要跑官网的例子,又不想写好几个项目跑,就直接在SpringBoot的项目里加了测试类,由于每个例子的配置又不太一样,就学习了下怎么指定配置文件运行单元测试

举个例子,下边这段是 fanout 模式的代码

package com.gettler.rabbitmq.fanout;import com.gettler.rabbitmq.RabbitmqApplication;
import com.gettler.rabbitmq.config.RabbitMqConnectionFactory;
import com.rabbitmq.client.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;@ActiveProfiles("fanout")
@RunWith(SpringRunner.class)
@SpringBootTest(classes = RabbitmqApplication.class, webEnvironment =SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ConsumerATest {private static final Logger logger = LoggerFactory.getLogger(ConsumerATest.class);@Testpublic void testConsumerA() throws Exception {// 创建一个connectionConnection connection = RabbitMqConnectionFactory.getSingleInstanceConnection();// 创建一个channelChannel channel = connection.createChannel();// 声明交换机channel.exchangeDeclare("fanout", BuiltinExchangeType.FANOUT);// 声明临时队列String queueName = channel.queueDeclare().getQueue();// 绑定队列与交换机channel.queueBind(queueName, "fanout", "");// 消费消息DeliverCallback deliverCallback = (consumerTag, message) -> {System.out.println("获得消息:" + new String(message.getBody()));};CancelCallback cancelCallback = (consumerTag) -> {System.out.println("消息消费被中断");};channel.basicConsume(queueName, true, deliverCallback, cancelCallback);}
}

@ActiveProfiles("fanout") 就是指定读取 fanout 配置文件

image-20240619085802553

这样就可以读取到其他配置文件了

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 如何在Python中使用Pip换源
  • Leetcode Hot100之哈希表
  • 外卖APP开发详解:从同城O2O系统源码开始
  • 【C语言】信号
  • AWS无服务器 应用程序开发—第十六章 CI/CD CodeBuild
  • Java 获取客户端 IP 地址【工具类】
  • FTP 550 No such file or directory-
  • HDFS 面试题(一)
  • Qt Quick介绍
  • js-promise、async/await
  • 缓存技术实战[一文讲透!](Redis、Ecache等常用缓存原理介绍及实战)
  • WPF 深入理解四、样式
  • 用Flask定制指令上传Excel数据到数据库
  • 常用的sql语句
  • 板凳------56.Linux/Unix 系统编程手册(下) -- SOCKET 介绍
  • hexo+github搭建个人博客
  • 【407天】跃迁之路——程序员高效学习方法论探索系列(实验阶段164-2018.03.19)...
  • 【MySQL经典案例分析】 Waiting for table metadata lock
  • 【个人向】《HTTP图解》阅后小结
  • 【译】理解JavaScript:new 关键字
  • android百种动画侧滑库、步骤视图、TextView效果、社交、搜房、K线图等源码
  • CentOS学习笔记 - 12. Nginx搭建Centos7.5远程repo
  • create-react-app做的留言板
  • Docker 笔记(1):介绍、镜像、容器及其基本操作
  • HTTP那些事
  • JavaScript学习总结——原型
  • JDK 6和JDK 7中的substring()方法
  • Python中eval与exec的使用及区别
  • Spring Cloud Alibaba迁移指南(一):一行代码从 Hystrix 迁移到 Sentinel
  • Xmanager 远程桌面 CentOS 7
  • 从 Android Sample ApiDemos 中学习 android.animation API 的用法
  • 对象管理器(defineProperty)学习笔记
  • 翻译:Hystrix - How To Use
  • 浮动相关
  • 技术发展面试
  • 近期前端发展计划
  • 利用DataURL技术在网页上显示图片
  • 前端知识点整理(待续)
  • 全栈开发——Linux
  • 设计模式走一遍---观察者模式
  • TPG领衔财团投资轻奢珠宝品牌APM Monaco
  • ​LeetCode解法汇总2696. 删除子串后的字符串最小长度
  • # Panda3d 碰撞检测系统介绍
  • # 深度解析 Socket 与 WebSocket:原理、区别与应用
  • (51单片机)第五章-A/D和D/A工作原理-A/D
  • (arch)linux 转换文件编码格式
  • (ctrl.obj) : error LNK2038: 检测到“RuntimeLibrary”的不匹配项: 值“MDd_DynamicDebug”不匹配值“
  • (C语言)逆序输出字符串
  • (PHP)设置修改 Apache 文件根目录 (Document Root)(转帖)
  • (八)Spring源码解析:Spring MVC
  • (博弈 sg入门)kiki's game -- hdu -- 2147
  • (二十三)Flask之高频面试点
  • (转)关于如何学好游戏3D引擎编程的一些经验
  • (轉)JSON.stringify 语法实例讲解
  • (总结)Linux下的暴力密码在线破解工具Hydra详解