【发布时间】:2021-03-30 17:02:00
【问题描述】:
考虑下表:
表A
| id | sys_time | user_id | rent_time |
|---|
表 B
| id | sys_time | occur_time |
|---|
我想在 MYSQL 中使用 UNION 查询来创建这个表,并使用 sys_time 顺序将两个表中的数据逐行放入:
表 AB
| id | sys_time | user_id | occur_time | rent_time |
|---|
我使用以下查询:
select id, sys_time, user_id, null as occur_time, rent_time from open_close
union
select id, sys_time, null as user_id, occur_time, null as rent_time from periodic
order by sys_time desc;
现在我定义了一个具有以下结构的@Entity:
...
@Data
@Entity
@NamedNativeQuery(
name="TotalEntity.getTotal"
, query="select id, sys_time, user_id, null as occur_time, rent_time from open_close\r\n"
+ "union\r\n"
+ "select id, sys_time, null as user_id, occur_time, null as rent_time from periodic \r\n" + "order by sys_time desc;"
, resultClass=TotalEntity.class
)
...
// Entity Fields and so on
以及对应的Repository:
@Repository
public interface TotalRepository extends JpaRepository<TotalEntity, BigInteger> {
@Query(nativeQuery = true)
public List<TotalEntity> getTotal();
}
到目前为止一切正常。
现在我要添加分页:
@Repository
public interface TotalRepository extends JpaRepository<TotalEntity, BigInteger> {
@Query(nativeQuery = true)
public Page<TotalEntity> getTotal(Pageable page);
}
并使用它:
...
private TotalRepository tr;
...
Pageable pageable = PageRequest.of(page, size,
direction.toUpperCase().equals("ASC") ? Sort.by(sort).ascending() : Sort.by(sort).descending());
Optional<Page<TotalEntity>> pe = Optional.ofNullable(tr.getTotal(pageable));
抛出以下异常:
java.sql.SQLSyntaxErrorException:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 4 行的“limit 20”附近使用正确的语法
好像Hibernate不能修改nativeQuery添加分页语句。而且我知道 JPQL 和 JPA 不支持 UNION。有什么解决方法吗?
【问题讨论】:
-
这能回答你的问题吗? Spring Data and Native Query with pagination
-
@NikolaiShevchenko 我对分页本身没有问题,工会正在制造一些问题。
-
作为一个小的解决方法,您可以使用“选择联合部分”定义数据库视图并在视图上执行查询。
-
@lzagkaretos 好主意。有效。谢谢!您可以将此作为答案提交。我想。
标签: spring-boot hibernate jpa