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

Hibernate映射非实体类报错:Unknown entity: java.time.LocalDateTime

问题解决:原生SQL查询直接映射LocalDateTime集合

报错原因

你用createNativeQuery时传入的第二个参数LocalDateTime.class不符合要求——这个参数需要是带有@Entity注解的持久化实体类,而LocalDateTime不是Hibernate可识别的实体,因此抛出Unknown entity异常。

解决方案

不需要单独创建实体类,只需修改查询逻辑,指定查询目标字段并正确映射类型即可:

方法1:标量查询(推荐)

直接查询order_timestamp字段,通过addScalar显式指定字段类型,确保Hibernate正确转换为LocalDateTime:

public List<LocalDateTime> getGuest2MaintenanceOrderTime(long guestId, long maintenanceId) {
    return entityManager.createNativeQuery(
                    "SELECT order_timestamp FROM guest_2_maintenance where guest_id = ? and maintenance_id = ?")
            .setParameter(1, guestId)
            .setParameter(2, maintenanceId)
            .unwrap(org.hibernate.query.Query.class)
            .addScalar("order_timestamp", org.hibernate.type.descriptor.sql.TimestampType.INSTANCE)
            .getResultList();
}

方法2:简化自动转换(依赖版本支持)

如果你的Hibernate版本在5.2+(已支持Java 8时间API),可以省略显式类型指定,直接查询单个字段后转换结果:

public List<LocalDateTime> getGuest2MaintenanceOrderTime(long guestId, long maintenanceId) {
    @SuppressWarnings("unchecked")
    List<LocalDateTime> resultList = (List<LocalDateTime>) entityManager.createNativeQuery(
                    "SELECT order_timestamp FROM guest_2_maintenance where guest_id = ? and maintenance_id = ?")
            .setParameter(1, guestId)
            .setParameter(2, maintenanceId)
            .getResultList();
    return resultList;
}

关键说明

  • 原代码中SELECT *会返回整行数据,无法直接映射到单个LocalDateTime类型,必须改为查询单个目标字段order_timestamp。
  • 当查询单个非实体字段时,Hibernate会自动处理JDBC类型与Java类型的转换(前提是版本兼容),显式使用addScalar可以避免类型转换歧义,提升代码稳定性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 08:54:21