我有以下情况:
我正在开发一个使用Hibernate的应用程序,我正在尝试创建一个 HQL 查询,该查询提取具有某些特定条件的随机记录。
所以我有这些实体类:
1)我有这个 Room 实体类,代表住宿的房间:
@Entity
@Table(name = "room")
public class Room implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@ManyToOne
@JoinColumn(name = "id_accomodation_fk", nullable = false)
private Accomodation accomodation;
@ManyToOne
@JoinColumn(name = "id_room_tipology_fk", nullable = false)
private RoomTipology roomTipology;
@OneToMany(mappedBy = "room")
private List<RoomMedia> roomMediaList;
@Column(name = "room_number")
private String number;
@Column(name = "room_name")
private String name;
@Column(name = "room_description")
private String description;
@Column(name = "is_enabled")
private Boolean isEnabled;
........................................................................
........................................................................
GETTER AND SETTER METHODS
........................................................................
........................................................................
}
2)然后我有这个 RoomMedia 实体类,它代表与特定房间实体相关的照片:
@Entity
@Table(name = "room_media")
public class RoomMedia {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "id_room")
private Long idRoom;
@ManyToOne
@JoinColumn(name = "id_room", nullable = false) // da rinominare anche sul DB in room_fk
private Room room;
@Lob
@Column(name = "media")
private byte[] media;
private String description;
........................................................................
........................................................................
GETTER AND SETTER METHODS
........................................................................
........................................................................
}
正如您在前面的代码中所看到的,这些表链接到了gheter。
好的,现在我正在尝试创建一个 HQL 查询,该查询返回由属于特定房间提示的 RoomMedia 实体类映射的2个随机记录表,这是 Room 实体类的特定字段,这一个:
@ManyToOne
@JoinColumn(name = "id_room_tipology_fk", nullable = false)
private RoomTipology roomTipology;
所以,在线搜索我发现了这个有趣的帖子:MySQL select 10 random rows from 600K rows fast
引用本文:http://jan.kneschke.de/projects/mysql/order-by-rand/
这是一个纯SQL解决方案,我需要将其转换为适合我的实体的SQL
所以我选择实施建议的解决方案(在SO帖子上提出的解决方案,因为我可以拥有&#34;漏洞&#34;),我已经在我的DAO中实现了这个 HQL 查询类:
@Repository
@Transactional(propagation = Propagation.MANDATORY)
public interface RoomMediaDAO extends JpaRepository<RoomMedia, Long> {
@Query( "FROM RoomMedia as rm1 JOIN " +
"(SELECT (RAND() * (SELECT MAX(id) FROM RoomMedia)) AS id) AS rm2 " +
"WHERE rm1.id >= rm2.id AND rm1.roomTipology.id = :roomTipologyId " +
"ORDER BY rm1.id ASC " +
"LIMIT 2")
List<RoomMedia> getRandomRoomMediaOfACategory(@Param(value = "roomTipologyId") Long roomTipologyId);
}
正如您所见,我试图在我的 RoomMedia 实体上回溯相同的推理
它没有用,在应用程序启动时我收到此错误消息:
Caused by: java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.betrivius.dao.RoomMediaDAO.getRandomRoomMediaOfACategory(java.lang.Long)!
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:92)
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.<init>(SimpleJpaQuery.java:62)
at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromMethodWithQueryString(JpaQueryFactory.java:72)
at org.springframework.data.jpa.repository.query.JpaQueryFactory.fromQueryAnnotation(JpaQueryFactory.java:53)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$DeclaredQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:144)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:212)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:77)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:435)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:220)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:266)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:252)
at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:92)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1642)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1579)
... 39 more
Caused by: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 49 [FROM com.betrivius.domain.RoomMedia as rm1 JOIN (SELECT (RAND() * (SELECT MAX(id) FROM RoomMedia)) AS id) AS rm2 WHERE rm1.id >= rm2.id AND rm1.roomTipology.id = :roomTipologyId ORDER BY rm1.id ASC LIMIT 2]
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1750)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1677)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1683)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:331)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:347)
at com.sun.proxy.$Proxy107.createQuery(Unknown Source)
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:86)
... 52 more
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 49 [FROM com.betrivius.domain.RoomMedia as rm1 JOIN (SELECT (RAND() * (SELECT MAX(id) FROM RoomMedia)) AS id) AS rm2 WHERE rm1.id >= rm2.id AND rm1.roomTipology.id = :roomTipologyId ORDER BY rm1.id ASC LIMIT 2]
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:328)
... 59 more
为什么呢?问题是什么?如何修复它将其转换为工作HQL查询的工具?
答案 0 :(得分:1)
您的子查询发生在JOIN子句中:
"FROM RoomMedia as rm1 JOIN " +
"(SELECT (RAND() * (SELECT MAX(id) FROM RoomMedia)) AS id) AS rm2 "
但你不能因为 Hibernate documentation州:
请注意,HQL子查询只能在select或where中出现 条款。
由JOIN子句后的意外(
字符引起的异常:
引起:org.hibernate.hql.internal.ast.QuerySyntaxException: 意外的令牌:(
1)在您的情况下,另一种合适的解决方案是使用Hibernate创建和执行本机SQL查询。
您可以通过使用实体管理器以这种方式重用原始SQL查询(我建议您使用标准):
String sqlQuery = " SELECT rm1 FROM room_media as rm1 JOIN room_media on... " );
List<RoomMedia> roomMediat= (List<RoomMedia>)em.createQuery(sqlQuery)
.getResultList();
未经测试,但您有这个想法。
2)否则,另一种方法是修改查询以将子查询放在WHERE子句中。