简体   繁体   中英

Type mismatch: number, date or string expected hibernate LocalDate

Task:


The field dates has type date in the database .

create table items
(
    id   serial primary key,
    dates date
);

Entity : // field "date", type "LocalDate":

@Entity
@Table(name = "items")
public class Item {
    private LocalDate date;

    @Column(name = "dates")
    public LocalDate getDate() {
        return date;
    }
}

class UserStore:

class UserStore {
    private final SessionFactory factory = new Configuration()
            .configure().buildSessionFactory();

    public List<?> findByDate() {
        Session session = factory.openSession();
        session.beginTransaction();
        final String sql = "from Item i where i.date between ?1 and ?2";
        Query query = session.createQuery(sql, Item.class);
        query.setParameter(1, LocalDate.now());
        query.setParameter(2, LocalDate.now());
        List<?> result = query.getResultList();
        session.getTransaction().commit();
        session.close();
        return result;
    }
}

pom.xml

        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.12.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-java8 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-java8</artifactId>
            <version>5.4.17.Final</version>
        </dependency>

added:

 <property name="dialect">org.hibernate.dialect.PostgreSQL9Dialect</property>

in the sql request: "from Item i where i.date between?1 and?2", field i.date is highlighted in red, indicating a jpa error and requiring the use of the Date type:

看错

If i use type Date instead LocalDate mistake escape. But I need LocalDate type.


How to fix it?

ps. The code compiles correctly.code implementation is not important. question one: How to remove the error without turning off the inspection.

Remove the hibernate-java8 artifact from your pom.xml . It is deprecated . The hibernate-core will be enough. I have tested your query and it works fine for me with LocalDate .

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