简体   繁体   中英

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

I have the following tables:

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 ...
)

And the following mappings:

@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 ...
}

I don't want to have all order's states in my mappings (they are just for historical reasons), but just the current state of the order, which is determined by the latest state's date.

Is there are any annotations for this? For example (I guess):

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

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

    ... getter and setter for orderState ...

    ...
}

The feature you are talking about is called soft delete . Here is an example of doing such stuff by using Hibernate 's annotations @SQLDelete and @Where .

However it would be difficult to make following code work

@TakeFirst
private OrderState orderState

it would be easier to code it like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM