1

我正在使用Spring Boot (2.1.7.RELEASE) + Spring Data JPA + postgres示例,并希望在发生任何异常的情况下回滚主键 ID。我浏览了https://www.logicbig.com/tutorials/spring-framework/spring-data-access-with-jdbc/transactional-roll-back.html以及如何在 JPA 中回滚事务?和许多其他有用的链接,但事情对我不起作用。

在我的项目中,我一直在寻找存储和的唯一组合firstNameLastName

学生.java

@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name="STUDENT", uniqueConstraints = {
        @UniqueConstraint(name="STU_KEY",columnNames = {"FIRSTNAME", "LASTNAME"})
})
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="STUDENT_ID")
    private Long studentId;

    @Column(name="FIRSTNAME")
    private String firstName;

    @Column(name="LASTNAME")
    private String lastName;

    @Column(name="EMAIL")
    private String email;
}

我已经开发了 REST 端点

StudentController.java

@RestController
public class StudentController {

    @Autowired
    private StudentService studentService;

    @ApiOperation(value = "Save Student", nickname = "Save Student")
    @ApiResponses(value = { @ApiResponse(code = 201, message = "Save Student Successful"),
            @ApiResponse(code = 500, message = "Internal Server Error"),
            @ApiResponse(code = 400, response = ErrorResource.class, message = "Program Type details are required ") })
    @PostMapping("/student")
    public ResponseEntity<HttpStatus> saveStudent(@ApiParam(value="Accepts a Student") @Valid @RequestBody StudentDto dto){
        studentService.saveStudent(dto);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }
}

StudentServiceImpl.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

import com.example.demo.dto.StudentDto;
import com.example.demo.entity.Student;
import com.example.demo.exceptions.InternalServerException;
import com.example.demo.repository.StudentRepository;

import lombok.extern.slf4j.Slf4j;


@Service
@Slf4j
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentRepository studentRepository;
    @Autowired
    private Environment e;

    @org.springframework.transaction.annotation.Transactional(rollbackFor= {DataIntegrityViolationException.class, Exception.class})
    @Override
    public void saveStudent(StudentDto dto) {
        Student studentEntity = convertToEntity(dto);
        try {
            studentRepository.save(studentEntity);
        } catch (DataIntegrityViolationException e) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "ConstraintViolationException", e.getCause());
        } catch (Exception ex) {
            log.error(e.getProperty("error.errors"), e.getProperty("DB Exception"));
            throw new InternalServerException(HttpStatus.INTERNAL_SERVER_ERROR, e.getProperty("DB Exception"), ex);
        }
    }

    private Student convertToEntity(StudentDto dto) {
        return Student.builder().firstName(dto.getFirstName()).lastName(dto.getLastName()).email(dto.getEmail())
                .build();
    }
}

以下是请求有效负载:第一次,它将成功保存到数据库中。下一次,我使用相同的有效负载点击请求。UniqueConstraints 失败了,我又遇到了同样的问题。

{
  "email": "john.doe@gmail.com",
  "firstName": "John",
  "lastName": "Doe"
}

现在,这次我将有效负载更改为下面并将其保存到数据库中

{
  "email": "john1.doe1@gmail.com",
  "firstName": "John1",
  "lastName": "Doe1"
}

但我看到主键序列号:2 和 3 已被消耗。有什么方法可以重置主键 2 和 3,当请求成功时,我想在主键 2 处保存记录。

student_id |email                |firstname |lastname |
-----------|---------------------|----------|---------|
1          |john.doe@gmail.com   |John      |Doe      |
4          |john1.doe1@gmail.com |John1     |Doe1     |

让我知道是否需要任何其他信息,即使我也可以分享我的示例代码。

4

0 回答 0