派生的DeleteBy查询不起作用。但是findBy
并使用@Query
删除即可。
我尝试添加@Modifying
和@Transactional
,我将返回类型更改为Long
,List<OrderItem>
,void
。
这是我的CrudRepository接口,Order和OrderItem类:
public interface OrderItemRepository extends CrudRepository<OrderItem, Long> {
List<OrderItem> findByOrderAndItem_ItemGroup(Order order, ItemGroup itemGroup);
@Transactional
Long deleteByOrder(Order order);
@Modifying
@Query("delete from OrderItem o where o.order = ?1")
Integer deleteByOrderQuery(Order order);
}
@Entity
@Table(name = "t_order_items")
public class OrderItem {
@GeneratedValue
@Id
private Integer id;
@Column(name="itemcount")
private Integer itemCount;
@OneToOne()
@JoinColumn(name="item_id")
private Item item;
@ManyToOne
@JoinColumn(name = "oder_id")
private Order order;
}
@Entity
@Table(name = "t_orders")
public class Order implements Serializable {
@GeneratedValue
@Id
private Integer id;
@Column(name = "orderdate")
private LocalDate orderDate;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.REMOVE, mappedBy = "order")
private List<OrderItem> orderItems;
}
我已经阅读了文档http://docs.spring.io/spring-data/jpa/docs/current/reference/html/,但是deleteBy并没有什么特别之处。
最佳答案
问题出在CascadeType.ALL
中。
当我将其更改为CascadeType.REMOVE
时,一切正常。
正确的答案是:
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.REMOVE, mappedBy = "order")
private List<OrderItem> orderItems;