Home > Software engineering >  Hibernate mapping non-entity classes. org.hibernate.MappingException: Unknown entity: java.time.Loca
Hibernate mapping non-entity classes. org.hibernate.MappingException: Unknown entity: java.time.Loca

Time:07-28

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

    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

CodePudding user response:

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;
}

CodePudding user response:

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

  • Related