如何强制 Hibernate 在生成的 SQL 语句中添加引号?

发布于 2024-09-29 20:43:00 字数 3642 浏览 4 评论 0原文

Hibernate 正在为特定条件查询生成无效的 SQL。我可以通过向 WHERE 子句中使用的值添​​加单引号来手动修复查询。

为了解决这个问题,我将查询从:更改

where (role0_.ROLE_ID=2L )

为:

where (role0_.ROLE_ID=`2L` )

如何强制hibernate添加单引号(在mysql中它是单引号,但在其他数据库系统中它可能是其他东西)以包含使用的在生成的 SQL 查询中?

完整生成的查询是:

select permission1_.PERMISSION_ID as PERMISSION1_12_,
    permission1_.IS_REQUIRED as IS2_12_,
    permission1_.SOURCE_ROLE_ID as SOURCE3_12_,
    permission1_.TARGET_ROLE_ID as TARGET4_12_
from (
        select ROLE_ID,
        NAME,
        DESCRIPTION,
        IS_ACTION,
        LABEL,
        null as FIRST_NAME,
        null as LAST_NAME,
        null as PASSWORD_HASH,
        1 as clazz_ from GROUPS
    union
        select ROLE_ID,
            NAME,
            null as DESCRIPTION,
            null as IS_ACTION,
            null as LABEL,
            FIRST_NAME,
            LAST_NAME,
            PASSWORD_HASH,
            2 as clazz_ from USERS
    )
role0_ inner join PERMISSIONS permission1_ on role0_.ROLE_ID=permission1_.SOURCE_ROLE_ID
    where (role0_.ROLE_ID=2L )

基本上我希望 Hibernate 添加这个单引号。

生成此查询的条件查询是:

EntityManager entityManager = getEntityManager();
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery();

Class<?> queryScopeClass = temp.pack.commons.user.Role.class;
Root<?> from = criteriaQuery.from(queryScopeClass);

Path<?> idAttrPath = from.get("id");
// also tried criteriaBuilder.equal(idAttrPath, new Long(2))
Predicate predicate = criteriaBuilder.equal(idAttrPath, criteriaBuilder.literal(new Long(2)))
criteriaQuery.where(predicate);

Path<?> attributePath = from.get("permissions");
PluralAttributePath<?> pluralAttrPath = (PluralAttributePath<?>)attributePath;
PluralAttribute<?, ?, ?> pluralAttr = pluralAttrPath.getAttribute();

Join<?, ?> join = from.join((SetAttribute<Object,?>)pluralAttr);

TypedQuery<Object> typedQuery = entityManager.createQuery(criteriaQuery.select(join));
return (List<P>)typedQuery.getResultList();

如果您有任何有关如何强制 Hibernate 将这些单引号添加到值(而不是列/表名称)的线索,请告诉我。

当然,在我的实体 Role 中,WHERE 子句中出现的 id 属性是 long 类型。

后续:数据库中id列的类型是bingint:

+---------------+--------------+------+-----+---------+-------+
| Field         | Type         | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+-------+
| ROLE_ID       | bigint(20)   | NO   | PRI | NULL    |       |

...

这就是Role类的注释方式:

@Entity(name="Role")
@Table(name = "ROLES")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@javax.persistence.TableGenerator(
    name="GENERATED_IDS",
    table="GENERATED_IDS",
    valueColumnName = "ID"
)
public abstract class Role implements Serializable {
    private static final long serialVersionUID = 1L;


    /**
     * The id of this role. Internal use only.
     * 
     * @since 1.0
     */
    @Id @GeneratedValue(strategy = GenerationType.TABLE, generator="GENERATED_IDS")
    @Column(name = "ROLE_ID")
    protected long id;


    /**
     * Set of permissions granted to this role.
     * 
     * @since 1.0
     */
    @OneToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy="sourceRole")
    protected Set<Permission> permissions = new HashSet<Permission>();

...

}

我使用每类表继承策略,这就是为什么你在生成的查询中看到联合的原因对于用户和组实体。他们扩展了角色。 Id 在角色中定义。

谢谢你!

爱德华多

Hibernate is generating invalid SQL for a particular criteria query. I can manually fix the query by adding single quotes to the value being used in the WHERE clause.

To fix it, I changed the query from:

where (role0_.ROLE_ID=2L )

to:

where (role0_.ROLE_ID=`2L` )

How to force hibernate to add single quotes (in mysql it is single quotes but in other database systems it might be something else) to enclose the values used in generated SQL queries?

The full generated query is:

select permission1_.PERMISSION_ID as PERMISSION1_12_,
    permission1_.IS_REQUIRED as IS2_12_,
    permission1_.SOURCE_ROLE_ID as SOURCE3_12_,
    permission1_.TARGET_ROLE_ID as TARGET4_12_
from (
        select ROLE_ID,
        NAME,
        DESCRIPTION,
        IS_ACTION,
        LABEL,
        null as FIRST_NAME,
        null as LAST_NAME,
        null as PASSWORD_HASH,
        1 as clazz_ from GROUPS
    union
        select ROLE_ID,
            NAME,
            null as DESCRIPTION,
            null as IS_ACTION,
            null as LABEL,
            FIRST_NAME,
            LAST_NAME,
            PASSWORD_HASH,
            2 as clazz_ from USERS
    )
role0_ inner join PERMISSIONS permission1_ on role0_.ROLE_ID=permission1_.SOURCE_ROLE_ID
    where (role0_.ROLE_ID=2L )

Basically I'd like this single quotes to be added by Hibernate.

The criteria query that generated this query is:

EntityManager entityManager = getEntityManager();
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery();

Class<?> queryScopeClass = temp.pack.commons.user.Role.class;
Root<?> from = criteriaQuery.from(queryScopeClass);

Path<?> idAttrPath = from.get("id");
// also tried criteriaBuilder.equal(idAttrPath, new Long(2))
Predicate predicate = criteriaBuilder.equal(idAttrPath, criteriaBuilder.literal(new Long(2)))
criteriaQuery.where(predicate);

Path<?> attributePath = from.get("permissions");
PluralAttributePath<?> pluralAttrPath = (PluralAttributePath<?>)attributePath;
PluralAttribute<?, ?, ?> pluralAttr = pluralAttrPath.getAttribute();

Join<?, ?> join = from.join((SetAttribute<Object,?>)pluralAttr);

TypedQuery<Object> typedQuery = entityManager.createQuery(criteriaQuery.select(join));
return (List<P>)typedQuery.getResultList();

Please let me know if you have any clues on how to force Hibernate to add those single quotes to the values (not the column/table name).

In my entity Role, the id property that appears in the WHERE clause is of long type, of course.

Follow up: The type of the id column in the database is bingint:

+---------------+--------------+------+-----+---------+-------+
| Field         | Type         | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+-------+
| ROLE_ID       | bigint(20)   | NO   | PRI | NULL    |       |

...

This is how the Role class has been annotated:

@Entity(name="Role")
@Table(name = "ROLES")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@javax.persistence.TableGenerator(
    name="GENERATED_IDS",
    table="GENERATED_IDS",
    valueColumnName = "ID"
)
public abstract class Role implements Serializable {
    private static final long serialVersionUID = 1L;


    /**
     * The id of this role. Internal use only.
     * 
     * @since 1.0
     */
    @Id @GeneratedValue(strategy = GenerationType.TABLE, generator="GENERATED_IDS")
    @Column(name = "ROLE_ID")
    protected long id;


    /**
     * Set of permissions granted to this role.
     * 
     * @since 1.0
     */
    @OneToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy="sourceRole")
    protected Set<Permission> permissions = new HashSet<Permission>();

...

}

I use table per class inheritance strategy, that's why you see the union in the generated query for User and Group entities. They extend Role. Id is defined in Role.

Thank you!

Eduardo

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

陪你搞怪i 2024-10-06 20:43:00

hibernate 属性 hibernate.globally_quoted_identifiers=true 就可以解决问题

The hibernate property hibernate.globally_quoted_identifiers=true will do the trick

深陷 2024-10-06 20:43:00

将您的 id 更改为 Long 类类型而不是原始类型。然后 Hibernate 将简单地生成 ROLE_ID=2 的查询,这是 100% 有效的,因为数字不需要刻度或引号。

Change your id to the Long class type instead of a primitive. Hibernate will then simply generate the query to be ROLE_ID=2, which is 100% valid since numbers don't require ticks or quotes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文