简体   繁体   中英

Hibernate mapping non-entity classes. org.hibernate.MappingException: Unknown entity: java.time.LocalDateTime

I have a table [order_id, guest_id, maintenance_id, order_timestamp] , and I want to select list of timestamps , when the guest_id ordered maintenance_id .

I simply tried to select LocalDateTime with the code below, but hibernate threw: Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.MappingException: Unknown entity: java.time.LocalDateTime Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.MappingException: Unknown entity: java.time.LocalDateTime

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

It seems strange to me to create separate class for holding date, and annotate it with @Entity . How to select LocalDateTime and map it to a new LocalDateTime object?

Mapping LocalDateTime as field of @Entity object works fine, but in my case this table field does not belong to any @Entity

Your mistake is that you do 'select *...' There are two ways to solve your problem:

  1. Select only time field

     List<LocalDateTime> resultList = entityManager.createNativeQuery( "SELECT order_timestamp FROM guest_2_maintenance where guest_id =? and maintenance_id =?", LocalDateTime.class).setParameter(1, guestId).setParameter(2, maintenanceId).getResultList(); return resultList; }
  2. Or you should use an entity and then retrieve order_timestamp field from it. For example

Thanks to @akortex and @Human Bean for responsing but I managed to make it works somehow this way:

public List<LocalDateTime> getGuest2MaintenanceOrderTime(long guestId, long maintenanceId) {
    List<Timestamp> resultList = entityManager.createNativeQuery(
                    "SELECT order_timestamp FROM guest_2_maintenance where guest_id = ? and maintenance_id = ?")
            .setParameter(1, guestId)
            .setParameter(2, maintenanceId)
            .getResultList();
    List<LocalDateTime> localDateTimeList = new ArrayList<>();
    resultList.forEach(timestamp -> {
        localDateTimeList.add(timestamp.toLocalDateTime());
    });
    return localDateTimeList;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM