java - Hibernate实体只有一列,没有名字

标签 java hibernate jpa hql hsqldb

我想映射一列,而不使用列名。

我正在使用计数实体,并且想对同一实体使用多个不同的查询:

@Entity
public class CountDTO extends Number {

    @Id
    // below causes an error in my test, hsql not same syntax
    @Column(name = 'COUNT') 
    private Long count;

在我的 prod (oracle) 数据库中,我可以执行 select count() as COUNT from ...但是,使用 hypersql 内存数据库时,相同的语法不起作用?

他们是在 HQL 中映射单个列别名的 oracle/hsql 兼容方式吗?

最佳答案

您的问题是 COUNTreserved keyword for HSQL , 但是 not for Oracle .

根据 HSQL 文档,可能仍然可以使用 COUNT作为标识符,如果你要么

  • 按照 Hibernate documentation 中的描述屏蔽它或在 JPA 规范中(参见 JPA 2 spec 的第 2.13 章;您需要接受他们的许可协议(protocol))。请注意,JPA 规范提到了双引号,而 Hibernate 文档提到了反引号(将根据使用的数据库方言将其转换为适当的字符)。

    来自 hibernate 文档:

    You can force Hibernate to quote an identifier in the generated SQL by enclosing the table or column name in backticks in the mapping document. Hibernate will use the correct quotation style for the SQL Dialect. This is usually double quotes, but the SQL Server uses brackets and MySQL uses backticks.

    来自 JPA 2 规范:

    Using annotations, a name is specified as a delimited identifier by enclosing the name within double quotes, whereby the inner quotes are escaped, e.g., @Table(name="\"customer\"").

  • 通过执行 SET DATABASE SQL NAMES FALSE 配置 HSQL 以允许它(然而,这应该已经是默认设置,它只允许“使用大多数关键字”,而不是全部 - 编辑:COUNT 根据文档仍将被禁止)

我的建议是尽可能避免使用标识符,因为您永远不知道其他地方可能会出现什么问题(例如,有人可能认为 Hibernate 本身能够屏蔽关键字)并使用类似 COUNT1 的标识符。而不是列名。

JPA 规范的上述部分还解释了为什么 Hibernate 不屏蔽名称本身:

By default, the names of database objects must be treated as undelimited identifiers and passed to the database as such.

JPA 规范还提到了一个 <delimited-identifiers/>选项“指定所有用于持久性单元的数据库标识符被视为 定界标识符”,但这似乎只能用于 XML 映射文件。

关于java - Hibernate实体只有一列,没有名字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31247046/

相关文章:

java - Volley 不从 https 服务器检索图像

java - GAE 中的同步块(synchronized block)

java - HSEARCH000151 : Unable to get input stream from object of type byte

java - 如何将值或参数从jsp传递到Spring Controller ?

Java:Selenium 将文本发送到错误的字段

java - hibernate 以及如何避免模式名称更改

hibernate - org.hibernate.QueryException : not an association

java - 生成 JPA 动态类型化查询的最佳实践?

java - 使用 JPA/QueryDSL 的类似数据透视的结果

java - 如何使用 SqlResultSetMapping 将 JPA NativeQuery 的结果集映射到 POJO