【发布时间】: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