Hibernate, MySQL and table named “Repeat” - strange behaviour

前端 未结 2 1602
孤城傲影
孤城傲影 2020-12-10 22:47

I am having a strange problem. But first the orm.xml:


    

        
                      
相关标签:
2条回答
  • 2020-12-10 23:15

    Yes, repeat is a reserved word in MySQL

    http://dev.mysql.com/doc/refman/5.7/en/keywords.html

    0 讨论(0)
  • 2020-12-10 23:31

    The SQL Reserved Words Checker tells me that "repeat" is a reserved SQL keyword with MySQL (and DB2) so you need to escape it.

    JPA 1.0 doesn't define a standard way to handle that so you'll have to use Hibernate solution which relies on backticks. From the Hibernate Reference Guide:

    5.4. SQL quoted identifiers

    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.

    <class name="LineItem" table="`Line Item`">
        <id name="id" column="`Item Id`"/><generator class="assigned"/></id>
        <property name="itemNumber" column="`Item #`"/>
        ...
    </class>
    

    I assume this would work in orm.xml too.

    JPA 2.0 went further and defined a way to specify delimited identifiers:

    2.13 Naming of Database Objects

    ...

    To specify delimited identifiers, one of the following approaches must be used:

    • It is possible to specify that all database identifiers in use for a persistence unit be treated as delimited identifiers by specifying the <delimited-identifiers/> element within the persistence-unit-defaults element of the object/relational xml mapping file. If the <delimited-identifiers/> element is specified, it cannot be overridden.
    • It is possible to specify on a per-name basis that a name for a database object is to be interpreted as a delimited identifier as follows:
      • 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\"").
      • When using XML, a name is specified as a delimited identifier by use of double quotes, e.g., <table name="&quot;customer&quot;"/>

    If you are using JPA 2.0, I'd recommend to use the portable solution.

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