我想將此 sql 查詢轉換為 JPA 查詢,但我似乎無法理解...我應該使用 findByMarinaIdAndMovementGroupMeanId 嗎?或 findByMarinaIdAndMovementGroupMeanIdAndMovementMeanId??
資料:
select m.* from movement_group m
join movement_group_mean mgm on m.id = mgm.movement_group_id
join movement_mean mm on mgm.movement_mean_id = mm.id
where mm.id = 1 and m.marina_id = :marinaId and mm.active = true;
運動組:
@Entity
public class MovementGroup {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String code;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
private Boolean active;
private String iconUrl;
@OneToMany(mappedBy = "movementGroup")
private Set<MovementGroupMean> movementGroupMeans;
@JsonIgnore
@ManyToOne()
@JoinColumn(name = "marina_id")
private Marina marina;
運動組平均值:
@Entity
public class MovementGroupMean {
@EmbeddedId
@JsonIgnore
private MovementGroupMeanPK movementGroupMeanPK;
@JsonBackReference
@ManyToOne
@JoinColumn(name = "movement_group_id", insertable = false, updatable = false)
private MovementGroup movementGroup;
@ManyToOne
@JoinColumn(name = "movement_mean_id", insertable = false, updatable = false)
private MovementMean movementMean;
運動平均值:
@Entity
public class MovementMean {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@Enumerated(EnumType.STRING)
private MovementMeanType movementMeanType;
private Boolean active;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
@JsonBackReference
@ManyToOne()
@JoinColumn(name = "marina_id")
private Marina marina;
uj5u.com熱心網友回復:
不確定問題出在哪里,所以請原諒關于 SQL->JPQL 的冗長解釋:
用您的物體名稱替換您的表名稱
- 運動組->運動組
將您的連接替換為 java 參考,讓 JPA 使用您定義的關系映射。
- “在 m.id = mgm.movement_group_id 上加入 motion_group_mean mgm”變為“加入 m.movementGroupMeans mgm”
- “在 mgm.movement_mean_id = mm.id 上加入 motion_mean mm = mm.id 變為“加入 mgm.movementMean mm”
唯一棘手的地方是您的物體沒有為 marina_id 值定義基本映射。因此,要獲取 m.marina_id,您必須使用“marina”參考并使用其大概的 ID 值:“m.marina_id = :marinaId”->“m.marina.id = :marinaId”
給你JPQL:
"Select m from MovementGroup m join m.movementGroupMeans mgm join mgm.movementMean mm where mm.id = 1 and m.marina.id = :marinaId and mm.active = true"
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/454159.html
下一篇:FK指向各種表的JPA建模
