How to map an entity field whose name is a reserved word in JPA

前端 未结 7 1568
陌清茗
陌清茗 2020-11-22 12:35
@Column(name=\"open\")

Using sqlserver dialect with hibernate.

[SchemaUpdate] Unsuccessful: create table auth_session (id numeric(1         


        
相关标签:
7条回答
  • 2020-11-22 12:45
    @Column(name="\"open\"")
    

    This will work for sure, Same problem happened with me, when I was learning hibernate.

    0 讨论(0)
  • 2020-11-22 12:50

    Some JPA implementations (e.g the one I use, DataNucleus) automatically quote the identifier for you, so you never get this.

    0 讨论(0)
  • 2020-11-22 12:56

    No - change the column name.

    This is database-specific, and you just can't create such a column. After all hibernate finally sends DDL to the database. If you can't create a valid DDL with this column name, this means hibernate can't as well. I don't think quoting would solve the issue even if you are writing the DDL.

    Even if you somehow succeed to escape the name - change it. It will work with this database, but won't work with another.

    0 讨论(0)
  • 2020-11-22 13:02

    If you use as shown below it should work

    @Column(name="[order]")
    private int order;
    
    0 讨论(0)
  • 2020-11-22 13:03

    Manually escaping the reserved keywords

    If you are using JPA, you can escape with double quotes:

    @Column(name = "\"open\"")
    

    If you're using Hibernate native API, then you can escape them using backticks:

    @Column(name = "`open`")
    

    Automatically escaping reserved keywords

    If you want to automatically escape reserved keywords, you can set to true the Hibernate-specific hibernate.globally_quoted_identifiers configuration property:

    <property
        name="hibernate.globally_quoted_identifiers"
        value="true"
    />
    

    Yaml format

    spring:
      jpa:
        properties:
          hibernate:
            globally_quoted_identifiers: true
    

    For more details, check out this article.

    0 讨论(0)
  • 2020-11-22 13:08

    Had the same problem, but with a tablename called Transaction. If you set

    hibernate.globally_quoted_identifiers=true
    

    Then all database identifiers will be quoted.

    Found my answer here Special character in table name hibernate giving error

    And found all available settings here https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/appendices/Configurations.html

    Could not find better docs for this though.

    In my case the setting was in my Spring properties file. As mentioned in the comments, it could also be in other, hibernate related, configuration files.

    0 讨论(0)
提交回复
热议问题