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 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)pluralAttr);
TypedQuery typedQuery = entityManager.createQuery(criteriaQuery.select(join));
return (List
)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 permissions = new HashSet();
...
}

我使用每类表继承策略,这就是为什么您在生成的User和Group实体查询中看到并集的原因。他们扩展了角色。 ID在角色中定义。