我正在构建一个 Spring Boot 后端,并想要创建一个休息端点,该端点会按供应商 ID 删除所有项目。当我调用其余端点时,我收到“没有可用的实际事务的实体管理器”异常。
如何修复此错误?
我尝试了@Transactional
注释,但错误仍然发生
型号:
public class Item {
public Item() {}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ItemId")
private int id;
public int getId() {
return this.id;
}
public void setId(int Id) {
this.id = Id;
}
@Column(name = "Suppid")
private int suppid;
public int getSuppid() {
return this.suppid;
}
public void setSuppid(int Suppid) {
this.suppid = Suppid;
}
}
存储库:
public interface ItemRepository extends CrudRepository<Item, Integer> {
@Transactional
public void deleteAllBySuppid(int suppid);
}
Controller :
public void deleteSupplier(@RequestParam(name = "suppid") int suppid) {
itemrepo.deleteAllBySuppid(suppid);
supprepo.delete(supprepo.findByid(suppid));
}
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.0.Final</version>
</dependency>
</dependencies>
我希望该项目被删除,但它抛出:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: No EntityManager with actual transaction available for current thread - cannot reliably process 'remove' call; nested exception is javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'remove' call] with root cause
最佳答案
解释为什么需要@Transactional
:
当您查看 CrudMethodMetadataPostProcessor.postProcess
方法时,implementations
集中包含的所有方法都会通过 TransactionSynchronizationManager
进行调用。 Custum Functions需要手动添加Transactions。
关于hibernate - 调用deleteallby方法时如何修复 'no entitymanager with actual transaction'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56220144/