Java 如何计算一对多JPA关系中每个项目的总成本?
我如何计算一对多关系中的订单总数,当客户在订单属性中购买了一定数量的商品时,他想知道,他可以开始调查,以实现这一点。我真的有点困惑,我真的很想学习Java 如何计算一对多JPA关系中每个项目的总成本?,java,spring,spring-boot,kotlin,spring-data-jpa,Java,Spring,Spring Boot,Kotlin,Spring Data Jpa,我如何计算一对多关系中的订单总数,当客户在订单属性中购买了一定数量的商品时,他想知道,他可以开始调查,以实现这一点。我真的有点困惑,我真的很想学习 @Entity @Table(name = "orders") class Order( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Int? = 0, val name: S
@Entity
@Table(name = "orders")
class Order(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Int? = 0,
val name: String? = "",
val address: String? = "",
val phone: String? = "",
val totalOrderPrice: Long? // total based on the cost of each item
@OneToMany(cascade = [CascadeType.MERGE])
@JoinColumn(name = "order_id")
val items: List<Items>? = mutableListOf()
)
首先,您需要更正映射。在子实体中,应该有父实体的引用。这意味着在“Items”类中添加对订单id的引用,作为“orderId”列。那么你的班级应该是这样的
@Entity
@Table(name = "items")
class Items(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long? = null,
val orderId: int? = null,
val name: String? = null,
val price: Long?, // cost item
)
现在,您有3个选项来计算订单的总价
@Entity
@Table(name = "items")
class Items(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long? = null,
val orderId: int? = null,
val name: String? = null,
val price: Long?, // cost item
)
@Query(“从项目m中选择总和(m.price),其中orderId=:orderId”)
Long getOrderPrice(@Param(“orderId”)Long orderId)强>
@Entity
@Table(name = "items")
class Items(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long? = null,
val orderId: int? = null,
val name: String? = null,
val price: Long?, // cost item
)
@Query(“从订单id=:orderId,nativeQuery=true的项目中选择总和(价格)
Long getOrderPrice(@Param(“orderId”)Long orderId)强>
看看这是不是你的。我真的很感谢你的帮助!很高兴认识你,这对你很有帮助