0

I am building RESTAPI in Spring boot+JPA(MYSQL). If I serach for an user id which is not present in the db, I get below response as error:

{
    "timestamp": 1545657449608,
    "status": 500,
    "error": "Internal Server Error",
    "exception": "**org.springframework.http.converter.HttpMessageNotWritableException**",
    "message": "Could not write content: Unable to find com.bookmyshow.user.User with id asd (through reference chain: com.bookmyshow.user.User_$$_jvst809_0[\"username\"]); nested exception is **com.fasterxml.jackson.databind.JsonMappingException**: Unable to find com.bookmyshow.user.User with id asd (through reference chain: com.bookmyshow.user.User_$$_jvst809_0[\"username\"])",
    "path": "/users/asd"
}

UserRegistrationController

package com.bookmyshow.user;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserRegistrationController {

@Autowired
private UserDAO userDAO;

@RequestMapping("/users/{id}") 
public ResponseEntity<?> getUser(@PathVariable String id) {

    User user= userDAO.getUser(id);

    if(user==null) {
        return ResponseEntity.notFound().build();
    }

    return ResponseEntity.ok().body(user);
    }

UserDAO

package com.bookmyshow.user;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class UserDAO {

@Autowired
UserRepository userRepository;  

public User getUser(String id) {

     System.out.println("USERDAO:"+id);
          return userRepository.getOne(id);
}
Alien
  • 15,141
  • 6
  • 37
  • 57

1 Answers1

1

The getOne methods returns only the reference from DB (lazy loading). So basically you are outside the transaction (the Transactional you have been declare in service class is not considered), and the error occur. see documentation

Use findOne instead.

Also see when-use-getone-and-findone-methods-spring-data-jpa

Alien
  • 15,141
  • 6
  • 37
  • 57