I'm trying to post a simple model using Restful controllers in Spring Boot, but when I'd like my relationship objects it won't work.
I'm using the latest version of Spring
The Controller Method:
#RequestMapping(value= "rest/person/create", method = RequestMethod.POST)
public ResponseEntity<Person> createOrUpdate(#RequestBody Person person){
System.out.println("creating!");
try{
if (person != null){
peopleRepository.save(person);
}
}
catch (Exception e){
e.printStackTrace();
return new ResponseEntity<Person>(HttpStatus.UNAUTHORIZED);
}
return new ResponseEntity<Person>(HttpStatus.OK);
}
The Person class:
#Entity
public class Person {
#Id
#GeneratedValue
private Long id;
#Temporal(TemporalType.DATE)
#DateTimeFormat(pattern = "dd/MM/yyyy")
private Date registryDate;
#Temporal(TemporalType.DATE)
#DateTimeFormat(pattern = "dd/MM/yyyy")
private Date updateDate;
private String firstName;
private String lastName;
#Temporal(TemporalType.DATE)
#DateTimeFormat(pattern = "dd/MM/yyyy")
private Date birthDate;
private String gender;
private String rg;
private String cpf;
private String phone;
private String celPhone;
#ManyToOne
private Address address;
#Column(unique=true)
private String email;
private String observation;
byte situation;
protected Person(){}
public Person(Long id, Date registryDate, Date updateDate,
String firstName, String lastName, Date birthDate, String gender, String rg,
String cpf, String phone, Address address, String email,
String observation, byte situation) {
super();
this.id = id;
this.registryDate = registryDate;
this.updateDate = updateDate;
this.firstName = firstName;
this.lastName = lastName;
this.birthDate = birthDate;
this.gender = gender;
this.rg = rg;
this.cpf = cpf;
this.phone = phone;
if (address != null)
this.address = address;
this.email = email;
this.observation = observation;
this.situation = situation;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getRegistryDate() {
return registryDate;
}
public void setRegistryDate(Date registryDate) {
this.registryDate = registryDate;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getRg() {
return rg;
}
public void setRg(String rg) {
this.rg = rg;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getObservation() {
return observation;
}
public void setObservation(String observation) {
this.observation = observation;
}
public byte getSituation() {
return situation;
}
public void setSituation(byte situation) {
this.situation = situation;
}
public String getCelPhone() {
return celPhone;
}
public void setCelPhone(String celPhone) {
this.celPhone = celPhone;
}
}
The JSON Object:
var person = {"firstName":"Joao","lastName":"Silva",
"gender":"Masculino","rg":"808080",
"cpf":"00","phone":"0","celPhone":"0",
"address":{"street":"Rua","number":5,"neighborhood":"Bairro",
"city":{"name":"Cidade",
"state":{"name":"Rio Grande do Sul","uf":"RS"},
"uf":"AE"},"cep":"Cep","complement":"Complemento"},
"email":"maluco#gmail.com","observation":"poisé","situation":0};
And the Angular.JS post ->
$http.post('rest/person/create', person).
success(function(data, status, headers, config) {
console.log('all good!');
$scope.create = true;
}).
error(function(data, status, headers, config) {
console.log('error');
$scope.create = false;
});
I've been looking how to do it, and could'nt find it.
I'm completely beginner with Spring
The error happens only with the relationships, if I remove
"address":{"street":"Rua","number":5,"neighborhood":"Bairro",
"city":{"name":"Cidade",
"state":{"name":"Rio Grande do Sul","uf":"RS"},
"uf":"AE"},"cep":"Cep","complement":"Complemento"}
It will work.
You need to declare Content-Type when you post a request, and then #RequesetBody annotation convert http body text to a JSON object using jackson.
So you need to change your content-types, and stringify your json object.
$http({
url: 'rest/person/create',
dataType: 'json',
method: 'POST',
data: JSON.stringify(persion),
headers: {
"Content-Type": "application/json"
}
}).success(function(response){
$scope.response = response;
}).error(function(error){
$scope.error = error;
});
Related
I have a one to one relation between two classes. I want to create phase items without having to insert candidate Id with it, because I get candidates afterwards so they basically don't exist.
Right now I'm getting the error:
could not execute statement; SQL [n/a]; constraint [null];
because i'm not sending candidateId with it.
This is the first class :
public class PhaseItems {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "phaseI_id")
private long id;
private String PhaseItem;
#ManyToMany(fetch = FetchType.LAZY,
mappedBy = "items")
#JsonIgnore
private List<PhaseTemplate> template = new ArrayList<>();
#OneToOne(fetch = FetchType.LAZY, optional = true)
#JoinColumn(name = "candidate_id", nullable = true)
private Candidate candidate;
public PhaseItems() {
super();
}
public PhaseItems(long id, String phaseItem) {
super();
this.id = id;
PhaseItem = phaseItem;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getPhaseItem() {
return PhaseItem;
}
public void setPhaseItem(String phaseItem) {
PhaseItem = phaseItem;
}
public List<PhaseTemplate> getTemplate() {
return template;
}
public void setTemplate(List<PhaseTemplate> template) {
this.template = template;
}
public Candidate getCandidate() {
return candidate;
}
public void setCandidate(Candidate candidate) {
this.candidate = candidate;
}
#Override
public String toString() {
return "PhaseItems [id=" + id + ", PhaseItem=" + PhaseItem + ", template=" + template + "]";
}
This is the second class:
#Entity
#Table(name= "candidats")
public class Candidate {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "candidate_id")
private long id;
private String fullname;
private String username;
#Column(nullable = false, unique = true, length = 45)
private String email;
private String adress;
private String phoneNumber;
private String password;
#Column(name = "status")
private String status;
#OneToOne(fetch = FetchType.LAZY,
cascade = CascadeType.ALL,
mappedBy = "candidate")
private PhaseItems phases;
public Candidate(){
}
public Candidate(String fullname,String username,String email, String adress, String phoneNumber, String password,
List<JobApplication> appliedJobs) {
super();
this.fullname = fullname;
this.username = username;
this.email = email;
this.adress = adress;
this.phoneNumber = phoneNumber;
this.password = password;
this.appliedJobs = appliedJobs;
}
public Candidate(String fullname,String username, String email, String adress, String phoneNumber, String password) {
super();
this.fullname = fullname;
this.username = username;
this.email = email;
this.adress = adress;
this.phoneNumber = phoneNumber;
this.password = password;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<JobApplication> getAppliedJobs() {
return appliedJobs;
}
public void setAppliedJobs(List<JobApplication> appliedJobs) {
this.appliedJobs = appliedJobs;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
Set column candidate_id as nullable in your database. Java attribute nullable = true of #JoinColumn annotation is ignored.
Is your column « candidate_id » from table phase_items nullable in your schema ?
I am trying submit json data to a Spring MVC controller mapped with a model. Instead of getting the json values, the values of the fields of the model are all NULL.
IDE debugger:
Chrome:
Exception:
org.springframework.dao.InvalidDataAccessApiUsageException: The given id must not be null!; nested exception is java.lang.IllegalArgumentException: The given id must not be null!
Controller:
#RequestMapping(value = "/update", method = RequestMethod.POST)
#ResponseBody
public PostResponse update(Setting setting, BindingResult bindingResult) {
return settingService.processUpdate(setting, bindingResult, messageSource);
}
JSON data:
{
"updatedAt":1460600207000,
"id":1,
"createdBy":null,
"description":"This is a setting",
"code":"MY_SETTING",
"value":"{\"id\":\"1018\",\"title\":\"Another setting\",\"code\":\"220-203-10-101\"}"
}
Model:
#Entity
#JsonIgnoreProperties(ignoreUnknown = true)
public class Setting {
#Id
#GeneratedValue
#Column
private Integer id;
#Column(unique = true)
private String code;
#Column
private String description;
#Column
private String value;
#Temporal(TemporalType.TIMESTAMP)
#Column(nullable = false)
private Date createdAt;
#Temporal(TemporalType.TIMESTAMP)
#Column(nullable = false)
private Date updatedAt;
#NotFound(action = NotFoundAction.IGNORE)
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="FK_createdByUserId")
private User createdBy;
public Setting() {}
public Setting(String code, String description, String value, Date createdAt, Date updatedAt, User createdBy) {
this.code = code;
this.description = description;
this.value = value;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
this.createdBy = createdBy;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public User getCreatedBy() {
return createdBy;
}
public void setCreatedBy(User createdBy) {
this.createdBy = createdBy;
}
I guess that the setting bean is not mapped at all.
You need to tell spring how to map the http request to the method arguments. If you're posting data, the best way is to add #RequestBody annotation to the relevant method argument (setting in your case)
Modify your controller method like this:
#RequestMapping(value = "/update", method = RequestMethod.POST)
#ResponseBody
public PostResponse update(#RequestBody Setting setting, BindingResult bindingResult) {
return settingService.processUpdate(setting, bindingResult, messageSource);
}
How do I access the returned result from a service? The result is queried from the database and added to a ObservableList. I have a checkbox and wanted its value to depend on the result from the database.
How do I bind the checkbox so that its value(checked/unchecked) will depend on the rs.getString("studentForm137") field.
//cboxForm137.selectedProperty().bind(//I don't know the codes to bind checkbox);
Service
final Service<ObservableList<Student>> service = new Service<ObservableList<Student>>()
{
#Override
protected Task<ObservableList<Student>> createTask()
{
return new Task<ObservableList<Student>>()
{
#Override
protected ObservableList<Student> call() throws Exception
{
for (int i = 0; i < 250; i++)
{
updateProgress(i, 250);
Thread.sleep(2);
}
return student.display();
}
};
}
};
service.start();
Student Class
public class Student extends Person {
private SimpleStringProperty form137;
private SimpleStringProperty form138;
private SimpleStringProperty goodMoralCertificate;
private SimpleStringProperty birthCertificate;
private SimpleStringProperty highschoolDiploma;
public Student()
{
super();
}
public Student(String lastName, String firstName, String middleName,
String cpNumber, String address, String dateOfBirth,
String placeOfBirth, String emailAddress, String gender,
String fathersName, String mothersName,
String form137, String form138, String goodMoralCertificate,
String birthCertificate, String highschoolDiploma)
{
super(lastName, firstName, middleName,
cpNumber, address, dateOfBirth, placeOfBirth, emailAddress, gender,
fathersName, mothersName);
this.form137 = new SimpleStringProperty(form137);
this.form138 = new SimpleStringProperty(form138);
this.goodMoralCertificate = new SimpleStringProperty(goodMoralCertificate);
this.birthCertificate = new SimpleStringProperty(birthCertificate);
this.highschoolDiploma = new SimpleStringProperty(highschoolDiploma);
}
//form137
public String getForm137()
{
return form137.get();
}
public void setForm137(String form137)
{
this.form137.set(form137);
}
public StringProperty form137Property()
{
return form137;
}
//form138
public String getForm138()
{
return form138.get();
}
public void setForm138(String form138)
{
this.form138.set(form138);
}
public StringProperty form138Property()
{
return form138;
}
//goodMoralCertificate
public String getGoodMoralCertificate()
{
return goodMoralCertificate.get();
}
public void setGoodMoralCertificate(String goodMoralCertificate)
{
this.goodMoralCertificate.set(goodMoralCertificate);
}
public StringProperty goodMoralCertificateProperty()
{
return goodMoralCertificate;
}
//birthCertificate
public String getBirthCertificate()
{
return birthCertificate.get();
}
public void setBirthCertificate(String birthCertificate)
{
this.birthCertificate.set(birthCertificate);
}
public StringProperty birthCertificateProperty()
{
return birthCertificate;
}
//highschoolDiploma
public String getHighschoolDiploma()
{
return highschoolDiploma.get();
}
public void setHighschoolDiploma(String highschoolDiploma)
{
this.highschoolDiploma.set(highschoolDiploma);
}
public StringProperty highschoolDiplomaProperty()
{
return highschoolDiploma;
}
#Override
public ObservableList display()
{
Connection c = null;
PreparedStatement pst = null;
ResultSet rs = null;
ObservableList<Student> student = FXCollections.observableArrayList();
try
{
c = MySqlConnection.connect();
String SQL = "SELECT * " +
"FROM students ";
pst = c.prepareStatement(SQL);
rs = pst.executeQuery();
while(rs.next())
{
student.add(new Student(rs.getString("studentLastName"),
rs.getString("studentFirstName"),
rs.getString("studentMiddleName"),
rs.getString("studentCPNumber"),
rs.getString("studentAddress"),
rs.getString("studentDateOfBirth"),
rs.getString("studentPlaceOfBirth"),
rs.getString("studentEmailAddress"),
rs.getString("studentGender"),
rs.getString("studentFathersName"),
rs.getString("studentMothersName"),
rs.getString("studentForm137"),
rs.getString("studentForm138"),
rs.getString("studentGMC"),
rs.getString("studentNSO"),
rs.getString("studentHSDiploma")));
}
}
catch(Exception e)
{
System.out.println("Error on Building Data");
}
finally
{
try
{
PublicClass.closeConnection(c, pst, rs);
}
catch (SQLException ex)
{
Logger.getLogger(Student.class.getName()).log(Level.SEVERE, null, ex);
}
}
return student;
}
}
angular controller
$http({
method: 'POST',
url: '/Eatery/save',
contentType:'application/json',
dataType:'json',
data:resvnCtrl.user
})
Spring mvc controller
#RequestMapping(value="/save",method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public int save(#RequestBody Reservation reservation) {
System.out.println(reservation.getTime());
return reservationRepo.save(reservation);
}
Java model
#Entity
#Table(name="reservations")
public class Reservation implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String cnf;
private String name;
private String email;
private String phone;
#JsonDeserialize(using=CustomJsonDateDeserializer.class)
private LocalDateTime time;
private int seats;
private String note;
public Reservation() { }
public Reservation(String cnf, String name, String email, String phone,
LocalDateTime time, int seats, String note) {
this.cnf = cnf;
this.name = name;
this.email = email;
this.phone = phone;
this.time = time;
this.seats = seats;
this.note = note;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCnf() {
return cnf;
}
public void setCnf(String cnf) {
this.cnf = cnf;
}
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 getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public LocalDateTime getTime() {
return time;
}
public void setTime(LocalDateTime time) {
this.time = time;
}
public int getSeats() {
return seats;
}
public void setSeats(int seats) {
this.seats = seats;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
From browser console
email: "kerhb#regerg.e"
name: "kjergk"
note: "wefwef"
phone: "1234567899"
seats: 2
time: "10/23/2015 5:53 PM"
Custom date deserializer
public class CustomJsonDateDeserializer extends JsonDeserializer<Date>
{
#Override
public Date deserialize(JsonParser jsonparser,
DeserializationContext deserializationcontext) throws IOException, JsonProcessingException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String date = jsonparser.getText();
try {
return format.parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
I have a bootstrap datetimepicker on UI and a java REST webservice at the backend. when i send date select, i got "The request sent by the client was syntactically incorrect.". the datetime string which is sent did not map to the java model. can someone spot my error
#Marged is rigth saying that you didn't cover AM/PM in your date pattern. The proper patter would be yyyy-MM-dd HH:mm a. Note also that you don't need a custom deserializer for this, can rather use #DateTimeFormat
#DateTimeFormat(pattern = "yyyy-MM-dd HH:mm a")
private LocalDateTime time;
I defined an endpoint with the following methods:
#ApiMethod(name = "update", path = "properties/{id}", httpMethod = HttpMethod.PUT)
public void update(#Named("id") Long id, RealEstatePropertyAPI propertyAPI,
User user) {
On the client side I tried several calls but none of them populates the propertyAPI object on the server side. The instance is created with all fields set to null except the id.
var jsonId = { 'id': '11'};
var x = {"name": "Test","address": { "street": "White House"}};
gapi.client.realestate.update(jsonId, x).execute(function(resp) {
console.log('PropertyEdited');
console.log(resp);
});
Or
var jsonId = { 'id': '11'};
var x = {"name": "Test","address": { "street": "White House"}};
gapi.client.realestate.update(jsonId, {'resource' : x}).execute(function(resp) {
console.log('PropertyEdited');
console.log(resp);
});
The Java classes:
public class RealEstatePropertyAPI {
private Long id;
private String name;
private AddressAPI address;
public RealEstatePropertyAPI() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public AddressAPI getAddress() {
return address;
}
public void setAddress(AddressAPI address) {
this.address = address;
}
}
public class AddressAPI {
private Long id;
private String street;
private String city;
private String state;
private String zip;
private String country;
public AddressAPI() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
I'm not actually sure about about this, but you can try to pass all the parameters within a single object, I mean wrap the parameters with brackets { }, like this:
//var jsonId = { 'id': '11'};
var x = {"name": "Test","address": { "street": "White House"}};
gapi.client.realestate.update({'id': '11', 'resource' : x}).execute(function(resp) {
console.log('PropertyEdited');
console.log(resp);
});
Because in fact in both your requests you're sending 2 objects... And I think you have to use 'resource' for the parameters in the POST data as in your second option...