code-snipplet|| put table content into yaml

本文介绍了一种使用 Ruby on Rails 从现有数据库中创建 YAML 格式的测试固定装置的方法。默认针对开发数据库,可通过设置 RAILS_ENV 来指定其他环境。该过程涉及遍历数据库表并导出其内容为 YAML 文件。
namespace :db do
namespace :fixtures do

desc 'Create YAML test fixtures from data in an existing database.
Defaults to development database. Set RAILS_ENV to override.'
task :dump => :environment do
sql = "SELECT * FROM %s"
skip_tables = ["schema_info"]
ActiveRecord::Base.establish_connection(RAILS_ENV)
(ActiveRecord::Base.connection.tables - skip_tables).each do |table_name|
i = "000"
File.open("#{RAILS_ROOT}/test/fixtures/#{table_name}.yml", 'w') do |file|
data = ActiveRecord::Base.connection.select_all(sql % table_name)
file.write data.inject({}) { |hash, record|
hash["#{table_name}_#{i.succ!}"] = record
hash
}.to_yaml
end
end
end
end
end
本项目通过STM32F103C8T6单片机最小系统,连接正点原子ESP8266 WiFi模块,将模块设置为Station模式,并与电脑连接到同一个WiFi网络。随后,STM32F103C8T6单片机将数据发送到电脑所在的IP地址。 功能概述 硬件连接: STM32F103C8T6单片机与正点原子ESP8266 WiFi模块通过串口连接。 ESP8266模块通过WiFi连接到电脑所在的WiFi网络。 软件配置: 在STM32F103C8T6上配置串口通信,用于与ESP8266模块进行数据交互。 通过AT指令将ESP8266模块设置为Station模式,并连接到指定的WiFi网络。 配置STM32F103C8T6单片机,使其能够通过ESP8266模块向电脑发送数据。 数据发送: STM32F103C8T6单片机通过串口向ESP8266模块发送数据。 ESP8266模块将接收到的数据通过WiFi发送到电脑所在的IP地址。 使用说明 硬件准备: 准备STM32F103C8T6单片机最小系统板。 准备正点原子ESP8266 WiFi模块。 将STM32F103C8T6单片机与ESP8266模块通过串口连接。 软件准备: 下载并安装STM32开发环境(如Keil、STM32CubeIDE等)。 下载本项目提供的源代码,并导入到开发环境中。 配置与编译: 根据实际需求配置WiFi网络名称和密码。 配置电脑的IP地址,确保与ESP8266模块在同一网络中。 编译并下载程序到STM32F103C8T6单片机。 运行与测试: 将STM32F103C8T6单片机与ESP8266模块上电。 在电脑上打开网络调试工具(如Wireshark、网络调试助手等),监听指定端口。 观察电脑是否接收到来自STM32F103C8T6单片机发送的数据。
在电子测量技术中,示波装置扮演着观测电信号形态的关键角色。然而,市售标准示波器往往定价较高,使得资源有限的入门者或教学环境难以配备。为此,可采用基于51系列微控制器的简易示波方案进行替代。该方案虽在性能上不及专业设备,但已能满足基础教学与常规电路检测的需求。下文将系统阐述该装置的主要构成模块及其运行机制。 本装置以51系列单片机作为中央处理核心,承担信号数据的运算与管理任务。该单片机属于8位微控制器家族,在嵌入式应用领域使用广泛。其控制程序可采用C语言进行开发,得益于C语言在嵌入式编程中的高效性与适应性,它成为实现该功能的合适选择。 波形显示部分采用了由ST7565控制器驱动的128×64点阵液晶模块。ST7565是一款图形液晶驱动芯片,支持多种像素规格的显示输出;此处所指的12864即表示屏幕具有128列、64行的像素阵列。该屏幕能以图形方式实时绘制信号曲线,从而提供直观的观测界面。 在模拟至数字信号转换环节,系统集成了TLC0820型模数转换芯片。该芯片具备8位分辨率及双输入通道,最高采样速率可达每秒10万次。这样的转换速度对于捕获快速变动的信号波形具有重要意义。 实现该示波装置需综合运用嵌入式软硬件技术。开发者需掌握51单片机的指令系统与编程方法,熟悉ST7565控制器的显示驱动配置,并能对TLC0820芯片进行正确的采样编程。此外,还需设计相应的模拟前端电路,包括信号调理、放大与滤波等部分,以确保输入ADC的信号质量满足测量要求。 通过C语言编写的控制程序,可完成系统各模块的初始化、数据采集、数值处理以及图形化显示等完整流程。开发过程中需借助调试工具对代码进行验证,保证程序执行的正确性与稳定性。 应当指出,受限于51系列单片机的运算能力与资源,该自制装置的功能相对基础,例如难以实现多通道同步测量、高级触发模式或高容量波形存储等复杂特性。尽管如此,对于绝大多数基础电子实验与教学演示而言,其性能已足够适用。 综上所述,结合51单片机、ST7565液晶控制器与TLC0820转换芯片,可以构建出一套成本低廉、结构清晰的简易示波系统。该装置不仅可作为电子爱好者、在校学生及教师的有益实践平台,帮助理解示波测量的基本原理,还能通过动手组装与调试过程,深化对电路分析与嵌入式系统设计的认识。 资源来源于网络分享,仅用于学习交流使用,请勿用于商业,如有侵权请联系我删除!
2025-09-18 15:29:33.615 [reactor-http-nio-5] DEBUG reactor.netty.http.server.HttpServerOperations - [a0e83397, L:/192.168.10.122:9000 - R:/192.168.10.221:51066] New http connection, requesting read 2025-09-18 15:29:33.615 [reactor-http-nio-5] DEBUG reactor.netty.transport.TransportConfig - [a0e83397, L:/192.168.10.122:9000 - R:/192.168.10.221:51066] Initialized pipeline DefaultChannelPipeline{(reactor.left.httpCodec = io.netty.handler.codec.http.HttpServerCodec), (reactor.left.httpTrafficHandler = reactor.netty.http.server.HttpTrafficHandler), (reactor.right.reactiveBridge = reactor.netty.channel.ChannelOperationsHandler)} 2025-09-18 15:29:33.616 [reactor-http-nio-5] DEBUG reactor.netty.http.server.HttpServerOperations - [a0e83397, L:/192.168.10.122:9000 - R:/192.168.10.221:51066] Increasing pending responses, now 1 2025-09-18 15:29:33.616 [reactor-http-nio-5] DEBUG reactor.netty.http.server.HttpServer - [a0e83397-1, L:/192.168.10.122:9000 - R:/192.168.10.221:51066] Handler is being applied: org.springframework.http.server.reactive.ReactorHttpHandlerAdapter@250c00e8 2025-09-18 15:29:33.617 [reactor-http-nio-5] DEBUG o.s.web.server.adapter.HttpWebHandlerAdapter - [a0e83397-4] HTTP PUT "/master/shipper/update" 2025-09-18 15:29:33.617 [reactor-http-nio-5] DEBUG o.s.w.r.r.m.a.RequestMappingHandlerMapping - [a0e83397-4] Mapped to com.hvlink.controller.ShipperController#updateShipper(ShipperDTO) 2025-09-18 15:29:33.617 [reactor-http-nio-5] DEBUG o.s.w.r.r.m.a.RequestBodyMethodArgumentResolver - [a0e83397-4] Content-Type:application/json 2025-09-18 15:29:33.617 [reactor-http-nio-5] DEBUG o.s.w.r.r.m.a.RequestBodyMethodArgumentResolver - [a0e83397-4] 0..1 [com.hvlink.entity.dto.master.ShipperDTO] 2025-09-18 15:29:33.618 [reactor-http-nio-5] DEBUG reactor.netty.channel.FluxReceive - [a0e83397-1, L:/192.168.10.122:9000 - R:/192.168.10.221:51066] [terminated=false, cancelled=false, pending=0, error=null]: subscribing inbound receiver 2025-09-18 15:29:33.618 [reactor-http-nio-5] DEBUG o.s.http.codec.json.Jackson2JsonDecoder - [a0e83397-4] Decoded [ShipperDTO(id=29, companyCode=null, supplierCode=null, supplierName=0012000048 - 上海信耀电子有限公司, shipper (truncated)...] 2025-09-18 15:29:33.618 [reactor-http-nio-5] DEBUG o.s.jdbc.datasource.DataSourceTransactionManager - Creating new transaction with name [com.hvlink.service.impl.ShipperServiceImpl.updateShipper]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT 2025-09-18 15:29:33.618 [reactor-http-nio-5] DEBUG o.s.jdbc.datasource.DataSourceTransactionManager - Acquired Connection [ConnectionID:1 ClientConnectionId: 832daba7-ee0b-4bc1-9a5c-db187f8edc8d] for JDBC transaction 2025-09-18 15:29:33.618 [reactor-http-nio-5] DEBUG o.s.jdbc.datasource.DataSourceTransactionManager - Switching JDBC Connection [ConnectionID:1 ClientConnectionId: 832daba7-ee0b-4bc1-9a5c-db187f8edc8d] to manual commit 2025-09-18 15:29:33.628 [reactor-http-nio-5] DEBUG org.mybatis.spring.SqlSessionUtils - Creating a new SqlSession 2025-09-18 15:29:33.628 [reactor-http-nio-5] DEBUG org.mybatis.spring.SqlSessionUtils - Registering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6f745882] 2025-09-18 15:29:33.629 [reactor-http-nio-5] DEBUG o.m.spring.transaction.SpringManagedTransaction - JDBC Connection [ConnectionID:1 ClientConnectionId: 832daba7-ee0b-4bc1-9a5c-db187f8edc8d] will be managed by Spring 2025-09-18 15:29:33.629 [reactor-http-nio-5] DEBUG c.h.mapper.master.ShipperMapper.existsOtherDefault - ==> Preparing: SELECT CASE WHEN EXISTS ( SELECT 1 FROM tm_shipper WHERE is_default = '是' ) THEN 1 ELSE 0 END 2025-09-18 15:29:33.629 [reactor-http-nio-5] DEBUG c.h.mapper.master.ShipperMapper.existsOtherDefault - ==> Parameters: 2025-09-18 15:29:33.644 [reactor-http-nio-5] DEBUG c.h.mapper.master.ShipperMapper.existsOtherDefault - <== Total: 1 2025-09-18 15:29:33.644 [reactor-http-nio-5] DEBUG org.mybatis.spring.SqlSessionUtils - Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6f745882] 2025-09-18 15:29:33.644 [reactor-http-nio-5] DEBUG org.mybatis.spring.SqlSessionUtils - Fetched SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6f745882] from current transaction 2025-09-18 15:29:33.644 [reactor-http-nio-5] DEBUG c.hvlink.mapper.master.ShipperMapper.updateShipper - ==> Preparing: UPDATE tm_shipper SET company_code = ?, supplier_code = ?, shipper_name = ?, address = ?, contact_person = ?, contact_tel = ?, contact_mobile = ?, is_default = ? WHERE id = ? 2025-09-18 15:29:33.645 [reactor-http-nio-5] DEBUG c.hvlink.mapper.master.ShipperMapper.updateShipper - ==> Parameters: null, null, 发货方AC(String), null, 1(String), null, null, 否(String), 29(Integer) 2025-09-18 15:29:33.660 [reactor-http-nio-5] DEBUG org.mybatis.spring.SqlSessionUtils - Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6f745882] 2025-09-18 15:29:33.660 [reactor-http-nio-5] DEBUG o.s.j.support.SQLErrorCodeSQLExceptionTranslator - Unable to translate SQLException with Error code '515', will now try the fallback translator 2025-09-18 15:29:33.660 [reactor-http-nio-5] DEBUG o.s.jdbc.support.SQLStateSQLExceptionTranslator - Extracted SQL state class '23' from value '23000' 2025-09-18 15:29:33.661 [reactor-http-nio-5] DEBUG org.mybatis.spring.SqlSessionUtils - Transaction synchronization deregistering SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6f745882] 2025-09-18 15:29:33.661 [reactor-http-nio-5] DEBUG org.mybatis.spring.SqlSessionUtils - Transaction synchronization closing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6f745882] 2025-09-18 15:29:33.661 [reactor-http-nio-5] DEBUG o.s.jdbc.datasource.DataSourceTransactionManager - Initiating transaction rollback 2025-09-18 15:29:33.661 [reactor-http-nio-5] DEBUG o.s.jdbc.datasource.DataSourceTransactionManager - Rolling back JDBC transaction on Connection [ConnectionID:1 ClientConnectionId: 832daba7-ee0b-4bc1-9a5c-db187f8edc8d] 2025-09-18 15:29:33.679 [reactor-http-nio-5] DEBUG o.s.jdbc.datasource.DataSourceTransactionManager - Releasing JDBC Connection [ConnectionID:1 ClientConnectionId: 832daba7-ee0b-4bc1-9a5c-db187f8edc8d] after transaction 2025-09-18 15:29:33.680 [reactor-http-nio-5] DEBUG o.s.w.r.r.m.annotation.ResponseBodyResultHandler - [a0e83397-4] Using 'application/json' given [application/json, text/plain, */*] and supported [application/json, application/*+json, application/x-ndjson, text/event-stream] 2025-09-18 15:29:33.680 [reactor-http-nio-5] DEBUG o.s.w.r.r.m.annotation.ResponseBodyResultHandler - [a0e83397-4] 0..1 [com.hvlink.common.Result<java.lang.String>] 2025-09-18 15:29:33.680 [reactor-http-nio-5] DEBUG o.s.http.codec.json.Jackson2JsonEncoder - [a0e83397-4] Encoding [Result(status=500, msg=<EOL><EOL>### Error updating database. Cause: com.microsoft.sqlserver.jdbc.SQLServer (truncated)...] 2025-09-18 15:29:33.681 [reactor-http-nio-5] DEBUG reactor.netty.http.server.HttpServerOperations - [a0e83397-1, L:/192.168.10.122:9000 - R:/192.168.10.221:51066] Detected non persistent http connection, preparing to close 2025-09-18 15:29:33.681 [reactor-http-nio-5] DEBUG reactor.netty.http.server.HttpServerOperations - [a0e83397-1, L:/192.168.10.122:9000 - R:/192.168.10.221:51066] Last HTTP packet was sent, terminating the channel 2025-09-18 15:29:33.681 [reactor-http-nio-5] DEBUG reactor.netty.channel.ChannelOperations - [a0e83397-1, L:/192.168.10.122:9000 - R:/192.168.10.221:51066] [HttpServer] Channel inbound receiver cancelled (operation cancelled). 2025-09-18 15:29:33.681 [reactor-http-nio-5] DEBUG o.s.web.server.adapter.HttpWebHandlerAdapter - [a0e83397-4] Completed 200 OK
09-19
你提供的是一段 **Spring WebFlux + MyBatis + Reactor Netty** 的完整日志,从 HTTP 请求进入一直到数据库更新失败并回滚事务。我们来逐行分析问题的根本原因,并给出解决方案。 --- ## ✅ 问题定位:核心错误 关键日志如下: ```log 2025-09-18 15:29:33.660 [reactor-http-nio-5] DEBUG o.s.j.support.SQLErrorCodeSQLExceptionTranslator - Unable to translate SQLException with Error code '515' 2025-09-18 15:29:33.660 [reactor-http-nio-5] DEBUG o.s.jdbc.support.SQLStateSQLExceptionTranslator - Extracted SQL state class '23' from value '23000' ``` > 🔴 **SQL Server 错误码 515:Cannot insert the value NULL into column 'xxx', column does not allow nulls. UPDATE fails.** 说明:你在执行 `UPDATE` 时,试图将一个 **不允许为 NULL 的列更新为 NULL**,而该字段在数据库中定义了 `NOT NULL`。 --- ## 📌 具体 SQL 分析 ```sql UPDATE tm_shipper SET company_code = ?, supplier_code = ?, shipper_name = ?, address = ?, contact_person = ?, contact_tel = ?, contact_mobile = ?, is_default = ? WHERE id = ? ``` 参数值: ```text Parameters: null, null, 发货方AC(String), null, 1(String), null, null, 否(String), 29(Integer) ``` ### ❌ 问题暴露: - `company_code = null` - `supplier_code = null` - `address = null` - `contact_tel = null` - `contact_mobile = null` 这些字段如果在数据库表 `tm_shipper` 中被定义为 **`NOT NULL`**,那么传入 `NULL` 就会触发 **SQL Server 错误 515**! --- ## 🧩 根本原因总结 | 原因 | 说明 | |------|------| | 💥 DTO 数据缺失 | 前端没有传递 `companyCode`, `supplierCode` 等字段(或值为 null) | | 🛠 实体类未做非空校验 | 后端未对必要字段进行合法性检查 | | 🗃 数据库约束严格 | `company_code` 等字段是 `NOT NULL`,但你尝试写入 `NULL` | | 🔄 更新逻辑缺陷 | 使用了全量字段 SET,即使某些字段没变也设为 NULL | --- ## ✅ 解决方案 ### ✅ 方案一:前端保证必填字段上传(推荐) 确保前端发送的 JSON 包含所有必要字段: ```json { "id": 29, "companyCode": "C001", "supplierCode": "S001", "shipperName": "发货方AC", "contactPerson": "张三", "contactTel": "021-12345678", ... } ``` > ⚠️ 如果字段为空字符串 `""`,也要避免传 `null` --- ### ✅ 方案二:后端接收 DTO 做校验(防御性编程) 使用 `@NotNull`、`@NotBlank` 等注解校验: ```java public class ShipperDTO { private Integer id; @NotBlank(message = "公司编码不能为空") private String companyCode; @NotBlank(message = "供应商编码不能为空") private String supplierCode; @NotBlank(message = "发货方名称不能为空") private String shipperName; // 其他字段... } ``` Controller 添加校验: ```java @PutMapping("/update") public Mono<Result<String>> updateShipper(@Valid @RequestBody ShipperDTO dto) { return shipperService.updateShipper(dto) .thenReturn(Result.success("更新成功")); } ``` 这样会在解析 JSON 阶段就报错,而不是等到 DB 抛异常。 --- ### ✅ 方案三:只更新非 null 字段(推荐做法) 不要用 MyBatis 的全字段 `UPDATE`,而是改为 **选择性更新**。 #### 方法 1:使用 `<set>` 动态标签(XML) ```xml <update id="updateShipper"> UPDATE tm_shipper <set> <if test="companyCode != null">company_code = #{companyCode},</if> <if test="supplierCode != null">supplier_code = #{supplierCode},</if> <if test="shipperName != null">shipper_name = #{shipperName},</if> <if test="address != null">address = #{address},</if> <if test="contactPerson != null">contact_person = #{contactPerson},</if> <if test="contactTel != null">contact_tel = #{contactTel},</if> <if test="contactMobile != null">contact_mobile = #{contactMobile},</if> <if test="isDefault != null">is_default = #{isDefault},</if> update_time = GETDATE() </set> WHERE id = #{id} </update> ``` ✅ 这样只有非 null 的字段才会参与更新,不会覆盖原有数据。 --- #### 方法 2:使用 MyBatis-Plus 的 `updateById(entity)`(更简单) 如果你用的是 **MyBatis-Plus**,可以直接: ```java // DTO → PO 转换 ShipperPO po = BeanCopyUtils.copyBean(dto, ShipperPO.class); // 使用 MP 的 updateById,它会自动忽略 null 字段(取决于 global config) shipperMapper.updateById(po); ``` ⚠️ 注意:默认情况下 MP 是“全量更新”,你需要配置: ```yaml mybatis-plus: global-config: db-config: field-strategy: NOT_NULL # 只更新非 null 字段 ``` > ⚠️ 注:`field-strategy` 在新版本中已废弃,建议改用 `insertStrategy` / `updateStrategy` 最新写法(Java 配置): ```java @Component public class MyMetaObjectHandler implements MetaObjectHandler { @Override public void updateFill(MetaObject metaObject) { this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.now()); } } // 并在实体类上标注策略 @TableField(fill = FieldFill.UPDATE, update = "now()") // 或自定义 private LocalDateTime updateTime; ``` 同时,在字段上指定更新策略: ```java @TableField(updateStrategy = FieldStrategy.NOT_NULL) private String companyCode; ``` --- ### ✅ 方案四:数据库允许 NULL(不推荐) 除非业务允许,否则不要修改数据库结构去适应代码 bug。 ```sql ALTER TABLE tm_shipper ALTER COLUMN company_code VARCHAR(50) NULL; ``` ❌ 不推荐!破坏数据完整性。 --- ## ✅ 最佳实践建议 | 措施 | 建议 | |------|------| | ✔️ 前端提交完整数据 | 必填字段不能为 null | | ✔️ 后端 DTO 校验 | 使用 `@Valid` + `@NotBlank` | | ✔️ 使用动态 SQL 更新 | `<set><if>` 结合使用 | | ✔️ 使用 MyBatis-Plus 更新策略 | `updateStrategy = NOT_NULL` | | ✔️ 记录操作日志 | 打印出要更新的字段和值,便于排查 | | ✔️ 统一异常处理 | 捕获 `DataIntegrityViolationException` 返回友好提示 | ```java @ExceptionHandler(DataIntegrityViolationException.class) public Mono<Result<?>> handleIntegrity(Exception e) { return Mono.just(Result.error("数据完整性冲突,请检查必填字段")); } ``` --- ## ✅ 总结 | 项目 | 内容 | |------|------| | 🔍 错误类型 | SQL Server 错误 515 | | 📌 原因 | 向 `NOT NULL` 字段插入 `NULL` | | 📍 关键字段 | `company_code`, `supplier_code` 等为 null | | ✅ 解决方案 | 1. 前端补全数据<br>2. 后端校验<br>3. 使用动态更新 SQL 或 MP 更新策略 | ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值