You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vaadin+Spring+MySQL环境下LocalDate属性更新类型不匹配问题

解决方案:JPA更新LocalDate字段类型不匹配问题

问题根源

你的实体类expiryDate是java.time.LocalDate类型,但服务层手动转成java.sql.Date传给DAO,而JPA(Hibernate 5.2+)原生支持Java 8日期API,不需要这种转换,反而会导致参数类型和实体属性不匹配,触发异常。另外更新操作需要事务支持,否则也可能执行失败。

修复步骤

  1. 修改服务层,直接传递LocalDate
    去掉不必要的java.sql.Date转换,直接把LocalDate参数传给DAO,同时给方法加上事务注解:

    import java.time.LocalDate;
    import org.springframework.transaction.annotation.Transactional;
    
    @Service
    public class EnterpriseService {
        private final EnterpriseDao enterpriseDao;
    
        public EnterpriseService(EnterpriseDao enterpriseDao) {
            this.enterpriseDao = enterpriseDao;
        }
    
        @Transactional
        public void updateExpiryDate(int enterpriseId, LocalDate newExpiryDate) {
            enterpriseDao.updateExpiryDate(enterpriseId, newExpiryDate);
        }
    }
    
  2. 修正DAO层参数类型为LocalDate
    确保DAO的方法参数和实体属性类型一致,同时@Modifying注解必须配合事务注解使用:

    import java.time.LocalDate;
    import org.springframework.data.jpa.repository.Modifying;
    import org.springframework.data.jpa.repository.Query;
    import org.springframework.data.jpa.repository.CrudRepository;
    import org.springframework.data.repository.query.Param;
    import org.springframework.transaction.annotation.Transactional;
    
    public interface EnterpriseDao extends CrudRepository<Enterprise, Integer> {
    
        @Modifying
        @Transactional
        @Query("update Enterprise e set e.expiryDate = :expiryDate where e.enterpriseId = :enterpriseId")
        void updateExpiryDate(@Param("enterpriseId") int enterpriseId, @Param("expiryDate") LocalDate expiryDate);
    }
    
  3. 调用代码保持不变
    原调用逻辑无需修改:

    enterpriseService.updateExpiryDate(enterpriseX.getEnterpriseId(), LocalDate.of(2022, 12, 12));
    

补充说明

  • JPA 2.2及以上版本已经完全支持java.time.LocalDate、LocalDateTime等类型,会自动映射到数据库的DATE、DATETIME类型,不需要手动转换为java.sql包下的日期类。
  • 执行更新/删除的JPQL语句时,必须同时添加@Modifying和@Transactional注解,否则会抛出操作无效的异常。

内容的提问来源于stack exchange,提问作者Kiemoon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 06:01:27