簡體   English   中英

如何編寫 Jpa 規范來連接兩個表?

[英]How to write a Jpa Specification to join two tables?

假設我有如下兩個實體:

@Data
@Entity
@Table(name = "reward")   
public class Reward{

  @Id
  @GeneratedValue(generator = "system-uuid")
  @GenericGenerator(name = "system-uuid", strategy = "org.hibernate.id.UUIDGenerator")
  @Column(length = 36)
  private String id;

  private String sn;

  //other fields

}


@Data
@Entity
@Table(name = "strategy_rewards")
public class RewardUserRelation{

  @Id
  @GeneratedValue(generator = "system-uuid")
  @GenericGenerator(name = "system-uuid", strategy = "org.hibernate.id.UUIDGenerator")
  @Column(length = 36)  
  private String id; 

  private String uid;

  private String rid; //reward id

  //other fields;    

}

我還編寫了一些其他規范,如下所示,以從 mysql 中過濾我的獎勵數據並將它們返回給其他服務:

public static Specification<Reward> withSn(String sn) {
    return (root, query, builder) -> builder
        .like(root.get("sn"), "%" +sn + "%");
  }

Page result = rewardRepository.findAll(where(sn == null ? null : 
    RewardSpecs.withSn(sn)), pageable));

但現在我想完成一個規范,可以過濾其 id 未出現在 RewardUserRelation Table 中的獎勵,這意味着這些獎勵未被使用。 我已經搜索了幾個規范教程,但仍然無法解決。 我應該使用 Join Criteria Api 嗎? 但我不知道該怎么做。 :(

更新:我設法通過提前從關系表中選擇所有 rid 並使用 Expression.in() 來解決這個問題,但仍然想知道是否有更好的方法來做到這一點。

List<String> idList =strategyRewardRelationRepository.getByDeleted(false).stream()
.map(StrategyRewardRelation::getRid).distinct().collect(Collectors.toList());

public static Specification<Reward> withUsed(Boolean used, List<String> idList) {
    return (root, query, builder) -> {
      return used ? root.get("id").in(idList) : root.get("id").in(idList).not();
    };
 }

Specification中的兩個連接可能是可行的方法:

case "propertyId":
                Join<SourceEntity, Item> itemJoin = root.join("item");
                Join<SourceEntity, ItemSourceDetail> itemDetailJoin = itemJoin.join("itemSourceDetail");
                try {
                    filterValue = criteria.getString(key).toString();
                    filters.add(itemDetailJoin.get("propertyId").in(Long.valueOf(filterValue)));
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                break;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM