调用DELETE接口时出现JTA EntityManager无法使用getTransaction()异常
Hey there, let's figure out how to fix this java.lang.IllegalStateException: A JTA EntityManager cannot use getTransaction() error you're hitting when calling your DELETE endpoint.
What's causing this error?
The root issue here is that you're using a JTA-managed EntityManager (since you've configured a JNDI datasource, which in JBoss-like containers triggers JTA transaction management by default). JTA EntityManagers don't allow manual calls to getTransaction()—but Spring Data JPA's default repository operations might be trying to start a local transaction, which clashes with JTA's container-managed global transactions.
Step-by-step fixes
Let's adjust your configuration and code to play nicely with JTA:
Explicitly set JPA transaction type to JTA
Add this line to yourapplication.propertiesto tell Spring you're using JTA instead of local transactions:spring.jpa.transaction-type=JTAThis ensures Spring Data JPA adapts its transaction handling to JTA rules, avoiding the forbidden
getTransaction()call.Fix your Repository interface
Your currentQuestionnarieRepositoryonly defines a customdeleteByIdmethod, which might bypass Spring's JTA-aware logic. Instead, inherit from Spring Data JPA'sJpaRepository—it provides a pre-built, JTA-compatibledeleteByIdimplementation:import org.springframework.data.jpa.repository.JpaRepository; public interface QuestionnarieRepository extends JpaRepository<Questionnarie, Long> { // No need to manually define deleteById—JpaRepository already includes it! }Add transaction management to your Service (if needed)
For consistency (especially if you add more business logic later), annotate your service class or method with@Transactional. This binds the operation to JTA's global transaction context:import org.springframework.transaction.annotation.Transactional; @Transactional public class QuestionnarieService { private final QuestionnarieRepository questionnarieRepository; // Constructor injection (preferred over field injection) public QuestionnarieService(QuestionnarieRepository questionnarieRepository) { this.questionnarieRepository = questionnarieRepository; } public void deleteQuestionnarie(Long id) { questionnarieRepository.deleteById(id); } }Verify your JBoss datasource configuration
Double-check that your JNDI datasourcejava:jboss/datasources/testDSis configured to support JTA in your JBossstandalone.xml. Look for a line like this in the datasource definition:<datasource jta="true" jndi-name="java:jboss/datasources/testDS" ...> <!-- rest of config --> </datasource>JBoss usually enables JTA by default for datasources, but it's worth confirming.
Wrap-up
After making these changes, Spring Data JPA will properly handle transactions via JTA instead of trying to manage local transactions, which should resolve the IllegalStateException you're seeing.
内容的提问来源于stack exchange,提问作者samdset

