繁体   English   中英

如何使用 Hibernate 和 ManyToOne 映射从连接两个表的条​​件中获取数据?

[英]How to fetch data from joining two tables with condition on both tables using Hibernate with ManyToOne mapping?

我有两个表:

@Entity
@Table(name = "subs")
public class Subs {

    @Column(name = "cin_id")
    private Long cinId;
    @ManyToOne(
      fetch = FetchType.LAZY,
      cascade = {CascadeType.ALL}
    )
    @JoinColumn(
      name = "cinId",
      insertable = false,
      updatable = false
    )

    @NotNull
    @NotBlank
    @Column(
      name = "status"
    )
    private String status;


    @NotNull
    @NotBlank
    @Column(
      name = "mode"
    )
    private String mode;

}

第二张表:

@Entity
@Table(name = "cin")
public class Cin {
    
        @Id
        @Column(
          name = "cinId"
        )

        private Long id;
        @OneToMany(
          fetch = FetchType.LAZY,
          mappedBy = "cinId"
        )
        private List<Subs> subs;

        @Column(
          name = "is_eligible"
        )
        private Boolean isEligible;

        @Column(
          name = "is_fix"
        )
        private Boolean is_fix;
        
    
}

我想在休眠中编写一个 DAO 服务来从 CIN 表中获取行,其中应该根据 where 子句获取 subs 表中的状态和模式值以及 Cin 表中的 is_eligible 和 is_fix 值的结果。

基本上 Hibernate 相当于下面的查询:

select 
    cin.id, 
from subs
inner join cin
ON subs.cinId=cin.cinId
where (subs.mode = 'something' and subs.status ='something')
and  cin.isEligible = true and cin.isFix = false 

我知道使用 Query.setParameters 来做到这一点,但如果我们想在两个具有多对一关系的连接表上应用条件,我不确定如何做到这一点。

from Cin c
where (c.subs.mode = :param1 and c.subs.status = :param2)
and  c.isEligible = true and c.isFix = false 

应该为你工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM