我嘗試爲名稱爲User
的類建立findAll
查詢。使用休眠的SessionFactory
它工作正常,但與休眠的EntityManager
我得到一個錯誤。JPA查詢名稱爲Hibernate的用戶表
的原因似乎是escaping(用方括號[
和]
)的MS SQL Server的關鍵字user
的,但EntityManager#persist(Object)
和EntityManager#find(Class, Object)
我沒有問題。
堆棧跟蹤:
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: [ near line 1, column 29 [select generatedAlias0 from [user] as generatedAlias0]
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:91)
at org.hibernate.hql.internal.ast.ErrorCounter.throwQueryException(ErrorCounter.java:109)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:304)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:203)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:131)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:93)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:167)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1836)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:568)
... 103 more
代碼:
@Entity(name = "[user]")
public class User {
// some properties
}
public class UserDao
@PersistenceContext
private EntityManager entityManager;
public List<User> findAll() {
CriteriaQuery<User> criteriaQuery = entityManager.getCriteriaBuilder().createQuery(User.class);
Root<User> root = criteriaQuery.from(User.class);
criteriaQuery.select(root);
return entityManager.createQuery(criteriaQuery).getResultList();
}
}
研究:
這些解決方案都不能正常工作了。有沒有辦法在Hibernate的JPA查詢中使用表名[user]
?