奇怪的现象:BigDecimal.new('3.0').to_f == 3.0 # => false

BigDecimal 精度问题
在使用 Ruby 的 BigDecimal 类处理浮点数时发现了一个奇怪的现象:BigDecimal 转换为 Float 进行比较时出现不一致的结果。通过 to_s 方法可以解决此问题。
开发中遇到奇怪的现象:
> ruby script/console -s
>> BigDecimal.new('3.0').to_f == 3.0
=> false
>> BigDecimal.new('3.0').to_i == 3
=> true
>> BigDecimal.new('3.0').to_s == '3.0'
=> true


虽然可以通过to_s绕过这个问题,但是这个现象百思不得其解。
package com.example.model; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import lombok.Data; import java.math.BigDecimal; import java.io.Serializable; import com.baomidou.mybatisplus.annotation.TableName; @Data @TableName("goods") public class Goods implements Serializable { @TableId(type = IdType.AUTO) private Long id; @TableField(value="name") private String name; private String storage; private String goodsType; // 改为驼峰命名,与数据库goods_type对应 private Long count; private String remark; private BigDecimal price; } package com.example.model; import lombok.Data; import java.math.BigDecimal; import java.util.Date; import java.util.List; import java.io.Serializable; @Data public class Order implements Serializable{ private Long orderId; private Long userId; private Date createTime; private BigDecimal totalAmount; private List<OrderItem> orderItems; // 关联订单项,创建订单时可一起处理 private String status; } package com.example.model; import lombok.Data; import java.math.BigDecimal; import java.io.Serializable; @Data public class OrderItem implements Serializable{ private Long itemId; private Long orderId; private Long goodsId; private String goodsName; private BigDecimal price; private Integer quantity; } package com.example.model; import lombok.Data; import java.io.Serializable; @Data public class User implements Serializable { private Long userId; // 对应表中的 id private String no; // 对应表中的 no private String name; // 对应表中的 name private String password; // 对应表中的 password private Integer age; // 对应表中的 age(int 类型在 Java 中对应 Integer) private String sex; // 对应表中的 sex private String phone; // 对应表中的 phone private Long roleId; // 对应表中的 role_id(Java 中一般用驼峰命名法) private Boolean isValid; // 对应表中的 is_valid(tinyint(1) 在 Java 中一般用 Boolean 表示) public Long getRoleId() { return roleId; } public void setRoleId(Long roleId) { this.roleId = roleId; } } package com.example.order.config; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @Configuration public class RestTemplateConfig { @LoadBalanced @Bean public RestTemplate restTemplate() { return new RestTemplate(); } } package com.example.order.controller; import com.example.model.Goods; import com.example.model.Order; import com.example.model.OrderItem; import com.example.model.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; @RestController @RequestMapping("/orders") public class OrderController { private static final Logger logger = LoggerFactory.getLogger(OrderController.class); private final Map<Long, Order> orderMap = new HashMap<>(); private final AtomicLong idGenerator = new AtomicLong(1); @Autowired private LoadBalancerClient loadBalancerClient; @Autowired private RestTemplate restTemplate; // @PostMapping("/create") // public Order createOrder(OrderRequest request) { // try { // // 调用用户服务获取用户信息 // User user = getUser(request.getUserId()); // if (user == null) { // logger.error("未找到用户信息,用户 ID: {}", request.getUserId()); // return null; // } // // List<OrderItem> orderItems = new ArrayList<>(); // BigDecimal totalAmount = BigDecimal.ZERO; // // for (OrderItemRequest itemRequest : request.getOrderItems()) { // Goods goods = getGoods(itemRequest.getGoodsId()); // if (goods != null) { // OrderItem orderItem = new OrderItem(); // orderItem.setGoodsId(goods.getId()); // orderItem.setGoodsName(goods.getName()); // orderItem.setPrice(goods.getPrice()); // orderItem.setQuantity(itemRequest.getQuantity()); // orderItems.add(orderItem); // totalAmount = totalAmount.add(goods.getPrice().multiply(BigDecimal.valueOf(itemRequest.getQuantity()))); // } else { // logger.warn("未找到商品信息,商品 ID: {}", itemRequest.getGoodsId()); // } // } // // // 创建订单 // Order order = new Order(); // order.setOrderId(idGenerator.getAndIncrement()); // order.setUserId(request.getUserId()); // order.setCreateTime(new Date()); // order.setTotalAmount(totalAmount); // order.setOrderItems(orderItems); // order.setStatus("CREATED"); // // orderMap.put(order.getOrderId(), order); // return order; // } catch (Exception e) { // logger.error("创建订单时发生异常", e); // return null; // } // } // // private User getUser(Long userId) { // try { // ServiceInstance instance = loadBalancerClient.choose("user-service"); // if (instance == null) { // logger.error("未找到 user - service 的实例"); // return null; // } // String url = String.format("http://%s:%d/users/%d", instance.getHost(), instance.getPort(), userId); // return restTemplate.getForObject(url, User.class); // } catch (Exception e) { // logger.error("调用用户服务获取用户信息时发生异常,用户 ID: {}", userId, e); // return null; // } // } // // private Goods getGoods(Long goodsId) { // try { // ServiceInstance instance = loadBalancerClient.choose("goods-service"); // String url = String.format("http://%s:%d/goods/%d", instance.getHost(), instance.getPort(), goodsId); // return restTemplate.getForObject(url, Goods.class); // } catch (Exception e) { // logger.error("调用商品服务获取商品信息时发生异常,商品 ID: {}", goodsId, e); // return null; // } // } @PostMapping(value = "/create", consumes = { "application/x-www-form-urlencoded", "application/json" }) public Order createOrder( @RequestParam("userId") Long userId, @RequestParam("goodsId") List<Long> goodsIds, @RequestParam("quantity") List<Integer> quantities) { try { // 检查参数有效性 if (userId == null || goodsIds == null || quantities == null || goodsIds.size() != quantities.size()) { logger.error("创建订单失败:参数不完整或无效"); return null; } // 调用用户服务获取用户信息 User user = getUser(userId); if (user == null) { logger.error("未找到用户信息,用户 ID: {}", userId); return null; } // 构建订单项 List<OrderItem> orderItems = new ArrayList<>(); BigDecimal totalAmount = BigDecimal.ZERO; for (int i = 0; i < goodsIds.size(); i++) { Long goodsId = goodsIds.get(i); Integer quantity = quantities.get(i); Goods goods = getGoods(goodsId); if (goods != null) { OrderItem orderItem = new OrderItem(); orderItem.setGoodsId(goods.getId()); orderItem.setGoodsName(goods.getName()); orderItem.setPrice(goods.getPrice()); orderItem.setQuantity(quantity); orderItems.add(orderItem); totalAmount = totalAmount.add(goods.getPrice().multiply(BigDecimal.valueOf(quantity))); } else { logger.warn("未找到商品信息,商品 ID: {}", goodsId); } } // 创建订单 Order order = new Order(); order.setOrderId(idGenerator.getAndIncrement()); order.setUserId(userId); order.setCreateTime(new Date()); order.setTotalAmount(totalAmount); order.setOrderItems(orderItems); order.setStatus("CREATED"); orderMap.put(order.getOrderId(), order); return order; } catch (Exception e) { logger.error("创建订单时发生异常", e); return null; } } private User getUser(Long userId) { try { ServiceInstance instance = loadBalancerClient.choose("service-user"); if (instance == null) { logger.error("service-user的实例"); return null; } String url = String.format("http://%s:%d/users/%d", instance.getHost(), instance.getPort(), userId); return restTemplate.getForObject(url, User.class); } catch (Exception e) { logger.error("调用用户服务获取用户信息时发生异常,用户 ID: {}", userId, e); return null; } } private Goods getGoods(Long goodsId) { try { ServiceInstance instance = loadBalancerClient.choose("service-goods"); String url = String.format("http://%s:%d/goods/%d", instance.getHost(), instance.getPort(), goodsId); return restTemplate.getForObject(url, Goods.class); } catch (Exception e) { logger.error("调用商品服务获取商品信息时发生异常,商品 ID: {}", goodsId, e); return null; } } @GetMapping("/{orderId}") public Order getOrder(@PathVariable Long orderId) { return orderMap.getOrDefault(orderId, null); } // 公开内部请求类(用于 x - www - form - urlencoded) public static class OrderRequest { private Long userId; private List<OrderItemRequest> orderItems; public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public List<OrderItemRequest> getOrderItems() { return orderItems; } public void setOrderItems(List<OrderItemRequest> orderItems) { this.orderItems = orderItems; } } public static class OrderItemRequest { private Long goodsId; private Integer quantity; public Long getGoodsId() { return goodsId; } public void setGoodsId(Long goodsId) { this.goodsId = goodsId; } public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } } } //package com.example.order.mapper; // //import com.example.model.Order; //import com.example.model.OrderItem; //import org.apache.ibatis.annotations.Mapper; //import org.apache.ibatis.annotations.Insert; //import org.apache.ibatis.annotations.Options; // //@Mapper //public interface OrderMapper<OrderItem, Order> { // // // 插入订单主表数据,同时获取自增的 order_id // @Insert("INSERT INTO `order` (user_id, create_time, total_amount, status) " + // "VALUES (#{userId}, #{createTime}, #{totalAmount}, #{status})") // @Options(useGeneratedKeys = true, keyProperty = "orderId", keyColumn = "order_id") // void insertOrder(Order order); // // // 插入订单项数据 // @Insert("INSERT INTO order_item (order_id, goods_id, goods_name, price, quantity) " + // "VALUES (#{orderId}, #{goodsId}, #{goodsName}, #{price}, #{quantity})") // void insertOrderItem(OrderItem orderItem); //} package com.example.order.mapper; import com.example.model.Order; import com.example.model.OrderItem; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Options; @Mapper // 必须添加该注解,让 MyBatis 扫描并创建 Mapper Bean public interface OrderMapper { @Insert("INSERT INTO `order` (user_id, create_time, total_amount, status) " + "VALUES (#{userId}, #{createTime}, #{totalAmount}, #{status})") @Options(useGeneratedKeys = true, keyProperty = "orderId", keyColumn = "order_id") void insertOrder(Order order); @Insert("INSERT INTO order_item (order_id, goods_id, goods_name, price, quantity) " + "VALUES (#{orderId}, #{goodsId}, #{goodsName}, #{price}, #{quantity})") void insertOrderItem(OrderItem orderItem); } package com.example.order.service; import com.example.order.mapper.OrderMapper; import com.example.model.Order; import com.example.model.OrderItem; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.List; @Service public class OrderService { private final OrderMapper orderMapper; public OrderService(OrderMapper orderMapper) { this.orderMapper = orderMapper; } @Transactional public Order createOrder(Order order) { // 设置订单创建时间 order.setCreateTime(new Date()); // 先插入订单主表,获取自增的 orderId orderMapper.insertOrder(order); Long orderId = order.getOrderId(); // 遍历订单项,设置 orderId 后插入 List<OrderItem> orderItems = order.getOrderItems(); if (orderItems != null && !orderItems.isEmpty()) { for (OrderItem item : orderItems) { item.setOrderId(orderId); orderMapper.insertOrderItem(item); } } return order; } } package com.example.order; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication @EnableDiscoveryClient @MapperScan("com.example.order.mapper") public class OrderServiceApplication { public static void main(String[] args) { SpringApplication.run(OrderServiceApplication.class, args); } @Bean public RestTemplate restTemplate() { return new RestTemplate(); } } <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.mapper.OrderMapper"> <resultMap id="OrderResultMap" type="com.example.model.Order"> <id column="order_id" property="orderId"/> <result column="order_user_id" property="orderUserId"/> <result column="order_create_time" property="orderCreateTime"/> <result column="order_total_amount" property="orderTotalAmount"/> <result column="order_status" property="orderStatus"/> </resultMap> <select id="selectOrderById" parameterType="java.lang.Long" resultMap="OrderResultMap"> SELECT order_id, user_id, create_time, total_amount, status FROM `order` WHERE order_id = #{orderId} </select> <insert id="insertOrder" parameterType="com.example.model.Order" useGeneratedKeys="true" keyProperty="orderId"> INSERT INTO `order` (user_id, create_time, total_amount, status) VALUES (#{orderUserId}, #{orderCreateTime}, #{orderTotalAmount}, #{orderStatus}) </insert> <update id="updateOrder" parameterType="com.example.model.Order"> UPDATE `order` SET user_id = #{orderUserId}, create_time = #{orderCreateTime}, total_amount = #{orderTotalAmount}, status = #{orderStatus} WHERE order_id = #{orderId} </update> <delete id="deleteOrder" parameterType="java.lang.Long"> DELETE FROM `order` WHERE order_id = #{orderId} </delete> </mapper> server: port: 8000 spring: main: allow-bean-definition-overriding: true datasource: url: jdbc:mysql://localhost:3306/hdms?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8 driver-class-name: com.mysql.cj.jdbc.Driver username: root password: 123456 application: name: service-order cloud: nacos: discovery: server-addr: 127.0.0.1:8848 jackson: # 添加Jackson配置确保BigDecimal序列化正常 default-property-inclusion: non_null serialization: write-dates-as-timestamps: false deserialization: fail-on-unknown-properties: false mybatis-plus: configuration: map-underscore-to-camel-case: true # 开启驼峰命名 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 启用SQL日志 mapper-locations: classpath*:/mapper/**/*.xml type-aliases-package: com.example.model mapper-scan: com.example.order.mapper package com.example.user.controller; import com.example.model.User; import com.example.user.service.UserService; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/users") public class UserController { private final UserService userService; public UserController(UserService userService) { this.userService = userService; } @GetMapping("/{id}") public User getUserById(@PathVariable Long id) { return userService.getById(id); // 调用 UserService 的查询方法 } @PostMapping("/create") public User save(User user) { return userService.save(user); } } package com.example.user.mapper; import com.example.model.User; import org.apache.ibatis.annotations.Mapper; import java.util.List; @Mapper public interface UserMapper<User> { // 添加selectById方法声明 User selectById(Long id); // 保持原有方法 User selectUserById(Long id); // 新增基础CRUD方法 List<User> selectAll(); int insertUser(User user); int updateUser(User user); int deleteUser(Long id); } package com.example.user.service; import com.example.model.Goods; import com.example.user.mapper.UserMapper; import com.example.model.User; import org.springframework.stereotype.Service; @Service public class UserService { private final UserMapper userMapper; public UserService(UserMapper userMapper) { this.userMapper = userMapper; } public User save(User user) { // 设置 is_valid 的值 user.setIsValid(true); // 设置 role_id 的值(假设之前已经处理过 role_id 的问题) user.setRoleId(1L); userMapper.insertUser(user); return user; } public User getById(Long id) { return (User) userMapper.selectById(id); // MyBatis-Plus 内置的根据id查询方法 } } package com.example.user; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @SpringBootApplication @EnableDiscoveryClient @MapperScan("com.example.user.mapper") public class UserServiceApplication { public static void main(String[] args) { SpringApplication.run(UserServiceApplication.class, args); } } <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.user.mapper.UserMapper"> <!-- 使用正确的实体类路径 --> <resultMap id="UserResultMap" type="com.example.user.entity.User"> <id column="id" property="id"/> <result column="no" property="no"/> <result column="name" property="name"/> <result column="password" property="password"/> <result column="age" property="age"/> <result column="sex" property="sex"/> <result column="phone" property="phone"/> <result column="role_id" property="roleId"/> <result column="is_valid" property="isValid"/> </resultMap> <!-- 添加selectById方法 --> <select id="selectById" resultMap="UserResultMap"> SELECT id, no, name, password, age, sex, phone, role_id, is_valid FROM user WHERE id = #{id} </select> <!-- 简化参数类型声明 --> <select id="selectUserById" resultMap="UserResultMap"> SELECT id, no, name, password, age, sex, phone, role_id, is_valid FROM user WHERE id = #{id} </select> <!-- 添加基础CRUD操作 --> <select id="selectAll" resultMap="UserResultMap"> SELECT * FROM user </select> <insert id="insertUser" useGeneratedKeys="true" keyProperty="id"> INSERT INTO user (no, name, password, age, sex, phone, role_id, is_valid) VALUES (#{no}, #{name}, #{password}, #{age}, #{sex}, #{phone}, #{roleId}, #{isValid}) </insert> <update id="updateUser"> UPDATE user SET no = #{no}, name = #{name}, password = #{password}, age = #{age}, sex = #{sex}, phone = #{phone}, role_id = #{roleId}, is_valid = #{isValid} WHERE id = #{id} </update> <delete id="deleteUser"> DELETE FROM user WHERE id = #{id} </delete> </mapper> server: port: 9000 spring: main: allow-bean-definition-overriding: true datasource: url: jdbc:mysql://localhost:3306/hdms?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8 driver-class-name: com.mysql.cj.jdbc.Driver username: root password: 123456 application: name: service-user cloud: nacos: discovery: server-addr: 127.0.0.1:8848 jackson: # 添加Jackson配置确保BigDecimal序列化正常 default-property-inclusion: non_null serialization: write-dates-as-timestamps: false deserialization: fail-on-unknown-properties: false mybatis-plus: configuration: map-underscore-to-camel-case: true # 开启驼峰命名 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 启用SQL日志 mapper-locations: classpath*:/mapper/**/*.xml type-aliases-package: com.example.model logging: level: com.example.user.mapper: TRACE 出现问题:2025-06-17T15:19:50.565+08:00 ERROR 21148 --- [service-order] [nio-8000-exec-2] c.e.order.controller.OrderController : service-user的实例 2025-06-17T15:19:50.565+08:00 ERROR 21148 --- [service-order] [nio-8000-exec-2] c.e.order.controller.OrderController : 未找到用户信息,用户 ID: 2
06-18
@RestController @RequestMapping("/system/healthRecords") public class HealthRecordsController { @Autowired private HealthRecordsMapper healthRecordsMapper; // 直接使用 MP 提供的 BaseMapper @Autowired private ElderlyProfilesMapper elderlyMapper; /** * GET /list - 查询健康记录列表(支持条件分页) */ @PreAuthorize("@ss.hasPermi(&#39;system:health:list&#39;)") @GetMapping("/list") public TableDataInfo list(HealthRecords records) { // 构建查询条件 QueryWrapper<HealthRecords> wrapper = new QueryWrapper<>(); if (records.getElderlyName() != null) { ElderlyProfiles elderlyProfiles = elderlyMapper.selectOne(new QueryWrapper<ElderlyProfiles>().eq("name", records.getElderlyName())); wrapper.eq("elderly_id", elderlyProfiles.getId()); } if (records.getRecordDate() != null) { wrapper.eq("DATE(record_date)", new java.sql.Date(records.getRecordDate().getTime())); // 按日期精确匹配 } if (records.getRecorder() != null && !records.getRecorder().trim().isEmpty()) { wrapper.like("recorder", records.getRecorder()); } wrapper.orderByDesc("record_date", "id"); Page<HealthRecords> page = new Page<>(records.getPageNum(), records.getPageSize()); Page<HealthRecords> resultPage = healthRecordsMapper.selectPage(page, wrapper); TableDataInfo tableDataInfo = new TableDataInfo(); tableDataInfo.setRows(resultPage.getRecords()); tableDataInfo.setTotal(resultPage.getTotal()); return tableDataInfo; }health中的elderlyId联查,将ElderlyProfiles中的name属性set进health中的elderlyName属性package com.ruoyi.system.domain; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.math.BigDecimal; import java.util.Date; import lombok.Data; /** * 每日健康数据 * @TableName health_records */ @TableName(value ="health_records") @Data public class HealthRecords { /** * */ @TableId(type = IdType.AUTO) private Integer id; /** * */ private Long elderlyId; @TableField(exist = false) private String elderlyName; /** * */ private Date recordDate; /** * */ private BigDecimal temperature; /** * */ private String bloodPressure; /** * */ private Integer heartRate; /** * */ private BigDecimal weight; /** * */ private String remark; /** * */ private String recorder; @TableField(exist = false) private Integer pageNum; @TableField(exist = false) private Integer pageSize; @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } HealthRecords other = (HealthRecords) that; return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getElderlyId() == null ? other.getElderlyId() == null : this.getElderlyId().equals(other.getElderlyId())) && (this.getRecordDate() == null ? other.getRecordDate() == null : this.getRecordDate().equals(other.getRecordDate())) && (this.getTemperature() == null ? other.getTemperature() == null : this.getTemperature().equals(other.getTemperature())) && (this.getBloodPressure() == null ? other.getBloodPressure() == null : this.getBloodPressure().equals(other.getBloodPressure())) && (this.getHeartRate() == null ? other.getHeartRate() == null : this.getHeartRate().equals(other.getHeartRate())) && (this.getWeight() == null ? other.getWeight() == null : this.getWeight().equals(other.getWeight())) && (this.getRemark() == null ? other.getRemark() == null : this.getRemark().equals(other.getRemark())) && (this.getRecorder() == null ? other.getRecorder() == null : this.getRecorder().equals(other.getRecorder())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); result = prime * result + ((getElderlyId() == null) ? 0 : getElderlyId().hashCode()); result = prime * result + ((getRecordDate() == null) ? 0 : getRecordDate().hashCode()); result = prime * result + ((getTemperature() == null) ? 0 : getTemperature().hashCode()); result = prime * result + ((getBloodPressure() == null) ? 0 : getBloodPressure().hashCode()); result = prime * result + ((getHeartRate() == null) ? 0 : getHeartRate().hashCode()); result = prime * result + ((getWeight() == null) ? 0 : getWeight().hashCode()); result = prime * result + ((getRemark() == null) ? 0 : getRemark().hashCode()); result = prime * result + ((getRecorder() == null) ? 0 : getRecorder().hashCode()); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", elderlyId=").append(elderlyId); sb.append(", recordDate=").append(recordDate); sb.append(", temperature=").append(temperature); sb.append(", bloodPressure=").append(bloodPressure); sb.append(", heartRate=").append(heartRate); sb.append(", weight=").append(weight); sb.append(", remark=").append(remark); sb.append(", recorder=").append(recorder); sb.append("]"); return sb.toString(); } }package com.ruoyi.system.domain; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.util.Date; import lombok.Data; /** * 老人档案表 * @TableName elderly_profiles */ @TableName(value ="elderly_profiles") @Data public class ElderlyProfiles { /** * 主键ID */ @TableId(type = IdType.AUTO) private Long id; /** * 名字 */ private String name; /** * 身份证号 */ private String idCard; /** * 手机号 */ private String phone; /** * 紧急联系人 */ private String emergencyContactPhone; /** * 健康史 */ private String healthHistory; /** * 过敏史 */ private String allergyHistory; /** * 创建时间 */ private Date createdTime; private String isCheckedIn; /** * 更新时间 */ private Date updatedTime; @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } ElderlyProfiles other = (ElderlyProfiles) that; return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName())) && (this.getIdCard() == null ? other.getIdCard() == null : this.getIdCard().equals(other.getIdCard())) && (this.getPhone() == null ? other.getPhone() == null : this.getPhone().equals(other.getPhone())) && (this.getEmergencyContactPhone() == null ? other.getEmergencyContactPhone() == null : this.getEmergencyContactPhone().equals(other.getEmergencyContactPhone())) && (this.getHealthHistory() == null ? other.getHealthHistory() == null : this.getHealthHistory().equals(other.getHealthHistory())) && (this.getAllergyHistory() == null ? other.getAllergyHistory() == null : this.getAllergyHistory().equals(other.getAllergyHistory())) && (this.getCreatedTime() == null ? other.getCreatedTime() == null : this.getCreatedTime().equals(other.getCreatedTime())) && (this.getUpdatedTime() == null ? other.getUpdatedTime() == null : this.getUpdatedTime().equals(other.getUpdatedTime())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); result = prime * result + ((getIdCard() == null) ? 0 : getIdCard().hashCode()); result = prime * result + ((getPhone() == null) ? 0 : getPhone().hashCode()); result = prime * result + ((getEmergencyContactPhone() == null) ? 0 : getEmergencyContactPhone().hashCode()); result = prime * result + ((getHealthHistory() == null) ? 0 : getHealthHistory().hashCode()); result = prime * result + ((getAllergyHistory() == null) ? 0 : getAllergyHistory().hashCode()); result = prime * result + ((getCreatedTime() == null) ? 0 : getCreatedTime().hashCode()); result = prime * result + ((getUpdatedTime() == null) ? 0 : getUpdatedTime().hashCode()); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", name=").append(name); sb.append(", idCard=").append(idCard); sb.append(", phone=").append(phone); sb.append(", emergencyContactPhone=").append(emergencyContactPhone); sb.append(", healthHistory=").append(healthHistory); sb.append(", allergyHistory=").append(allergyHistory); sb.append(", createdTime=").append(createdTime); sb.append(", updatedTime=").append(updatedTime); sb.append("]"); return sb.toString(); } }
09-27
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.springboot_test.dao.CardDao"> <!-- 根据卡号和密码查询用户 --> <select id="check" resultType="com.example.springboot_test.po.Card"> SELECT id, name, password, id_card AS idCard, card_number AS cardNumber, balance, create_time AS createTime, status FROM bank_card WHERE card_number = #{cardNumber} </select> <!--扣款方 --> <update id="transferOut"> update bank_card set balance=balance - #{amount} where card_number = #{cardNumber} and balance >= #{amount} </update> <update id="transferIn"> update bank_card set balance=balance + #{amount} where card_number = #{targetAccount} </update> <select id="findTarget" resultType="int"> select count(*) from bank_card where card_number=#{targetAccount} </select> <insert id="insertRecord" > INSERT INTO transaction_record ( operate_account, operation_type, transaction_amount, target_account, operation_time ) VALUES ( #{operateAccount}, #{operationType}, #{transactionAmount}, #{targetAccount}, #{operationTime} ) </insert> </mapper> package com.example.springboot_test.service; import com.example.springboot_test.dao.CardDao; import com.example.springboot_test.po.Card; import com.example.springboot_test.po.Record; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.math.BigDecimal; import java.util.Date; @Service public class BankService<T> { @Resource private CardDao cardDao; public Card check(String cardNumber) { return cardDao.check(cardNumber); } @Transactional(rollbackFor = Exception.class) public boolean transfer(String cardNumber, String targetAccount, BigDecimal amount) { Card payer = cardDao.check(cardNumber); Integer count = cardDao.findTarget(targetAccount); if (count==0) { System.out.println("对方账号不存在!"); } if (targetAccount == null || targetAccount.equals("")) { System.out.println("请输入目标账号"); } if (cardNumber.equals(targetAccount)) { System.out.println("无法向自己转账"); } //判断接受账号数据库中是否存在 if (payer.getBalance().compareTo(amount) < 0) { System.out.println("用户余额不足"); } int a=cardDao.transferIn(targetAccount, amount); int b=cardDao.transferOut(cardNumber, amount); //向转账记录表插入数据 Record record=new Record(); record.setOperateAccount(cardNumber); record.setOperationType("transfer"); record.setTransactionAmount(amount); record.setTargetAccount(targetAccount); record.setOperationTime(new Date()); return true; } } package com.example.springboot_test.dao; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; @Repository @Mapper public interface RecordDao { int insertRecord(RecordDao record); } package com.example.springboot_test.po; import java.math.BigDecimal; import java.util.Date; public class Record { private Integer id; private String operateAccount; private String operationType; private BigDecimal transactionAmount; private String targetAccount; private Date operationTime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getOperateAccount() { return operateAccount; } public void setOperateAccount(String operateAccount) { this.operateAccount = operateAccount; } public String getOperationType() { return operationType; } public void setOperationType(String operationType) { this.operationType = operationType; } public BigDecimal getTransactionAmount() { return transactionAmount; } public void setTransactionAmount(BigDecimal transactionAmount) { this.transactionAmount = transactionAmount; } public String getTargetAccount() { return targetAccount; } public void setTargetAccount(String targetAccount) { this.targetAccount = targetAccount; } public Date getOperationTime() { return operationTime; } public void setOperationTime(Date operationTime) { this.operationTime = operationTime; } } 可以正常转账,但是没有添加转账记录,我怀疑是驼峰命名法
10-30
【无人机】基于改进粒子群算法的无人机路径规划研究[和遗传算法、粒子群算法进行比较](Matlab代码实现)内容概要:本文围绕基于改进粒子群算法的无人机路径规划展开研究,重点探讨了在复杂环境中利用改进粒子群算法(PSO)实现无人机三维路径规划的方法,并将其与遗传算法(GA)、标准粒子群算法等传统优化算法进行对比分析。研究内容涵盖路径规划的多目标优化、避障策略、航路点约束以及算法收敛性和寻优能力的评估,所有实验均通过Matlab代码实现,提供了完整的仿真验证流程。文章还提到了多种智能优化算法在无人机路径规划中的应用比较,突出了改进PSO在收敛速度和全局寻优方面的优势。; 适合人群:具备一定Matlab编程基础和优化算法知识的研究生、科研人员及从事无人机路径规划、智能优化算法研究的相关技术人员。; 使用场景及目标:①用于无人机在复杂地形或动态环境下的三维路径规划仿真研究;②比较不同智能优化算法(如PSO、GA、蚁群算法、RRT等)在路径规划中的性能差异;③为多目标优化问题提供算法选型和改进思路。; 阅读建议:建议读者结合文中提供的Matlab代码进行实践操作,重点关注算法的参数设置、适应度函数设计及路径约束处理方式,同时可参考文中提到的多种算法对比思路,拓展到其他智能优化算法的研究与改进中。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值