【问题标题】:Type mismatch: number, date or string expected hibernate LocalDate类型不匹配:数字、日期或字符串预期休眠 LocalDate
【发布时间】:2020-09-18 22:50:11
【问题描述】:

任务:


数据库dates字段的类型为date

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

Entity: // 字段 "date" , type "LocalDate":

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

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

类 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>

添加:

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

在 sql 请求中:“从 Item i where i.date between ?1 and ?2”, i.date 字段以红色突出显示,表示 jpa 错误,需要使用 Date 类型:

如果我使用类型 Date 而不是 LocalDate 错误转义。但我需要LocalDate 类型。


如何解决?

ps。代码编译正确。代码实现并不重要。问题一:如何在不关闭检查的情况下排除错误。

【问题讨论】:

  • 你使用什么hibernate方言?
  • @SternK 嗨。 .PostgreSQL9方言
  • 您好 Mailtime,关于您在 elsehwere 中提出的问题:您知道您可以按年龄、投票和活动对问题的答案视图进行排序吗?这就是为什么例如“以上答案”通常是一个模棱两可的引用的原因。

标签: java hibernate jpa mismatch


【解决方案1】:

从您的pom.xml 中删除hibernate-java8 工件。它是deprecatedhibernate-core 就足够了。我已经测试了你的查询,它对我来说很好用 LocalDate

【讨论】:

  • 感谢您的帮助。已提出更改建议,但对我不起作用。
猜你喜欢
  • 2020-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多