代码之家  ›  专栏  ›  技术社区  ›  Roshana Pitigala Laxmansinghsodhanohdiyala

在hibernate中将“backticks”添加到列名

  •  0
  • Roshana Pitigala Laxmansinghsodhanohdiyala  · 技术社区  · 6 年前

    考虑这个问题

    INSERT INTO order (id, key, value) VALUES (?, ?, ?);
    

    上面的查询中有mysql语法错误 order key 是mysql中的关键字。所以解决方法是在查询中添加反勾号。

    INSERT INTO `order` (id, `key`, value) VALUES (?, ?, ?);
    

    Hibernate太蠢了,不能自动这么做。根据 this answer 通过将以下属性添加到hibernate配置文件中,可以解决表名问题。

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

    但这只会在数据库名和表名中添加反勾号。列名仍然有问题。

    如何向所有列名添加子查询?


    • Hibernate版本:3.6.10.final
    • MySQL版本:5.7
    • hibernate.dialect:org.hibernate.dialect.mysql5方言
    • JDK版本:1.8(如果这与什么有关的话)
    1 回复  |  直到 6 年前
        1
  •  0
  •   Roshana Pitigala Laxmansinghsodhanohdiyala    6 年前

    我找到了一种在hibernate中向列名添加backticks的方法。

    1. 打开相对于已映射的POJO文件的XML文件(tablename.hbm.xml)。
    2. 查找相对列的属性。

      <property name="key" type="string">
          <column name="key" />
      </property>
      
    3. 用方括号将列名括起来。

      <property name="key" type="string">
          <column name="[key]" />
      </property>
      

    但这是一个艰苦的过程,因为您必须对所有列逐个执行此操作 MySQL keywords . 最好的方法是避免 mysql关键字 作为数据库、表或列名。

    参考文献: