【问题标题】:Spring Data. Hibernate. Restrict result in joined table when one to many relationship弹簧数据。休眠。一对多关系时限制连接表中的结果
【发布时间】:2017-02-05 06:29:20
【问题描述】:

我有 2 张桌子。 我想找到用户所做的最后一个操作,还可以添加作为此操作的参数最大日期发送的可能性

create table user(
 id int,
 name char(5)
);

create table action(
 id int,
 user_id int,
 action char(5),
 rep_date date
);

在sql里面会这样

select t1.*, t2* from user t1
left join action t2 on (t1.id = t2.user_id)
join (select t3.user_id, max(t3.rep_date) as max_date
from action t3
group by t3.user_id) t4 on (t2.user_id=t4.user_id and t2.rep_date=t4.max_date)

我在用户中创建实体类是有 @OneToMany 在列表中

在仓库中

 @Repository
    public interface StudyMatherialRepository extends CrudRepository<User, Long> {
        @Query(value="select distinct u from User u left join fetch sm.action a1 join (select a2.user_id, max(a2.rep_date) max_date from  sm.history a2
group by a2.user_id) a3 on (a1.user_id = a2.user_id and a1.rep_date= a2.max_date)
")
        public List<StudyMaterial> findAllwithNative();
    }

我明白了 org.hibernate.hql.internal.ast.QuerySyntaxException:意外令牌 并且想不出我该如何解决它。

【问题讨论】:

    标签: hibernate spring-data spring-data-jpa


    【解决方案1】:

    我相信通过来自UserAction 实体会更容易实现这一点,它可能与User@ManyToOne 关系,允许我们加入-获取它:

    SELECT a
    FROM UserAction a
    JOIN FETCH a.user u
    WHERE a.id IN (
      SELECT a_.id
        FROM UserAction a_
       GROUP BY a_.user
       HAVING MAX( a_.repDate )
    )
    

    【讨论】:

      猜你喜欢
      • 2012-02-17
      • 2018-07-22
      • 2015-03-11
      • 1970-01-01
      • 1970-01-01
      • 2014-02-14
      • 1970-01-01
      • 2016-11-04
      • 2016-09-24
      相关资源
      最近更新 更多