【问题标题】:How do I query using JPA to get list of entities which do not contain a FK entity as its member?如何使用 JPA 查询以获取不包含 FK 实体作为其成员的实体列表?
【发布时间】:2015-12-08 06:27:47
【问题描述】:

我有一个Promotion,其中包含PromotionDetails 的列表。 PromotionDetails 是每个产品的促销信息。 如何获取不包含特定产品的促销列表?

例如

promotion_id  |     name
===========================
       1      |  'Promo A'
       2      |  'Promo B'

promotion_id  | product_id
===========================
       1      |      1
       1      |      2
       1      |      3
       1      |      4
       2      |      1
       2      |      3
       2      |      4
       2      |      5

  product_id  | name
===========================
       1      | 'Product A'
       2      | 'Product B'
       3      | 'Product C'
       4      | 'Product D'
       5      | 'Product E'
       6      | 'Product F'

PromotionRepository#findAllPromotionWithNoProductId(1) 应该返回空数组

执行PromotionRepository#findAllPromotionWithNoProductId(2) 应该返回第二次晋升

PromotionRepository#findAllPromotionWithNoProductId(6)应该返回所有促销

下面是我的代码:

@Entity
public class Promotion {

    @Id
    @Column(name = "promotion_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String name;

    @OneToMany(mappedBy = "promotion")
    private List<PromotionDetails> details = new ArrayList<>();

    //more code
}

@Entity
@IdClass(PromotionPK.class)
public class PromotionDetails  {

    @Id
    @ManyToOne(optional = false)
    @JoinColumn(name = "promotion_id", 
                referencedColumnName = "promotion_id")
    private Promotion promotion;

    @Id
    @ManyToOne(optional = false)
    @JoinColumn(name = "product_id", 
                referencedColumnName = "product_id")
    private Product product;

    //more code

}

@Entity
public class Product {

    @Id
    @Column(name = "product_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String name;

    //more code
}

@Repository
public interface PromotionRepository extends JpaRepository<Promotion, Long> {

    @Query("SELECT DISTINCT p "
            + "FROM Promotion p "
            + "INNER JOIN promotion.details d "
            + "WHERE p.id = d.promotion.id "
            + "AND d.product.id <> :productId ")   
    List<Promotion> findAllPromotionWithNoProductId(@Param("productId") Long productId);

}

【问题讨论】:

    标签: java spring hibernate jpa spring-boot


    【解决方案1】:

    试试,

    public List<Promotion> findByProductIdNotIn(long id);
    

    编辑:检查section 2.3.2,表2.3

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-11
      • 2018-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-01
      相关资源
      最近更新 更多