From controller I am sending BinderPlaceOrder object like this
model.addAttribute("addNewBinderPlaceOrder", new BinderPlaceOrder());
My Thymeleaf page is,
<form class="addBinderPlaceOrderForm" role="form" action="#" th:action="#{/binderPlaceOrder/new-binderPlaceOrder}" th:object="${addNewBinderPlaceOrder}" method="post">
<div class="form-group">
<label>Book</label>
<select class="form-control" th:field="*{binderOrderItemDetails.book}">
<option th:if="${book} == null" value=" " >Select Book</option>
<option th:each="book : ${allBook}"
th:value="${book.id}"
th:text="${book.name}">
</option>
</select>
</div>
<form>
Here is the controller,
#Controller
#RequestMapping("/binderPlaceOrder")
public class BinderPlaceOrderController{
#Autowired
BinderPlaceOrderService binderPlaceOrderService;
#Autowired
BookService bookService;
#RequestMapping(value="/new-binderPlaceOrder", method = RequestMethod.GET)
public String newBinderPlaceOrder(Model model){
model.addAttribute("addNewBinderPlaceOrder", new BinderPlaceOrder());
model.addAttribute("allBook", bookService.getAllBooks();
model.addAttribute("addNewBinderOrderItemDetails", new BinderOrderItemDetails());
return "user/binderPlaceOrder/new";
}
}
During run time I get the below error
org.springframework.beans.NotReadablePropertyException: Invalid property 'binderOrderItemDetails.book' of bean class [PublisherInventory.model.user.BinderPlaceOrder]: Bean property 'binderOrderItemDetails.book' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
Below are the classes.
Please note, every class has their own Id property along with other properties. For readability those are omitted.
Here is BinderPlaceOrder Class,
#Entity
public class BinderPlaceOrder implements Comparator<BinderPlaceOrder> {
#OneToMany(mappedBy = "binderPlaceOrder", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<BinderOrderItemDetails> binderOrderItemDetails;
public List<BinderOrderItemDetails> getBinderOrderItemDetails() {
return binderOrderItemDetails;
}
public void setBinderOrderItemDetails(List<BinderOrderItemDetails> binderOrderItemDetails) {
this.binderOrderItemDetails = binderOrderItemDetails;
}
}
Here is BinderOrderItemDetails class
#Entity
#Indexed
public class BinderOrderItemDetails {
#OneToOne(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
#JoinColumn(name="bookId")
private Book book;
#ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinColumn(name="binderPlaceOrderId")
private BinderPlaceOrder binderPlaceOrder;
public Book getBook() { return book; }
public void setBook(Book book) { this.book = book; }
public BinderPlaceOrder getBinderPlaceOrder() { return binderPlaceOrder; }
public void setBinderPlaceOrder(BinderPlaceOrder binderPlaceOrder) {
this.binderPlaceOrder = binderPlaceOrder; }
}
Here is the Book Class
#Entity
#Indexed
public class Book implements Comparator<Book> {
#Column(name = "name")
#NotNull
#NotBlank
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name;}
}
Can you please tell me of what I am doing wrong or how it can be solved?
Thanks in advance.
As #JBNizet pointed out, your BinderPlaceOrder has
public List<BinderOrderItemDetails> getBinderOrderItemDetails() {
return binderOrderItemDetails;
}
which is a list, hence
th:field="*{binderOrderItemDetails.book}"
would not be correct,
but say you want to insert the first element,
th:field="${binderOrderItemDetails[0].book}"
Related
I am trying to map a collection of objects in Spring MVC but its giving error
Mapping of String is working fine but could not map a collection
org.springframework.beans.NotReadablePropertyException: Invalid property 'familyHistory[0].relation' of bean class [com.medicine.yourmedics.model.FamilyHistoryForm]: Field 'familyHistory[0].relation' does not exist
My Jsp file looks like
<form:form action="familyhistory" modelAttribute="familyhistoryform" method="POST" name="familyHistoryForm">
<table id="tblData">
<c:forEach items="${familyhistoryform.familyHistory}" varStatus="i">
<form:input path="familyHistory[${i.index}].relation" type="text" id="relation${i.index}"/>
</c:forEach>
The familyhistoryform is a wrapper around the familyHistory class.
public class FamilyHistoryForm {
public List<FamilyHistory> familyHistory = new LinkedList<FamilyHistory>();
public List<FamilyHistory> getFamilyHistory() {
return familyHistory;
}
public void setFamilyHistory(List<FamilyHistory> familyHistory) {
this.familyHistory = familyHistory;
}}
Family history pojo looks like
public class FamilyHistory {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id", unique = true, nullable = false)
private int id;
private String relation;
public String getRelation() {
return relation;
}
public void setRelation(String relation) {
this.relation = relation;
}}
Just for testing purpose have created a controller which returns a list of familyhistory objects
#RequestMapping(method = RequestMethod.GET, value = "/familyhistory")
public String viewRegistration(Map<String, Object> model,
HttpServletRequest request) {
List<FamilyHistory> familyHistoryList = new LinkedList<FamilyHistory>();
FamilyHistoryForm familyHistoryForm = new FamilyHistoryForm();
familyHistoryList.add(new FamilyHistory());
familyHistoryList.add(new FamilyHistory());
familyHistoryList.add(new FamilyHistory());
familyHistoryList.add(new FamilyHistory());
familyHistoryForm.setFamilyHistory(familyHistoryList);
model.put("familyhistoryform", familyHistoryForm);
return "familyhistory";
}
If in the jsp I write the path for the form input as path="familyHistory" then it prints the string array of familyhistory objects in the input text
[com.medicine.yourmedics.model.FamilyHistory#472c6818,
com.medicine.yourmedics.model.FamilyHistory#34662429,
com.medicine.yourmedics.model.FamilyHistory#1dd01a9f,
com.medicine.yourmedics.model.FamilyHistory#4983cc03]
I have a simple model class Product which exhibits a many to one relationship with ProductCategory:
Product class:
#Entity
#Table(name="product")
public class Product {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private Long id;
#Column(name="name")
private String name;
#Column(name="description")
private String description;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="category_id")
private ProductCategory category;
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 String getPdfUrl() {
return pdfUrl;
}
public void setPdfUrl(String pdfUrl) {
this.pdfUrl = pdfUrl;
}
public ProductCategory getCategory() {
return category;
}
public void setCategoryId(ProductCategory category) {
this.category = category;
}
}
ProductCategory class
#Entity
#Table(name="product_category",uniqueConstraints={#UniqueConstraint(columnNames="name")})
public class ProductCategory {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private Long id;
#Column(name="name")
private String name;
#OneToMany(fetch=FetchType.LAZY, mappedBy="category")
private Set<Product> products = new HashSet<Product>(0);
// getters() & setters()
}
I am using Spring boot with Thymeleaf to create the necessary forms for the usual CRUD operations.
Here is the essential portion of my html page which I use to add a new Product object into the database.
<form action="#" th:action="/product/save" th:object="${newProduct}" method="POST">
<input type="text" th:field="*{name}" />
<input type="text" th:field="*{description}" />
<select th:field="*{category}">
<option th:each="category: ${productCategories}" th:value="${category}" th:text="${category.name}" />
</select>
<button type="submit">Submit</button>
</form>
The problem is, when I try and insert the resulting Product object from the controller (I know I haven't shown it here, mostly because I don't think that is actually the cause of the problem), there is a
MySQLIntegrityConstraintViolationException: Column 'category_id' cannot be null
I have tried changing the value of the option to ${category.id}, but even that doesn't fix it.
In a nutshell
How do I actually pass a complex object as a POST parameter into a controller using Thymeleaf?
Update
Contrary to my first thoughts, this might actually be related to my Controller, so here is my ProductController:
#RequestMapping(value="/product/save", method=RequestMethod.POST)
public String saveProduct(#Valid #ModelAttribute("newProduct") Product product, ModelMap model) {
productRepo.save(product);
model.addAttribute("productCategories", productCategoryRepo.findAll());
return "admin-home";
}
#RequestMapping(value="/product/save")
public String addProduct(ModelMap model) {
model.addAttribute("newProduct", new Product());
model.addAttribute("productCategories", productCategoryRepo.findAll());
return "add-product";
}
Note that I have changed the form method to POST.
From thymeleafs perspective I can assure the below code should work.
<form method="POST" th:action="#{/product/save}" th:object="${newProduct}">
....
<select th:field="*{category}" class="form-control">
<option th:each="category: ${productCategories}" th:value="${category.id}" th:text="${category.name}"></option>
</select>
Provided that your controller looks like this.
#RequestMapping(value = "/product/save")
public String create(Model model) {
model.addAttribute("productCategories", productCategoryService.findAll());
model.addAttribute("newproduct", new Product()); //or try to fetch an existing object
return '<your view path>';
}
#RequestMapping(value = "/product/save", method = RequestMethod.POST)
public String create(Model model, #Valid #ModelAttribute("newProduct") Product newProduct, BindingResult result) {
if(result.hasErrors()){
//error handling
....
}else {
//or calling the repository to save the newProduct
productService.save(newProduct);
....
}
}
Update
Your models should have proper getters and setters with the correct names. For example, for the property category You should have,
public ProductCategory getCategory(){
return category;
}
public void setCategory(productCategory category){
this.category = category;
}
NOTE - I have not compiled this code, I got it extracted from my current working project and replace the names with your class names
I generated a form:
<form:form action="${contextPath}/draw/constraints.do" method="post" modelAttribute="order"> <c:forEach items="${order.myDrawsAsArray}" var="draw" varStatus="status">
<label class="radio-inline"><form:radiobutton path="myDrawsAsArray[${status.index}].readable" value="true" /> yes</label>
<label class="radio-inline"><form:radiobutton path="myDrawsAsArray[${status.index}].readable" value="false" /> no</label>
</c:forEach></form:form>
When I submit it to update my entities, I got the following exception:
org.springframework.web.util.NestedServletException: Request
processing failed; nested exception is
org.springframework.beans.InvalidPropertyException: Invalid property
'myDrawsAsArray[0]' of bean class [com.entity.Order3d]: Getter
for property 'myDrawsAsArray' threw exception; nested exception is
java.lang.reflect.InvocationTargetException
org.springframework.beans.InvalidPropertyException: Invalid property
'myDrawsAsArray[0]' of bean class [com.entity.Order3d]: Getter
for property 'myDrawsAsArray' threw exception; nested exception is
java.lang.reflect.InvocationTargetException
java.lang.reflect.InvocationTargetException
java.lang.NullPointerException
com.entity.Order3d.getMyDrawsAsArray(Order3d.java:121)
My controller is like this:
#Controller
#RequestMapping("/draw")
public class PrintingController {
#RequestMapping(value="/constraints")
public String constraints(
#ModelAttribute Order3d order,
#RequestParam("order") int id,
#RequestParam(value="save", required=false) String save,
Model m) {
Session s=HibernateUtils.getSessionFactory().openSession();
if(save!=null) {
System.out.println(order.getMyDraws());
for(DrawFile df : order.getMyDraws())
s.saveOrUpdate(df);
}
Order3d o=(Order3d)s.createCriteria(Order3d.class).add(Restrictions.eq("id", id)).uniqueResult();
m.addAttribute("order", o);
s.close();
return "3dconstraints";
}
}
I also post my entities if you need them:
#Entity
#Table (name="order3d")
public class Order3d implements Serializable {
private static final long serialVersionUID = -2241346447352903470L;
public enum State {DEMAND, ESTIMATED, PAYED, PENDING, PRODUCED, SENT, DELIVERED};
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column (name="id")
private int id;
#OneToMany(mappedBy="order3d", fetch = FetchType.EAGER, cascade=CascadeType.ALL)
private Set<DrawFile> myDraws;
public Set<DrawFile> getMyDraws() {
return myDraws;
}
public List<DrawFile> getMyDrawsAsList() {
return new ArrayList<DrawFile>(myDraws);
}
public Object[] getMyDrawsAsArray() {
return myDraws.toArray(); //line 121
}
//other getters & setters
public Order3d() {}
}
#Entity
#Table (name="draw", uniqueConstraints=#UniqueConstraint(columnNames="hashname"))
public class DrawFile implements Serializable {
private static final long serialVersionUID = -9024754876558087847L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column (name="id")
private int id;
#Column (name="hashname", columnDefinition="CHAR(64)")
private String hashname;
#Column (name="filename")
private String filename="";
#Column (name="readable", columnDefinition = "BIT", length = 1)
private Boolean readable;
//getters & setters
public DrawFile() {}
}
I searched on the web but I didn't find a solution. Any idea?
How about try adding getter/setter to the fields in both Order3d and DrawFile classes?
The getters and setters must match field name, if the field is
List<DrawFile> myDraws;
then the getter/setter must be: (it cannot be getMyDrawsAsList())
public List<DrawFile> getMyDraws() {
return myDraws;
}
public void setMyDraws(List<DrawFile> myDraws) {
this.myDraws = myDraws;
}
In a spring mvc web application using hibernate in eclipse and tomcat server, I changed a couple of text fields to drop down lists in a jsp, so that a person's gender and race can each be selected from its own drop down menu. I was careful to change other levels of the application, including setting up joined tables for gender and race in the underlying database, and changing code in the model and repository levels. The application compiles, and the jsp loads with the correct selected values for the selected person in each dropdown list, but clicking the submit/update button causes a BindingResult.hasErrors() problem which does not help me localize the cause of the problem.
Can someone help me find the cause of the failure to process the update?
Here is the processUpdatePatientForm() method that is called in the controller class. Note that it triggers the System.out.println() which shows that BindingResult.hasErrors() and returns the jsp:
#RequestMapping(value = "/patients/{patientId}/edit", method = RequestMethod.PUT)
public String processUpdatePatientForm(#Valid Patient patient, BindingResult result, SessionStatus status) {
if (result.hasErrors()) {
System.out.println(":::::::::::::::: in PatientController.processUpdatePatientForm() result.hasErrors() ");
List<ObjectError> errors = result.getAllErrors();
for(int i=0;i<result.getErrorCount();i++){System.out.println("]]]]]]] error "+i+" is: "+errors.get(i).toString());}
return "patients/createOrUpdatePatientForm";}
else {
this.clinicService.savePatient(patient);
status.setComplete();
return "redirect:/patients?patientID=" + patient.getId();
}
}
When the jsp is returned, the following error messages are included:
//This is printed out in my jsp below the Sex drop down list:
Failed to convert property value of type java.lang.String to required type org.springframework.samples.knowledgemanager.model.Gender for property sex; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.springframework.samples.knowledgemanager.model.Gender] for property sex: no matching editors or conversion strategy found
//This is printed out in my jsp below the Race drop down list:
Failed to convert property value of type java.lang.String to required type org.springframework.samples.knowledgemanager.model.Race for property race; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.springframework.samples.knowledgemanager.model.Race] for property race: no matching editors or conversion strategy found
The following is all that is printed in the eclipse console:
Hibernate: select gender0_.id as id1_2_, gender0_.name as name2_2_ from gender gender0_ order by gender0_.name
Hibernate: select race0_.id as id1_7_, race0_.name as name2_7_ from race race0_ order by race0_.name
:::::::::::::::: in PatientController.processUpdatePatientForm() result.hasErrors()
]]]]]]] error 0 is: Field error in object 'patient' on field 'race': rejected value [Hispanic]; codes [typeMismatch.patient.race,typeMismatch.race,typeMismatch.org.springframework.samples.knowledgemanager.model.Race,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [patient.race,race]; arguments []; default message [race]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'org.springframework.samples.knowledgemanager.model.Race' for property 'race'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.springframework.samples.knowledgemanager.model.Race] for property 'race': no matching editors or conversion strategy found]
]]]]]]] error 1 is: Field error in object 'patient' on field 'sex': rejected value [Male]; codes [typeMismatch.patient.sex,typeMismatch.sex,typeMismatch.org.springframework.samples.knowledgemanager.model.Gender,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [patient.sex,sex]; arguments []; default message [sex]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'org.springframework.samples.knowledgemanager.model.Gender' for property 'sex'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.springframework.samples.knowledgemanager.model.Gender] for property 'sex': no matching editors or conversion strategy found]
Note that the values [Hispanic] and [Male] are shown in the error message as triggering the error. The problem might be that the name property of Gender and Race is being passed to Spring MVC, when the id property should be passed instead. But how do I fix this in the code?
Can someone help me get to the bottom of this? The first step would be how can I get a more useful error message which locates the location in my code where the problem is being triggered.
EDIT:
Per Sotirios's request, the following is my form in the jsp:
<form:form modelAttribute="patient" method="${method}" class="form-horizontal" id="add-patient-form">
<petclinic:inputField label="First Name" name="firstName"/>
<petclinic:inputField label="Middle Initial" name="middleInitial"/>
<petclinic:inputField label="Last Name" name="lastName"/>
<div class="control-group">
<petclinic:selectField label="Sex" name="sex" names="${genders}" size="5"/>
</div>
<petclinic:inputField label="Date of Birth" name="dateOfBirth"/>
<div class="control-group">
<petclinic:selectField label="Race" name="race" names="${races}" size="5"/>
</div>
<div class="form-actions">
<c:choose>
<c:when test="${patient['new']}">
<button type="submit">Add Patient</button>
</c:when>
<c:otherwise>
<button type="submit">Update Patient</button>
</c:otherwise>
</c:choose>
</div>
</form:form>
And the Patient.java class is:
#Entity
#Table(name = "patients")
public class Patient extends BaseEntity {
#OneToMany(cascade = CascadeType.ALL, mappedBy = "patient", fetch=FetchType.EAGER)
private Set<Document> documents;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "patient", fetch=FetchType.EAGER)
private Set<Address> addresses;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "patient", fetch=FetchType.EAGER)
private Set<PhoneNumber> phonenumbers;
#Column(name = "first_name")
#NotEmpty
protected String firstName;
#Column(name = "middle_initial")
protected String middleInitial;
#Column(name = "last_name")
#NotEmpty
protected String lastName;
#ManyToOne
#JoinColumn(name = "sex_id")
protected Gender sex;
#Column(name = "date_of_birth")
#Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
#DateTimeFormat(pattern = "yyyy/MM/dd")
protected DateTime dateOfBirth;
#ManyToOne
#JoinColumn(name = "race_id")
protected Race race;
////////////// Document methods
protected void setDocumentsInternal(Set<Document> documents) {this.documents = documents;}
public Set<Document> getFaxes() {
Set<Document> faxes = new HashSet<Document>();
for (Document doc : getDocumentsInternal()) {if (doc.getType().getName().equals("ScannedFaxes")) {faxes.add(doc);}}
return faxes;
}
public Set<Document> getForms() {
Set<Document> forms = new HashSet<Document>();
for (Document doc : getDocumentsInternal()) {if (doc.getType().getName().equals("ScannedPatientForms")) {forms.add(doc);}}
return forms;
}
protected Set<Document> getDocumentsInternal() {
if (this.documents == null) {this.documents = new HashSet<Document>();}
return this.documents;
}
public List<Document> getDocuments() {
List<Document> sortedDocuments = new ArrayList<Document>(getDocumentsInternal());
PropertyComparator.sort(sortedDocuments, new MutableSortDefinition("name", true, true));
return Collections.unmodifiableList(sortedDocuments);
}
public void addDocument(Document doc) {
getDocumentsInternal().add(doc);
doc.setPatient(this);
}
public Document getDocument(String name) {return getDocument(name, false);}
/** Return the Document with the given name, or null if none found for this Patient.
* #param name to test
* #return true if document name is already in use
*/
public Document getDocument(String name, boolean ignoreNew) {
name = name.toLowerCase();
for (Document doc : getDocumentsInternal()) {
if (!ignoreNew || !doc.isNew()) {
String compName = doc.getName();
compName = compName.toLowerCase();
if (compName.equals(name)) {
return doc;
}
}
}
return null;
}
//////////// Address methods
protected void setAddressesInternal(Set<Address> addresses) {this.addresses = addresses;}
protected Set<Address> getAddressesInternal() {
if (this.addresses == null) {this.addresses = new HashSet<Address>();}
return this.addresses;
}
public List<Address> getAddresses() {
List<Address> sortedAddresses = new ArrayList<Address>(getAddressesInternal());
PropertyComparator.sort(sortedAddresses, new MutableSortDefinition("address", true, true));
return Collections.unmodifiableList(sortedAddresses);
}
public void addAddress(Address addr) {
getAddressesInternal().add(addr);
addr.setPatient(this);
}
public Address getAddress(String address) {return getAddress(address, false);}
/** Return the Address with the given name, or null if none found for this Patient.
* #param name to test
* #return true if document name is already in use
*/
public Address getAddress(String addr, boolean ignoreNew) {
addr = addr.toLowerCase();
for (Address address1 : getAddressesInternal()) {
if (!ignoreNew || !address1.isNew()) {
String compName = address1.getAddress();
compName = compName.toLowerCase();
if (compName.equals(addr)) {
return address1;
}
}
}
return null;
}
//////////// PhoneNumber methods
protected void setPhoneNumbersInternal(Set<PhoneNumber> phonenumbers) {this.phonenumbers = phonenumbers;}
protected Set<PhoneNumber> getPhoneNumbersInternal() {
if (this.phonenumbers == null) {this.phonenumbers = new HashSet<PhoneNumber>();}
return this.phonenumbers;
}
public List<PhoneNumber> getPhoneNumbers() {
List<PhoneNumber> sortedPhoneNumbers = new ArrayList<PhoneNumber>(getPhoneNumbersInternal());
PropertyComparator.sort(sortedPhoneNumbers, new MutableSortDefinition("phonenumber", true, true));
return Collections.unmodifiableList(sortedPhoneNumbers);
}
public void addPhoneNumber(PhoneNumber pn) {
getPhoneNumbersInternal().add(pn);
pn.setPatient(this);
}
public PhoneNumber getPhoneNumber(String pn) {return getPhoneNumber(pn, false);}
/** Return the PhoneNumber with the given name, or null if none found for this Patient.
* #param name to test
* #return true if phone number is already in use
*/
public PhoneNumber getPhoneNumber(String pn, boolean ignoreNew) {
pn = pn.toLowerCase();
for (PhoneNumber number : getPhoneNumbersInternal()) {
if (!ignoreNew || !number.isNew()) {
String compName = number.getPhonenumber();
compName = compName.toLowerCase();
if (compName.equals(pn)) {
return number;
}
}
}
return null;
}
public String getFirstName(){return this.firstName;}
public void setFirstName(String firstName){this.firstName = firstName;}
public String getMiddleInitial() {return this.middleInitial;}
public void setMiddleInitial(String middleinitial) {this.middleInitial = middleinitial;}
public String getLastName() {return this.lastName;}
public void setLastName(String lastName) {this.lastName = lastName;}
public Gender getSex() {return this.sex;}
public void setSex(Gender sex) {this.sex = sex;}
public void setDateOfBirth(DateTime birthDate){this.dateOfBirth = birthDate;}
public DateTime getDateOfBirth(){return this.dateOfBirth;}
public Race getRace() {return this.race;}
public void setRace(Race race) {this.race = race;}
#Override
public String toString() {
return new ToStringCreator(this)
.append("id", this.getId())
.append("new", this.isNew())
.append("lastName", this.getLastName())
.append("firstName", this.getFirstName())
.append("middleinitial", this.getMiddleInitial())
.append("dateofbirth", this.dateOfBirth)
.toString();
}
}
SECOND EDIT:
Per Alexey's comment, the following is the method in the controller class which has always had the #InitBinder annotation. It is identical to a method in the controller of a similar module which works:
#InitBinder
public void setAllowedFields(WebDataBinder dataBinder) {dataBinder.setDisallowedFields("id");}
THIRD EDIT:
PatientController.java:
#Controller
#SessionAttributes(types = Patient.class)
public class PatientController {
private final ClinicService clinicService;
#Autowired
public PatientController(ClinicService clinicService) {this.clinicService = clinicService;}
#ModelAttribute("genders")
public Collection<Gender> populateGenders() {return this.clinicService.findGenders();}
#ModelAttribute("races")
public Collection<Race> populateRaces() {return this.clinicService.findRaces();}
#InitBinder
public void setAllowedFields(WebDataBinder dataBinder) {dataBinder.setDisallowedFields("id");}
#RequestMapping(value = "/patients/new", method = RequestMethod.GET)
public String initCreationForm(Map<String, Object> model) {
Patient patient = new Patient();
model.put("patient", patient);
return "patients/createOrUpdatePatientForm";
}
#RequestMapping(value = "/patients/new", method = RequestMethod.POST)
public String processCreationForm(#Valid Patient patient, BindingResult result, SessionStatus status) {
if (result.hasErrors()) {return "patients/createOrUpdatePatientForm";}
else {
this.clinicService.savePatient(patient);
status.setComplete();
return "redirect:/patients?patientID=" + patient.getId();
}
}
#RequestMapping(value = "/patients", method = RequestMethod.GET)
public String processFindForm(#RequestParam("patientID") String patientId, Patient patient, BindingResult result, Map<String, Object> model) {
Collection<Patient> results = this.clinicService.findPatientByLastName("");
model.put("selections", results);
int patntId = Integer.parseInt(patientId);
Patient sel_patient = this.clinicService.findPatientById(patntId);//I added this
model.put("sel_patient",sel_patient);
return "patients/patientsList";
}
#RequestMapping(value = "/patients/{patientId}/edit", method = RequestMethod.GET)
public String initUpdatePatientForm(#PathVariable("patientId") int patientId, Model model) {
Patient patient = this.clinicService.findPatientById(patientId);
model.addAttribute(patient);
return "patients/createOrUpdatePatientForm";
}
#RequestMapping(value = "/patients/{patientId}/edit", method = RequestMethod.PUT)
public String processUpdatePatientForm(#Valid Patient patient, BindingResult result, SessionStatus status) {
if (result.hasErrors()) {
System.out.println(":::::::::::::::: in PatientController.processUpdatePatientForm() result.hasErrors() ");
List<ObjectError> errors = result.getAllErrors();
for(int i=0;i<result.getErrorCount();i++){System.out.println("]]]]]]] error "+i+" is: "+errors.get(i).toString());}
return "patients/createOrUpdatePatientForm";}
else {
this.clinicService.savePatient(patient);
status.setComplete();
return "redirect:/patients?patientID=" + patient.getId();
}
}
}
FOURTH EDIT:
Gender.java
#Entity
#Table(name = "gender")
public class Gender extends NamedEntity {}
NamedEntity.java:
#MappedSuperclass
public class NamedEntity extends BaseEntity {
#Column(name = "name")
private String name;
public void setName(String name) {this.name = name;}
public String getName() {return this.name;}
#Override
public String toString() {return this.getName();}
}
BaseEntity.java:
#MappedSuperclass
public class BaseEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
protected Integer id;
public void setId(Integer id) {this.id = id;}
public Integer getId() {return id;}
public boolean isNew() {return (this.id == null);}
}
You need to add a converter or a proper editor. I prefer the first one. Refer to section 6.5. on this page for the details.
Your converter would have to get the Entity with the given name from the database and return it. The code would be something like this:
class StringToGender implements Converter<String, Gender> {
#Autowired
private GenderRepository repository;
public Gender convert(String name) {
return repository.getGenderByName(name);
}
}
And in your application context xml (if you use xml):
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="org.example.StringToGender"/>
</set>
</property>
I have Entity class Examination and it's connected with Entity class Student as ManyToOne. And examination is connected with Subject as ManyToOne.
I JSP file I sent corresponding input to Controller. But when I try to sent it I have an error (bad request). I found out the reason why it happens. In Examination I have fields:
examinationMark, student, subject and examinationId. examinationId generates automatically. Other fields I enter in JSP. When i try to pass values of student and subject to examination in controller using Ajax i have an error. But when i pass only examinationMark it's ok. I do not know why it happens.
#Entity
#Table(name = "Examination")
public class Examination implements Serializable {
public Examination() {}
public Examination(String examinationMark) {
this.examinationMark = examinationMark;
}
// create connectivity with table Student
private Student student;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "StudentID")
public Student getStudent() {
return this.student;
}
public void setStudent(Student student) {
this.student = student;
}
// create connectivity with table Subject
private Subject subject;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "SubjectId")
public Subject getSubject() {
return subject;
}
public void setSubject(Subject subject) {
this.subject = subject;
}
Subject entity class
#Entity
#Table(name = "Subject")
public class Subject implements Serializable {
public Subject() {}
public Subject(String subjectTitle, int subjectHours) {
this.subjectTitle = subjectTitle;
this.subjectHours = subjectHours;
}
// create connectivity with table Examination
private Set<Examination> examinations;
#OneToMany(mappedBy = "subject", cascade = CascadeType.ALL, orphanRemoval = true)
public Set<Examination> getExaminations() {
return examinations;
}
public void setExaminations(Set<Examination> examinations) {
this.examinations = examinations;
}
Student Entity class
#Entity
#Table(name = "Student")
public class Student implements Serializable {
public Student() {}
public Student(String studentFullName, String studentBook,
int studentEnter, String studentOKR) {
this.studentFullName = studentFullName;
this.studentBook = studentBook;
this.studentEnter =studentEnter;
this.studentOKR = studentOKR;
}
// create connectivity with table Examination
private Set<Examination> examinations = new HashSet<Examination>();
#OneToMany(mappedBy = "student",cascade = CascadeType.ALL, orphanRemoval = true)
public Set<Examination> getExaminations() {
return examinations;
}
public void setExaminations(Set<Examination> examinations) {
this.examinations = examinations;
}
Controller's methods
#RequestMapping(value = "/studentProfileEdit.html", method = RequestMethod.GET)
public ModelAndView getStudentProfile() {
ModelAndView mav = new ModelAndView("studentProfileEdit"); // create MVC object
// to pass it to JSP page
mav.getModelMap().put("student", sts.selectStudentByName("name"));
return mav;
}
#RequestMapping(value = "/studentProfileEdit.html", method = RequestMethod.POST)
public #ResponseBody String editStudentProfile( #ModelAttribute(value = "examination") Examination examination) {
return "";
}
JSP file
<div id="examPart">
<label>Subject</label>
<select id="subject">
<c:forEach var="s" items="${subjects}">
<option value="${s.subjectTitle}" >${s.subjectTitle}</option>
</c:forEach>
</select>
<br/>
<label>Exam mark</label>
<input id="examinationMark" />
<input type="submit" value="Add exam" onclick="addExam()" />
<div id="exam" style="color:green"></div>
</div>
and Ajax function
function addExam() {
var examinationMark = $('#examinationMark').val();
var subject = $('#subject');
var student = '${student}';
$.ajax({
type: "POST",
url: "/IRSystem/studentProfileEdit.html",
data: "examinationMark=" + examinationMark +
"&student=" + student +
"&subject=" + subject ,
success: function(response) {
$('#exam').html(response);
$('#examinationMark').val('');
},
error: function(e) {
alert('Error' + e);
}
});
}