即使将204作为HTTP状态代码获取,实体也不会保存在数据库中

时间:2014-12-13 17:18:56

标签: java hibernate jpa guice dropwizard

我使用JPA 2.0和Hibernate 4.3.0.Final以及带有dropwizard框架的Google Guice 3.0。在我的Resource类中,我在顶部应用了@Transactional注释。

@Path("/users")
@Slf4j
@Transactional
@Produces(MediaType.APPLICATION_JSON)
public class UsersResource {

    @PUT
    @Timed
    @Path("/{userId}/userAddress")
    @Consumes(MediaType.APPLICATION_JSON)
    public void setUserAddress(@Valid SetUserAddressRequest request,
           @PathParam("userId") String userId) {
           if (!userId.equals(request.getUserId())) {
                throw new BadRequestException(Constants.USERID_ID_DO_NOT_MATCH);
           }
           request.setUserId(userId);
           setUserAddressCommandProvider
           .get()
           .withRequest(request)
           .run();
     }
}

我在命令类中的run函数看起来像这样

private User getUserByUserId(String userId) throws ResourceNotFoundException {
    Optional<User> optionalUser = userRepository.getUser(userId);
    if (optionalUser.isPresent()) {
        return optionalUser.get();
    }
    throw new ResourceNotFoundException(Constants.COULD_NOT_FIND_USER);
}

 public Void run() throws ResourceNotFoundException, WebApplicationException {
     User user = getUserByUserId(request.getUserId());
     String address = request.getAddress();
     if (user.getAddress() != null) {
        throw new ResourceConflictException(Constants.ADDRESS_ALREADY_EXISTS);
     }
     user.setAddress(address);
     user.setUpdatedAt(new Date());
     return null;
 }

问题在于,大多数时间地址都会被保存,但有时即使我得到204作为响应代码也没有。任何关于如何调试它的指针都将非常感激。

更新:当我打开调试模式时,我在日志中看到此异常

 org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl: Exception clearing
 maxRows/queryTimeout [org.apache.tomcat.dbcp.dbcp.DelegatingPreparedStatement 
 with address: "com.mysql.jdbc.JDBC4PreparedStatement@76eb0f79: EXCEPTION: 
 com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: 
 No operations allowed after statement closed." is closed.]

1 个答案:

答案 0 :(得分:0)

您是否在@UnitOfWork方法上尝试了setUserAddress注释? https://dropwizard.github.io/dropwizard/manual/hibernate.html