Spring引导和Spring Data JPA @Transactional不工作

时间:2016-06-05 02:32:45

标签: spring jpa spring-boot spring-data

我创建了一个示例SpringBoot项目并使用JPA Repository来保存数据库中的简单Greeting对象(Greeting Id和Greeting Text)。我在服务类@Transactional中向createGreeting()方法添加了GreetingServiceImpl注释,并在数据库中保留了Greeting记录后抛出RuntimeException。我除了问候记录在数据库中回滚。但记录仍然存在于数据库中。代码如下。有什么建议?提前谢谢。

应用

@SpringBootApplication
@EnableTransactionManagement
public class SpringBootDataWebApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootDataWebApplication.class, args);
    }
}

ServletInitializer

 public class ServletInitializer extends SpringBootServletInitializer {

        @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
            return application.sources(SpringBootDataWebApplication.class);
        }

    }

模型

@Entity
public class Greeting {

    @Id
    @GeneratedValue
    private Long id;

    private String text;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

}

休息控制器

    @RestController
public class GreetingController {

    @Autowired
    private GreetingService greetingService;

    @RequestMapping(value = "/api/greetings", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Greeting> createGreeting(@RequestBody Greeting greeting) throws Exception {
        Greeting greetingCreated = greetingService.createGreeting(greeting);
        return new ResponseEntity<>(greetingCreated, HttpStatus.CREATED);
    }

}

服务类

@Service
public class GreetingServiceImpl implements GreetingService {

    @Autowired
    private GreetingRepository greetingRepository;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public Greeting createGreeting(Greeting greeting) {
        if (greeting.getId() != null)
            return null;
        Greeting greetingCreated = greetingRepository.save(greeting);
        if (true) {
            throw new RuntimeException("Roll me back!");
        }
        return greetingCreated;
    }

}

存储库

@Repository
public interface GreetingRepository extends JpaRepository<Greeting, Long> {

}

POM文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.sam</groupId>
    <artifactId>spring</artifactId>
    <version>1.0</version>
    <packaging>war</packaging>

    <name>SpringBootDataWeb</name>
    <description>Demo project for Spring Boot and Spring Data</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.5.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jta-atomikos</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

错误消息

{
  "timestamp": 1465094495762,
  "status": 500,
  "error": "Internal Server Error",
  "exception": "java.lang.RuntimeException",
  "message": "Roll me back!",
  "path": "/SpringBootDataWeb/api/greetings"
}

3 个答案:

答案 0 :(得分:0)

高级JpaTransactionManager

绑定到greetingRepository.save(greeting)

如果在save方法中发生任何异常将进行回滚,JpaTransactionManager将在commit期间没有异常时执行save并且TransactionStatus将被设置到completed

因此,如果在未绑定到JpaTransactionManager的应用程序代码中发生任何异常,则提交后提交是应用程序异常。

答案 1 :(得分:0)

理想情况下,在单元/集成测试时完成回滚。在这些场景中,注释@TransactionConfiguration(defaultRollback = true)用于编写测试用例的类。

您可以在服务类上试试吗。

答案 2 :(得分:0)

要记住几件事:

  • @Repository注释不是必需的,因为您的存储库界面已经从JpaRepository延伸。
  • 您的服务实现缺少(或至少在上面的示例中没有)@Service注释,因此控制器中的@Autowired不起作用(我假设您在界面中有它?因为你没有与bean相关的例外情况。)
  • 方法级别的@Transactional是正确的,但默认设置为readOnly=false,因此您无需再次指定

我想的是您的Greeting实体可能没有正确映射,但仍然很难猜出显示的错误消息。您能否提供有关错误堆栈跟踪的更多信息?