如何解决如何在OneToMany关系中仅检索一条记录?
我有两个实体,产品和价格。每个产品应只有1个有效价格。
产品:
@Entity
@Table(name = "product")
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;
@NotNull
@Column(name = "name",nullable = false)
private String name;
// getter and setters
}
价格:
@Entity
@Table(name = "product_price")
public class ProductPrice implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;
@NotNull
@Column(name = "price",nullable = false)
private Float price;
@NotNull
@Column(name = "active",nullable = false)
private Boolean active;
@ManyToOne
@JsonIgnoreProperties(value = "productPrices",allowSetters = true)
private Product product;
// getter and setters
}
我想在我的产品类中添加一个价格字段,以便知道当前价格。当前价格基本上是将active
设置为true
的价格条目。
我知道如何在Product实体上添加OneToMany关系,但这将为我提供所有价格。有什么办法让它只检索“活动”的价格?
解决方法
是的,您可以根据活动列检索单个记录。
您需要使用@Where(clause = "active = 'true'")
。
@Entity
@Table(name = "product")
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;
@NotNull
@Column(name = "name",nullable = false)
private String name;
@OneToMany(mappedBy = "product")
@Where(clause = "active = 'true'")
@JsonFormat(with = JsonFormat.Feature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED) // this will give you object structure instead of list
Set<ProductPrice> price;
// getter and setters
}
注意:请从@Where(clause = "active = 'true'")
或@Where(clause = "active = true")
中查看哪个在为您工作。
@JsonFormat(with = JsonFormat.Feature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED)
,这将为您提供对象结构而不是列表。
如下所示。
{
}
如果您不希望将单个记录作为列表返回,如下所示。
[{
}]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。