I
I
Ivan R2015-04-23 19:58:03
MySQL
Ivan R, 2015-04-23 19:58:03

How to make a correct POST request in java?

I am creating a rest service (I use: Java, Maven, TomCat, MySql, Hibernate). I'm trying to implement adding new data to the database via a POST request. But I can't do it, the data is not written to the database. What do I need to correct in order for the request to pass?
If I receive data from the server via JSON, then I get it in this form:

[{"person":{"id":11,"fullName":"Maria","age":19,"city":"Tver","gender":"female"}},{"person":{"id":12,"fullName":"Nadya","age":29,"city":"Omsk","gender":"female"}},{"person":{"id":13,"fullName":"Sergey","age":18,"city":"Novosibirsk","gender":"male"}}]

When sending a request to the Body, I write:
{"person":{"fullName":"Maria111","age":19,"city":"Tver","gender":"female"}}

service.java:
@POST
    @Path("/add")
    @Produces(MediaType.APPLICATION_JSON)
    public String saveNewPerson(JSONObject person) throws JSONException {
        person.toString();
         System.out.println(person + " output in service.java");
        if (!personDao.savePerson(null)) {
            return "Person create success   id=";
 
        } else {
            return "error, check information for new person";
        }
    }

PersonDao.java:
public boolean savePerson(JSONObject person) {
         System.out.println(person+" output in personDAO.java");
        Session session = null;
        boolean hasErrors = false;
 
        try {
            session = sessionFactory.openSession();
            session.beginTransaction();
            session.saveOrUpdate(person);
            session.getTransaction().commit();
 
        } catch (Exception ex) {
            if (session != null) {
                session.getTransaction().rollback();
                  Log.write("Ошибка в методе savePerson ");
            }
            hasErrors = true;
 
        } finally {
            if (session != null) {
                session.close();
            }
        }
        return hasErrors;
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Timur, 2015-04-23
@neo55

You don't really understand what's going on in your code. A couple of comments in the code:

@POST
    @Path("/add")
    @Produces(MediaType.APPLICATION_JSON)
    public String saveNewPerson(JSONObject person) throws JSONException {
  
  //вызов этого метода никак  не влияет на код, так как  toString() возвращает строку, но вы ее никак не используете
        person.toString();
    // тут как раз и происходит toString(); 
         System.out.println(person + " output in service.java");
     //почему в savePerson() вы кладете NULL?
        if (!personDao.savePerson(null)) {
            return "Person create success   id=";
 
        } else {
            return "error, check information for new person";
        }
    }
  
  ******************************************
      // Тут нужно класть Entity класс ,а не JSONObject.
            session.saveOrUpdate(person);

You are passing null to the method and naturally you have an error. But even if you passed your JSONObject, nothing would happen, because you need to save a persistent object that represents a table in the database. The so-called entity.
Here's what it might look like for you:
@Entity
@Table(name =  "person")
public class Person implements Serializable{

    private static final long serialVersionUID = 1L;

  @Id
  @Column(name = "id", nullable = false)
  private int id;
  
  @Column(name = "full_name")
  private String fullName;
  
  @Column(name = "age")
  private int age;
  
  @Column(name = "city")
  private String city;
  
  @Column(name = "gender")
  @Enumerated(EnumType.STRING)
  private Gender gender;
  
  
  public Person(){
  }
  
  // геттеры и сеттеры обязательно
}

In general, read the materiel a little.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question