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

Spring Data中无法实例化DTO Projection问题求助

Spring Data Cassandra 返回自定义对象失败,框架尝试实例化主实体类

我尝试从Repository返回自定义对象RecordData,但框架总是试图实例化主类Record,哪怕用了Interface Projections也没用。


相关代码

Record实体类

import org.springframework.data.cassandra.core.mapping.PrimaryKey;
import org.springframework.data.cassandra.core.mapping.Table;

@Table
public class Record {

    public record RecordData(long created_at, double value) {

    }

    @PrimaryKey
    private final long sensor_id;

    private final long created_at;

    private final double value;

    public Record(long sensor_id, long created_at, double value) {
        this.sensor_id = sensor_id;
        this.created_at = created_at;
        this.value = value;
    }

    public long getSensorId() {
        return sensor_id;
    }

    public long getCreatedAt() {
        return created_at;
    }

    public double getValue() {
        return value;
    }

}

Repository接口

@Repository
public interface RecordsRepository extends CassandraRepository<Record, String> {

    @Query("SELECT created_at, value FROM record WHERE sensor_id = ?0 and created_at > ?1")
    List<Record.RecordData> findBySensorIdAndCreatedAt(Long sensorId, Long createdAt);

}

报错栈信息

org.springframework.data.mapping.model.MappingInstantiationException: Failed to instantiate com.example.mainservice.models.entities.Record using constructor public com.example.mainservice.models.entities.Record(long,long,double) with arguments null,300,0.0

Caused by: java.lang.IllegalArgumentException: Parameter sensor_id must not be null!

解决方案

1. 显式指定查询结果类型

Spring Data Cassandra默认会尝试将查询结果映射到Repository泛型中定义的实体类(即Record),导致因缺少sensor_id字段抛出异常。需要在@Query注解中添加resultType参数,明确指定要映射到的自定义对象:

@Repository
public interface RecordsRepository extends CassandraRepository<Record, Long> { // 修正主键类型为Long,匹配实体类的sensor_id类型

    @Query(value = "SELECT created_at, value FROM record WHERE sensor_id = ?0 and created_at > ?1",
           resultType = Record.RecordData.class)
    List<Record.RecordData> findBySensorIdAndCreatedAt(Long sensorId, Long createdAt);

}

2. 修正Repository泛型的主键类型

原代码中CassandraRepository<Record, String>的主键类型与实体类中sensor_id的long类型不匹配,这会导致潜在的类型错误,建议改为CassandraRepository<Record, Long>。

3. 确认字段名匹配

RecordData的参数名created_at和value与查询返回的列名完全一致,Spring Data会自动完成映射,无需额外配置。如果后续需要修改参数名,可在Record的字段上添加@Column注解,确保映射关系正确。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 04:40:45