gpt4 book ai didi

java - JPA/hibernate : mapping a single element in an entity with an one-to-many relationship

转载 作者:行者123 更新时间:2023-12-03 20:16:55 26 4
gpt4 key购买 nike

我有以下表格:

TABLE Orders (
ID BIGINT NOT NULL PRIMARY KEY,
... other columns ...
)

TABLE Order_States (
ID BIGINT NOT NULL PRIMARY KEY,
Order_ID BIGINT NOT NULL FOREIGN KEY REFERENCES Orders(ID),
State_Type VARCHAR(30) NOT NULL,
State_Date DATETIME NOT NULL,
... other columns ...
)

以及以下映射:

@Entity
@Table(name = "orders")
class Order {

@Id
@GeneratedValue
private Long id;

@OneToMany(mappedBy = "order")
@OrderBy("stateDate DESC")
private List<OrderState> orderStates

public OrderState getCurrentState() {
return orderStates.get(0);
}

public void setCurrentState(OrderState state) {
state.setStateDate(new Date());
orderStates.add(state);
}

... other members ...
}

@Entity
@Table(name = "order_states")
class OrderState {

@Id
@GeneratedValue
private Long id;

@ManyToOne
@JoinColumn(name = "order_id")
private Order order;

@Enumerated(EnumType.STRING)
@Column(name = "state_type")
private StateType stateType;

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "state_date")
private Date stateDate;

... other members ...
}

我不想在我的映射中包含所有订单的状态(它们只是出于历史原因),而只是订单的当前状态,它由最新状态的日期决定。

这个有注释吗?例如(我猜):

@Entity
@Table(name = "orders")
class Order {
...

@OneToMany(mappedBy = "order")
@OrderBy("stateDate DESC")
@TakeFirst
private OrderState orderState

... getter and setter for orderState ...

...
}

最佳答案

您所说的功能称为软删除Here是通过使用 Hibernate 的注释 @SQLDelete@Where 来做这些事情的例子。

但是下面的代码很难实现

@TakeFirst
private OrderState orderState

这样写会更容易

@TakeFirst
private Set<OrderState> orderState // this will be a set containing one entry

关于java - JPA/hibernate : mapping a single element in an entity with an one-to-many relationship,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24906251/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com