Hibernate Entity and Ajax - java

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);
}
});
}

Related

How to send only the ID the of main nested objects in the body request in spring boot

I'm creating eCommerce for merchants using spring boot with JPA.
I have an issue while creating the order service.
I want to only pass the ID of the nested objects in the request body instead of sending the full nest objects because the size will be extremely big.
Here is my code.
Merchant can do many orders
Order
#Entity
#Table(name = "Orders")
#XmlRootElement
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Order extends BasicModelWithIDInt {
#Basic(optional = false)
#Column(name = "Quantity")
private Integer quantity;
#Basic(optional = false)
#Size(min = 1, max = 150)
#Column(name = "Notes")
private String notes;
#JoinColumn(name = "ProductID", referencedColumnName = "ID")
#ManyToOne(optional = false, fetch = FetchType.LAZY)
#JsonIgnoreProperties
private Product productID;
#JoinColumn(name = "MerchantID", referencedColumnName = "ID")
#ManyToOne(optional = false, fetch = FetchType.LAZY)
private Merchent merchent;
#JoinColumn(name = "OrderSatusID", referencedColumnName = "ID")
#ManyToOne(optional = false, fetch = FetchType.EAGER)
private OrderStatus orderStatus;
// Getters and Setters
}
Order Holder
public class OrderHolder {
#NotNull
private Order order;
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
}
OrderRepo
public interface OrderRepo extends JpaRepository<Order, Integer> {
}
Order Controller
#RestController
#RequestMapping(value = "order", produces = MediaType.APPLICATION_JSON_VALUE)
public class OrderRestController extends BasicController<OrderHolder>{
#Autowired
private OrderRepo orderRepo;
#PostMapping("create")
public ResponseEntity<?> create(#RequestBody #Valid OrderHolder orderHolder, Principal principal) throws GeneralException {
log.debug( "create order {} requested", orderHolder.toString());
Order order = new Order();
order = orderHolder.getOrder();
System.out.println("###############"+order);
try {
order = orderRepo.save(order);
log.info( "Order {} has been created", order );
} catch (Exception e) {
log.error( "Error creating Order: ", e );
e.printStackTrace();
throw new GeneralException( Errors.ORDER_CREATION_FAILURE, e.toString() );
}
return ResponseEntity.ok( order );
}
}
I need request body to look like the below instead of including the full Merchant and Product objects inside the request.
You can make use of JsonView to return only id of product and merchant
public class OrderView {}
...
public class Product{
#Id
#JsonView(OrderView.class)
private Integer id
private String otherFieldWithoutJsonView
...
}
and then in your controller
#PostMapping("create")
#JsonView(OrderView.class) // this will return the product object with one field (id)
public ResponseEntity<?> create(#RequestBody #Valid OrderHolder orderHolder, Principal principal) throws GeneralException {
...
}
hope this can help you
Just have a separate contract class.
public class OrderContract {
private int merchantID;
private String notes;
....
//getter, setters
}
public class OrderHolder {
#NotNull
private OrderContract orderContract;
public OrderContract getOrderContract() {
return orderContract;
}
public void setOrder(OrderContract orderContract) {
this.orderContract = orderContract;
}
}
And before making a call to the Repository , translate from OrderContract to Order.
I would like to share something regarding this.
I have searched a lot on internet and tried lot of things, but the solution given here suited well for this scenario.
https://www.baeldung.com/jackson-deserialization
You need to create a Custom-deserializer for your model by extending StdDeserializer from com.fasterxml.jackson.databind.deser.std.StdDeserializer, where you just want to pass id's and not the whole object in the request.
I have given below example for User Model with Address object.
User(long userId, String name, Address addressId)
Address(long addressId, String wholeAddress)
Writing Deserializer for User class
public class UserDeserializer extends StdDeserializer<User> {
public User() {
this(null);
}
public User Deserializer(Class<?> vc) {
super(vc);
}
#Override
public User deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JacksonException {
JsonNode node = p.getCodec().readTree(p);
long id = 0;
long addressId = (Long) ((IntNode) node.get("addressId")).numberValue().longValue();
return new User(id, name, new Address(addressId, null)
}
Now you have to use
#JsonDeserialize(using = UserDeserializer.class)
public Class User {
...
}
POST request
Before custom deserialization
{
"name" : "Ravi",
"addressId" : { "id" : 1}
}
After custom Deserialization
{
"name" : "Ravi",
"addressId" : 1
}
Also while GET /user/:id call you will get the whole obj like
{
"name" : "Ravi",
"addressId" : { "id" : 1, "wholeAddress" : "Some address"}
}

org.springframework.beans.NotReadablePropertyException:

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}"

How to remove object from Autopopulate list in spring

I am new to spring + hibernate. When I add a customer and its destinations (one to many relationship), everything is fine. But when I update the customer's destination, all previous destinations remain in the database with a null customer foreign key.
Suppose I insert 4 destinations a, b, c, d. After updating the customer, I insert x, y. Then it stores total 6 destinations: a, b, c, d with null references and x, y with customer references.
Here is my code:
1). Customer Entity
Has one-to-many relationship with destination and relationship is unidirectional.
#Entity
#Table(name="customers")
#Proxy(lazy=false)
public class CustomerEntity {
#Id
#Column(name="id")
#GeneratedValue
private Integer id;
private String description;
private String panNo;
private String cstNo;
private String vatNo;
#OneToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
#JoinColumn(name = "customer_id", referencedColumnName = "id")
public List<DestinationsEntity> destination = new AutoPopulatingList<DestinationsEntity>(DestinationsEntity.class);
//getter and setters
}
2). Destination Entity
#Entity
#Table(name = "destinations")
#Proxy(lazy = false)
public class DestinationsEntity {
#Id
#Column(name = "id")
#GeneratedValue
private Integer id;
#Column(name="destination")
private String destination;
// getter and setter
}
1). AddCustomer.jsp
This code for adding more destinations in Autopopulate list
<div id="destination_container">
<div><textarea row="3" col="5" class="destination_address" name= "destination[${0}].destination" placeholder="Please enter address"></textarea></div>
</div>
<script type="text/javascript">
$(document).ready(function(){
var index = 1;
/*
* Add more destination
*/
$('#add_more_destination').click(function(){
$('#destination_container').append('<div><textarea row="3" col="5" class="destination_address" name= "destination[${"'+index+'"}].destination" placeholder="Please enter address"></textarea><span class="remove_dest">*</span></div>');
index++;
});
});
</script>
2). updateCustomer.jsp
All destinations added by customer is show here and he/she can be change destinations(like before inserted pune, mumbai , banglore) now updating destinations( delhi, punjab)
<c:set var="index" scope="page" value="${fn:length(destinationss)}"/>
<c:forEach items="${destinationss}" var="dest" varStatus="i">
<div>
<textarea class="destination_address" name= "destination[${i.index}].destination" placeholder="Please enter address">${dest.destination}</textarea><span class="remove_dest">*</span>
</div>
</c:forEach>
<button type ="button" id="add_more_destination">Add More Destinations</button>
<script type="text/javascript">
$(document).ready(function(){
/*
* Add a destination
*/
var index = ${index};
$('#add_more_destination').click(function(){
$('#destination_container').append('<div><textarea row="3" col="5" class="destination_address" name=destination["'+index+'"].destination placeholder="Please enter address"></textarea><span class="remove_dest">*</span></div>');
alert(index);
index++;
});
</script>
Controller
#RequestMapping(value = "/addCustomerForm", method = RequestMethod.GET)
public String addCustomerForm(ModelMap map) {
return "master/addCustomer";
}
#RequestMapping(value = "/addCustomer", method = RequestMethod.POST)
public String addCustomer(#ModelAttribute(value = "customer") CustomerEntity customer,BindingResult result, HttpServletRequest request) {
customerService.addCustomer(customer);
return "redirect:/customer";
}
Update Customer
This is new thing I tried last night. Problem is solved partially.
#ModelAttribute
public void updateOperation(HttpServletRequest request, ModelMap map) {
if(null !=request.getParameter("id"))
map.addAttribute("customer1", customerService.findOne(Integer.parseInt(request.getParameter("id"))));
}
#RequestMapping(value = "/updateCustomerForm/{customerId}", method = RequestMethod.GET)
public String updateCustomerForm(#PathVariable("customerId") Integer customerId, ModelMap map, HttpServletRequest request) {
CustomerEntity customerEntity = customerService.findOne(customerId);
map.addAttribute("customer", customerEntity);
map.addAttribute("destinationss",customerEntity.getDestination());
}
#RequestMapping(value = "/updateCustomer", method = RequestMethod.POST)
public String updateCustomer(#ModelAttribute(value = "customer1")CustomerEntity customer1,BindingResult result, HttpServletRequest request,HttpServletResponse response) {
customerService.updateCustomer(customer1);
return "redirect:/customer";
}
}
1). CustomerServiceImpl
public class CustomerServiceImpl implements CustomerService{
#Autowired
private CustomerDao customerDao;
#Override
#Transactional
public void addCustomer(CustomerEntity customer) {
customerDao.addCustomer(customer);
}
#Override
#Transactional
public CustomerEntity findOne(Integer id){
return customerDao.findOne(id);
}
#Override
#Transactional
public void updateCustomer(CustomerEntity customerEntity){
if (null != customerEntity) {
customerDao.updateCustomer(customerEntity);
}
}
}
2).CustomerDaoImpl
public class CustomerDaoImpl implements CustomerDao{
#Autowired
private SessionFactory sessionFactory;
#Override
#Transactional
public void addCustomer(CustomerEntity customer){
this.sessionFactory.getCurrentSession().save(customer);
}
#Override
public CustomerEntity findOne(Integer id){
return (CustomerEntity) sessionFactory.getCurrentSession().load(CustomerEntity.class, id);
}
#Override
#Transactional
public void updateCustomer(CustomerEntity customerEntity){
if (null != customerEntity) {
this.sessionFactory.getCurrentSession().update(customerEntity);
}
}
}
The issue is Spring will give you new Customer entity, so I guess the Destination entities in this Customer is empty initially. So in your update operation you are just adding some new Destination entities and then adding them to customer as per your code.
So in this case, the customer entity is having only the new Destination objects where as the already existing Destination entities which were mapped earlier are not present in your Customer entity.
To fix the issue, first get the Customer entity from database, then this entity will have the set of Destination objects. Now to this Customer you can add new Destination objects and also update the existing Destination objects if needed then ask Hibernate to do the update operation. In this case Hibernate can see your earlier destination objects and also the new destination objects and based on that it will run the insert & update queries.
The code looks something like this:
// First get the customer object from database:
Customer customer = (Customer) this.sessionFactory.getCurrentSession().get(Customer.class, customerId);
// Now add your destination objects, if you want you can update the existing destination entires here.
for (int i = 0; i < destinationAddrs.length; i++) {
DestinationsEntity destination = new DestinationsEntity();
destination.setDestination(destinationAddrs[i]);
customer.getDestinationEntity().add(destination);
}
// Then do the update operation
this.sessionFactory.getCurrentSession().update(customer);

Mapping happening for normal objects but not for list in spring mvc

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]

how do I locate cause of errors in BindingResult

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>

Categories