@Transactional在我使用JPA进行弹簧启动时在控制器中使用@Valid时无法正常工作

时间:2018-01-15 06:33:52

标签: java spring hibernate jpa transactions

如果我不使用@Transactional,那么它可以正常工作。 如果我使用@Transactional并且我的输入数据是“tag_name”用于标记名称,@Valid检查模式验证并为此提供异常,我也正在处理它,但我无法处理{{1 }}。它给出“无法提交JPA事务;嵌套异常为org.springframework.transaction.TransactionSystemException:事务标记为rollbackOnly”

我的域名

javax.persistence.RollbackException

我的控制器

@Entity
@Table(name = "tag")
public class Tag implements Serializable{

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

@NotBlank(message = "{tag.name.mandatory.message}")
@Pattern(regexp = "^[A-Za-z0-9]+$", message = "{tag.name.pattern.message}")
@Column(name = "name", length = 50)
private String  name;
//Setter & Getter
}

服务

@RestController
@RequestMapping("/api")
public class TagController {

@Autowired
private TagService tagService;

private Map<String, Object> map = null; 

@PostMapping("/saveTag")
public ResponseEntity<Map> saveTag(@Valid @RequestBody String jsonString){  
    map = tagService.saveTag(jsonString);
    HttpStatus statusName;
    statusName = (HttpStatus) ((Map)map.get( "metadata" )).get( "status" );
    return new ResponseEntity<Map>(map,statusName);
  }
}

异常处理程序类

@Override
@Transactional
public Map<String,Object> saveTag(String jsonString){

    long startTime = System.currentTimeMillis();
    UUID returnId = UUID.randomUUID();      
    Tag tag = new Tag();
    URI location = ServletUriComponentsBuilder.fromCurrentRequest().buildAndExpand(tag).toUri();

    mapper = new ObjectMapper();
    node = mapper.readValue(jsonString, JsonNode.class);        
    map = new HashMap<>();
    Map<String, Object> map1 = new HashMap<>();     
    map1.put("requestId",returnId);
    map1.put("requestedUri",location);              
    tag.setName(node.get("name").asText());             
    try {
        tagRepository.save(tag);
        map1.put("code","201");
        map1.put("status",HttpStatus.CREATED);
    }catch (Exception e) {
        e.printStackTrace();                
        map1.put("message","Service Unavailable");
        map1.put("code","503");
        map1.put("status",HttpStatus.SERVICE_UNAVAILABLE);
    }                       
    long endTime = System.currentTimeMillis();
    long diff = endTime - startTime;        
    map1.put("responseTime",diff);
    map.put("metadata", map1);      
    return map;
}

异常

@ControllerAdvice
public class GlobalExceptionHandler{    
@ExceptionHandler({ ConstraintViolationException.class})
@ResponseStatus(org.springframework.http.HttpStatus.BAD_REQUEST)
public ResponseEntity<Object> handleConstraintViolation(ConstraintViolationException e) {
    StringBuilder message = new StringBuilder();
    Map<String, Object> map = new HashMap<>();
    Map<String, Object> map1 = new HashMap<>()
    Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
    for (ConstraintViolation<?> violation : violations) {
      message.append(violation.getMessage().concat(";"));
    }         
    map1.put("message",message);
    map1.put("code","400");
    map1.put("status",org.springframework.http.HttpStatus.BAD_REQUEST);
    map.put("metadata", map1);      
    return new ResponseEntity<Object>(map,org.springframework.http.HttpStatus.BAD_REQUEST);
}   

@ExceptionHandler({ TransactionSystemException.class })
@ResponseStatus(org.springframework.http.HttpStatus.BAD_REQUEST)
public ResponseEntity<Object> handleTransactionException(Exception ex, WebRequest request) {
    Throwable cause = ((TransactionSystemException) ex).getRootCause();
    StringBuilder message = new StringBuilder(); 
    Map<String, Object> map = new HashMap<>();
    Map<String, Object> map1 = new HashMap<>();     
    if (cause instanceof ConstraintViolationException) {
        Set<ConstraintViolation<?>> constraintViolations = ((ConstraintViolationException) cause).getConstraintViolations();
        for (ConstraintViolation<?> violation : constraintViolations) {
            message.append(violation.getMessage().concat(";"));
          } 
    }else{
        message.append("Invalid data");
    }
    map1.put("message",message);
    map1.put("code","400");
    map1.put("status",org.springframework.http.HttpStatus.BAD_REQUEST);
    map.put("metadata", map1);      
    return new ResponseEntity<Object>(map,org.springframework.http.HttpStatus.BAD_REQUEST);
 }

}

0 个答案:

没有答案