I’m trying to delete an entity with a composite primary key whose constituents are other 2 entities from a database (many to many relationship, code below). The primary keys of these entities are ids of type Long and I try to delete exactly by these ids (the code is again below) without a native request, but in response I get the following exception:
jakarta.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'remove' call.
As I understand it, there is no suitable method for such removal, although, as for me, the name of the method is constructed correctly.
And in this regard, I have a question – is it possible in my case to carry out the deletion by delegating the construction of the request to Spring JPA?
Repository:
@Repository
public interface ServiceOrderRepository extends JpaRepository<ServiceOrder, ServiceOrderPk> {
List<ServiceOrder> findAllByPkOrderId(Long id);
void deleteByPkOrderIdAndPkServiceId(Long orderId, Long serviceId);
}
P.S. findAllByPkOrderId
is working.
Order entity class:
// annotations skipped
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@EqualsAndHashCode.Include
private Long id;
@ManyToOne(
targetEntity = Client.class,
cascade = CascadeType.MERGE,
fetch = FetchType.EAGER
)
@JoinColumn(name = "client_id", referencedColumnName = "id")
private Client client;
@Column(name = "registration_date")
private LocalDateTime registrationDate;
@Column(name = "appointment_date")
private LocalDateTime appointmentDate;
@Column(name = "execution_date")
private LocalDateTime executionDate;
}
Service entity class:
// annotations skipped also
public class Service {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@EqualsAndHashCode.Include
private Long id;
@Column(name = "name")
private String name;
@Column(name = "description")
private String description;
@Column(name = "price")
private BigDecimal price;
}
Service-Order primary key:
// you know what I want to write
public class ServiceOrderPk implements Serializable {
@ManyToOne(
targetEntity = Order.class,
cascade = CascadeType.MERGE,
fetch = FetchType.LAZY
)
@JoinColumn(name = "order_id")
private Order order;
@ManyToOne(
targetEntity = Service.class,
cascade = CascadeType.MERGE,
fetch = FetchType.LAZY
)
@JoinColumn(name = "service_id")
private Service service;
}
Service-Order entity:
// ...
public class ServiceOrder {
@EmbeddedId
@EqualsAndHashCode.Include
private ServiceOrderPk pk;
@Column(name = "price")
private BigDecimal price;
@Column(name = "percent_discount")
private Long percentDiscount;
}
And additionally: does it make sense to write fetch = FetchType.LAZY
not over a collection?
John Wick is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.