我正在构建一个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);
}
控制器:
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
答案 0 :(得分:0)
好的,这是我的错误,因为我将@Transactional
放在错误的位置。我必须在控制器中而不是在CrudRepository中对方法进行标记。
存储库:
public interface ItemRepository extends CrudRepository<Item, Integer> {
public void deleteAllBySuppid(int suppid);
}
控制器:
@Transactional
public void deleteSupplier(@RequestParam(name = "suppid") int suppid) {
itemrepo.deleteAllBySuppid(suppid);
supprepo.delete(supprepo.findByid(suppid));
}
答案 1 :(得分:0)
解释为什么需要@Transactional
:
当您查看CrudMethodMetadataPostProcessor.postProcess
方法时,implementations
集中包含的所有Method都被TransactionSynchronizationManager
调用。 Custum函数需要手动添加事务。
答案 2 :(得分:0)
我也遇到过这个问题,但是 @Transactional
注释没有解决。
我遇到了一个奇怪的问题:我没有将 @SpringBootApplication
添加到我的 Main 类中。添加此注释解决了我的问题。