I hava two tables order and order_item, they have ManyToOne relationship. For the following code, what should I do to use pessimistic lock when I retrived order from database? CascadeType.ALL can not help solve this problem.
OrderItem orderItem = session.get(OrderItem.class, order_item_id, LockMode.PESSIMISTIC_WRITE)
Order order = orderItem.getOrder()
Not sure what your exact question is, but you can use an entity graph to specify that the many-to-one association should be fetched eagerly in which case the lock will also apply to the order table.
You can also do a query and join fetch though:
OrderItem orderItem = session.createQuery("from OrderItem i join fetch i.order where i.id = :id", OrderItem.class)
.setParameter("id", order_item_id)
.setLockMode(LockMode.PESSIMISTIC_WRITE)
.getSingleResult();