@RequestMapping не получает параметры и значения.

0

Я пытаюсь создать api с CRUD-операциями. Для этого создан пользовательский компонент и UserRepository, который расширяет CrudRepository.

Я попытался создать одного пользователя, но он принимает нулевые значения. Один идентификатор пользователя создан в базе данных с нулевыми значениями.

Код:

@Controller    // This means that this class is a Controller
@RequestMapping(path="/demo") // This means URL start with /demo (after Application path)
public class MainController {
    @Autowired // This means to get the bean called userRepository
               // Which is auto-generated by Spring, we will use it to handle the data
    private UserRepository userRepository;

/*  @GetMapping(path="/add") // Map ONLY GET Requests
    public @ResponseBody String addNewUser (@RequestParam String name
            , @RequestParam String email) {
        // @ResponseBody means the returned String is the response, not a view name
        // @RequestParam means it is a parameter from the GET or POST request

        User n = new User();
        n.setName(name);
        n.setEmail(email);
        userRepository.save(n);;
        return "Saved";
    }*/

      @RequestMapping("/create")
      @ResponseBody
      public String create(String email, String name) {
        String userId = "";
        try {
              User user = new User(email, name);
              userRepository.save(user);
              userId = String.valueOf(user.getId());
        }
        catch (Exception ex) {
          return "Error creating the user: " + ex.toString();
        }
        return "User succesfully created with id = " + userId;
      }

    @GetMapping(path="/all")
    public @ResponseBody Iterable<User> getAllUsers() {
        // This returns a JSON or XML with the users
        return userRepository.findAll();
    }
}


public interface UserRepository extends CrudRepository<User, Long> {

      public User findByEmail(String email);
}



@Entity // This tells Hibernate to make a table out of this class
public class User {

      public User(String email, String name) {
            this.email = email;
            this.name = name;
          }

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;

    private String name;

    private String email;

    private String number;


    @OneToMany(mappedBy="user")
    private List <Location> locations;

    public List<Location> getLocations() {
        return locations;
    }

    public void setLocations(List<Location> locations) {
        this.locations = locations;
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

}

Я отправляю почтовый запрос от почтмана в формате JSON.

http://localhost:8080/demo/create


{
"name" : "sid",
"email" : "[email protected]"
}


Response :
User succesfully created with id = 2

Что здесь происходит? Я новичок в веб-разработке. Пожалуйста помоги. Благодарю.

РЕДАКТИРОВАТЬ:

Точно так же я пытаюсь добавить местоположение для конкретного пользователя. Создал местоположение bean и manytoOne отношение с пользовательским объектом.

Место вставляется, но идентификатор местоположения и user_id возвращает значение null.

 @Entity
public class Location {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;


    private String location;
    private double latitude;

    public Location() {}

    @ManyToOne(fetch = FetchType.LAZY)
    private User user;


       @Override
    public String toString() {
        return "Location [id=" + id + ", location=" + location + ", latitude=" + latitude + ", longitude=" + longitude
                + "]";
    }
    public double getLatitude() {
        return latitude;
    }
    public void setLatitude(double latitude) {
        this.latitude = latitude;
    }
    public double getLongitude() {
        return longitude;
    }
    public void setLongitude(double longitude) {
        this.longitude = longitude;
    }
    private double longitude;
    public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    public char[] getId() {
        // TODO Auto-generated method stub
        return null;
    }
}


@Controller    // This means that this class is a Controller
@RequestMapping(path="/Locations") // This means URL start with /demo (after Application path)

public class LocationController {

        @Autowired // This means to get the bean called userRepository
                   // Which is auto-generated by Spring, we will use it to handle the data
        private LocationRepository locationRepository;
        private UserRepository userRepository;

         @RequestMapping("/create")
         @ResponseBody
         public Location create(@RequestBody Location location) {
           String locId = "";
           Location newLocation = new Location();
           try {
               User user = userRepository(location.getUser()); //Get the parent Object

               newLocation = new Location(); //Create a new Many object
               newLocation.setLatitude(location.getLatitude());
               newLocation.setLongitude(location.getLongitude());
               newLocation.setLocation(location.getLocation());
               newLocation.setUser(user);

               locationRepository.save(newLocation);
               locId = String.valueOf(newLocation.getId());

           }
           catch (Exception ex) {
            // return "Error creating the user: " + ex.toString();
               return newLocation;
           }
           return locationRepository.save(newLocation);
         }

        private User userRepository(User user) {
            // TODO Auto-generated method stub
            return null;
        }

        @GetMapping(path="/all")
        public @ResponseBody Iterable<Location> getAllLocations() {
            // This returns a JSON or XML with the users
            return locationRepository.findAll();
        }

}



  public interface LocationRepository extends CrudRepository<Location, Long>{

}

Почтальон;

http://localhost:8080/Locations/create

    {
"latitude" : 15645.00,
"longitude" : 154645.00,
"location" : "miraroad",
"user": {
    "id" : 6
}
}

отклик

    {
    "id": null,
    "location": "miraroad",
    "latitude": 15645,
    "user": null,
    "longitude": 154645
}

Что здесь не так? Пожалуйста помоги. Благодарю.

Теги:
spring
spring-data-jpa
crud

1 ответ

2
Лучший ответ

Попробуй это. Это должно работать

 @RequestMapping("/create")
 @ResponseBody
 public String create(@RequestBody User user) {
   String userId = "";
   try {
        userRepository.save(user);
        userId = String.valueOf(user.getId());
    } catch (Exception ex) {
          return "Error creating the user: " + ex.toString();
     }
        return "User succesfully created with id = " + userId;
  }

И создайте Контрактор No Args в классе User.

  • 0
    Спасибо.. :-)
  • 0
    Я хочу вернуть созданного пользователя как объект json, как я могу? @pvpkiran
Показать ещё 5 комментариев

Ещё вопросы

Сообщество Overcoder
Наверх
Меню