org.springframework.beans.NotReadablePropertyException - spring

In my web app, I want to build a registration form within which I wish to list all properties of a user's contact information that can be edited and saved. However, when I run my code, I get following error.
Any help will be greatly appreciated as I am new and learning as I go.
2019-01-03 17:09:58.705 ERROR 12223 --- [nio-8080-exec-5] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [An exception occurred processing JSP page /WEB-INF/views/enrollment/view.jsp at line 382
org.springframework.beans.NotReadablePropertyException: Invalid property 'contact' of bean class [com.intelo.model.Enrollment]: Bean property 'contact' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
Here is my view.jsp
<form:form id="editRegistration" action="/enrollment/action" modelAttribute="enrollment" method="post" enctype="multipart/form-data">
<input type="hidden" name="enrollmentId" value="${enrollment.id}">
...
<c:forEach items="${contacts}" var="contact">
<div class="form-group col-md-6">
<label class="control-label">First Name</label>
<form:input class="form-control" path="contact.firstName" disabled="${allowedActions.edit? 'false' : 'true'}"/>
</div>
</c:forEach>
Here is my EnrollmentControleller:
#GetMapping("/enrollment/view")
public String viewEnrollment(#ModelAttribute("enrollment") Enrollment enrollment, Model model,
#ModelAttribute("user") Member user)
{
StateManager stateManager = StateManager.getStateManager(enrollment);
model.addAttribute("hasActions", stateManager.allowedActions(user).size() > 0);
model.addAttribute("allowedActions", stateManager.allowedActionMap(user));
model.addAttribute("isAdministrator", stateManager.getRoleInContext(user).hasAdministratorPrivilege());
model.addAttribute("pageTitle", "View Enrollment");
RegistrationDetails registrationDetails = enrollment.getRegistrationDetails();
model.addAttribute("studentInformation", registrationDetails.getStudentInformation());
model.addAttribute("healthInformation", registrationDetails.getHealthInformation());
model.addAttribute("emergencyContact", registrationDetails.getEmergencyContact());
model.addAttribute("familyInformation", registrationDetails.getFamilyInformation());
model.addAttribute("schoolHistory", registrationDetails.getSchoolHistory());
model.addAttribute("contacts", registrationDetails.getContacts());
model.addAttribute("siblings", registrationDetails.getSiblings());
model.addAttribute("preferredSite", registrationDetails.getPreferredSite());
return "enrollment/view";
}
Enrollment class:
#Entity
#Table(name="enrollments")
#OnDelete(action = OnDeleteAction.CASCADE)
public class Enrollment extends ModelObject {
#JsonProperty("firstName")
private String firstName = "";
#JsonProperty("middleName")
private String middleName = "";
#JsonProperty("lastName")
private String lastName = "";
#JsonProperty("birthDate")
#DateTimeFormat(pattern="MM/dd/uuuu")
private LocalDate birthDate = LocalDate.now();
#JsonProperty("studentGrade")
private String studentGrade = null;
#JsonProperty("registrationDate")
#JsonDeserialize(using = LocalDateDeserializer.class)
#JsonSerialize(using = LocalDateSerializer.class)
#DateTimeFormat(pattern="MM/dd/uuuu")
private LocalDate registrationDate = LocalDate.now();
#JsonIgnore
#OneToOne(fetch=FetchType.LAZY, mappedBy="enrollment", cascade={CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE}, orphanRemoval=true)
#OnDelete(action = OnDeleteAction.CASCADE)
RegistrationDetails registrationDetails = null;
#JsonIgnore
#ManyToOne
#JoinColumn(name = "programId")
private Program program = null;
#JsonIgnore
#OrderBy("date")
#OneToMany (mappedBy = "enrollment", cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE})
#OnDelete(action = OnDeleteAction.CASCADE)
private List<AttendanceRecord> attendanceRecords = new ArrayList<AttendanceRecord>();
public Enrollment() {
super();
setType(this.getClass().getCanonicalName());
setState(State.DRAFT);
setRegistrationDetails(new RegistrationDetails());
}
public String getStudentGrade() {
return studentGrade;
}
public void setStudentGrade(String studentGrade) {
this.studentGrade = studentGrade;
}
public List<AttendanceRecord> getAttendance() {
return attendanceRecords;
}
public void addAttendanceRecord(AttendanceRecord attendanceRecord) {
attendanceRecords.add(attendanceRecord);
attendanceRecord.setEnrollment(this);
}
public void removeAttendanceRecord(AttendanceRecord attendanceRecord) {
attendanceRecords.remove(attendanceRecord);
attendanceRecord.setEnrollment(null);
}
public LocalDate getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(LocalDate registrationDate) {
this.registrationDate = registrationDate;
}
public Program getProgram() {
return program;
}
public void setProgram(Program program) {
this.program = program;
setParent(program);
}
#Override
public ParentContext getParentContext() {
return program;
}
public RegistrationDetails getRegistrationDetails() {
return registrationDetails;
}
public void setRegistrationDetails(RegistrationDetails registrationDetails) {
if (this.registrationDetails != null)
registrationDetails.setEnrollment(null);
this.registrationDetails = registrationDetails;
registrationDetails.setEnrollment(this);
}
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 String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public LocalDate getBirthDate() {
return birthDate;
}
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
}
Here is my Contact class
#Embeddable
public class Contact {
String firstName = "";
String lastName = "";
String email = "";
String homePhone = "";
String dayPhone = "";
String cellPhone = "";
String relationship = "";
#Embedded
#AttributeOverrides({
#AttributeOverride(name="street", column=#Column(name="contact_street")),
#AttributeOverride(name="apartment", column=#Column(name="contact_apartment")),
#AttributeOverride(name="city", column=#Column(name="contact_city")),
#AttributeOverride(name="state", column=#Column(name="contact_state")),
#AttributeOverride(name="zipCode", column=#Column(name="contact_zipcode")),
#AttributeOverride(name="country", column=#Column(name="contact_country"))
})
Address address = new Address();
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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getHomePhone() {
return homePhone;
}
public void setHomePhone(String homePhone) {
this.homePhone = homePhone;
}
public String getDayPhone() {
return dayPhone;
}
public void setDayPhone(String dayPhone) {
this.dayPhone = dayPhone;
}
public String getCellPhone() {
return cellPhone;
}
public void setCellPhone(String cellPhone) {
this.cellPhone = cellPhone;
}
public String getRelationship() {
return relationship;
}
public void setRelationship(String relationship) {
this.relationship = relationship;
}
public Address getAddress() {
return address;
}
}

Related

Spring validating a object before returning it in a function not working

I have a service, that gets an xml/json string, tries to read it as an pojo, then returns it. Then, I want to show the result in thymeleaf. I did that successfully, but - in the model I have validation annotations, but if I submit invalid information it accepts the value, although I validated the method. Here is my code:
Controller:
#Controller
public class ConvertController implements WebMvcConfigurer {
#Autowired
PrintJSON printJSON;
#Autowired
PrintXML printXML;
#Autowired
ReadJSON readJSON;
#Autowired
ReadXML readXML;
#GetMapping("/read")
public String showReadForm() {
return "read";
}
#PostMapping("/read")
public String read(#RequestParam(value = "convertFrom") String
convertFrom, String text, Model model){
if("json".equals(convertFrom)){
Book newBook = readJSON.read(text);
model.addAttribute("result", newBook);
return "converted";
}else if("xml".equals(convertFrom)){
Book newBook = readXML.read(text);
model.addAttribute("result", newBook);
return "converted";
}
return "read";
}
#GetMapping("/print")
public String showPrintForm(Book book){
return "convert";
}
#PostMapping("/print")
public String convert(#RequestParam(value = "convertTo") String
convertTo, #Valid Book book, Errors errors, Model model) {
if(errors.hasErrors()){
return "convert";
}
if("json".equals(convertTo)){
model.addAttribute("result", printJSON.getJSON(book));
return "converted";
}
if("xml".equals(convertTo)){
model.addAttribute("result", printXML.getXML(book));
return "converted";
}
return "convert";
}}
Service
public class ReadXML {
#Autowired
#Qualifier("XmlMapper")
XmlMapper xmlMapper;
#Valid
public Book read(String xml){
try{
#Valid Book book = xmlMapper.readValue(xml, Book.class);
return book;
}
catch(JsonProcessingException e){
e.printStackTrace();
return new Book();
}
}
}
Model
public class Book {
#NotEmpty
private String title;
private String description;
private Date publishDate;
private int ISBN;
private List<#Valid Author> authors;
#Override
public String toString(){
String bookString = String.format("Title: %s\nDescription: %s\nPublish Date: %s\nISBN: %s\nAuthor", title, description, publishDate, ISBN);
for(Author a : authors){
bookString += a.toString();
}
return bookString;
}
public String getTitle() {
return title;
}
public void setTitle(String title){
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description){
this.description = description;
}
public Date getPublishDate() {
return publishDate;
}
public void setPublishDate(String newPublishDate) throws ParseException {
Date publishDate = new SimpleDateFormat(Constants.dateFormat).parse(newPublishDate);
this.publishDate = publishDate;
}
public int getISBN() {
return ISBN;
}
public void setISBN(int ISBN){
this.ISBN = ISBN;
}
public void addAuthor(Author author) {
authors.add(author);
}
public List<Author> getAuthors(){
return authors;
}
}
Where is my problem???
Thank you!

Bidirectional OneToMany-ManyToOne Relationship referencing unsaved transient instance (Spring MVC - Thymeleaf)

new here. I'm new to Spring and Thymeleaf, I'm trying to learn by following a video and I don't know why I get the following exception (org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : org.launchcode.codingevents.models.Event.eventCategory -> org.launchcode.codingevents.models.EventCategory) when I try to creat an Event giving it an EventCategory in the Thymeleaf form. I tried cascading from one side, then from the other and then from both, but it didn't work.
I'll be immensely grateful with whoever helps me out.
Here's my code.
#MappedSuperclass
public abstract class AbstractEntity {
#Id
#GeneratedValue
private int id;
public int getId() {
return id;
}
#Override
public int hashCode() {
return Objects.hash(id);
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
AbstractEntity entity = (AbstractEntity) obj;
return this.id == entity.id;
}
#Entity
public class Event extends AbstractEntity {
#NotBlank(message = "Name is required")
#Size(min = 3, max = 50, message = "Name must be between 3 and 50 characters")
private String name;
#Size(max = 500, message = "Description too long!")
private String description;
#NotBlank(message = "Email is required")
#Email(message = "Invalid email. Try again")
private String contactEmail;
#ManyToOne
#NotNull(message = "Category is required")
private EventCategory eventCategory;
public Event() {
}
public Event(String name, String description, String contactEmail, EventCategory eventCategory) {
this.name = name;
this.description = description;
this.contactEmail = contactEmail;
this.eventCategory = eventCategory;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getContactEmail() {
return contactEmail;
}
public void setContactEmail(String contactEmail) {
this.contactEmail = contactEmail;
}
public EventCategory getEventCategory() {
return eventCategory;
}
public void setEventCategory(EventCategory eventCategory) {
this.eventCategory = eventCategory;
}
#Override
public String toString() {
return name;
}
#Entity
public class EventCategory extends AbstractEntity implements Serializable {
#Size(min = 3, message = "Name must be at least 3 characters long")
private String name;
#OneToMany(mappedBy = "eventCategory")
private final List<Event> events = new ArrayList<>();
public EventCategory() {
}
public EventCategory(#Size(min = 3, message = "Name must be at least 3 characters long") String name) {
this.name = name;
}
public List<Event> getEvents() {
return events;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return name;
#Controller
#RequestMapping("events")
public class EventController {
#Autowired
private EventRepository eventRepository;
#Autowired
private EventCategoryRepository eventCategoryRepository;
#GetMapping
public String displayAllEvents(#RequestParam(required = false) Integer categoryId, Model model) {
if (categoryId == null) {
model.addAttribute("title", "All Events");
model.addAttribute("events", eventRepository.findAll());
} else {
Optional<EventCategory> result = eventCategoryRepository.findById(categoryId);
if (!result.isPresent()) {
model.addAttribute("title", "Invalid Category Id: " + categoryId);
} else {
EventCategory category = result.get();
model.addAttribute("title", "Events in Category: " + category.getName());
model.addAttribute("events", category.getEvents());
}
}
return "events/index";
}
// Lives at /events/create
#GetMapping("create")
public String displayCreateEventForm(Model model) {
model.addAttribute("title", "Create Event");
model.addAttribute(new Event());
model.addAttribute("categories", eventCategoryRepository.findAll());
return "events/create";
}
// lives at /events/create
#PostMapping("create")
public String processCreateEventForm(#Valid #ModelAttribute("newEvent") Event newEvent, Errors errors, Model model) {
if (errors.hasErrors()) {
model.addAttribute("title", "Create Event");
return "events/create";
}
model.addAttribute("events", eventRepository.findAll());
eventRepository.save(newEvent);
return "redirect:";
}
// lives at /events/delete
#GetMapping("delete")
public String displayDeleteEventForm(Model model) {
model.addAttribute("title", "Delete Events");
model.addAttribute("events", eventRepository.findAll());
return "events/delete";
}
// lives at /events/delete
#PostMapping("delete")
public String processDeleteEventForm(#RequestParam(required = false) int[] eventIds) {
if (eventIds != null) {
for (int id : eventIds) {
eventRepository.deleteById(id);
}
}
return "redirect:";
}
}
Create Event
<nav th:replace="fragments :: navigation"></nav>
<form method="post" th:action="#{/events/create}" th:object="${event}">
<div class="form-group">
<label>Name
<input class="form-control" th:field="${event.name}">
</label>
<p class="error" th:errors="${event.name}"></p>
</div>
<div class="form-group">
<label>Description
<input class="form-control" th:field="${event.description}">
</label>
<p class="error" th:errors="${event.description}"></p>
</div>
<div class="form-group">
<label>Contact Email
<input class="form-control" th:field="${event.contactEmail}">
</label>
<p class="error" th:errors="${event.contactEmail}"></p>
</div>
<div class="form-group">
<label>Category
<select th:field="${event.eventCategory}">
<option th:each="eventCategory : ${categories}" th:value="${eventCategory.id}"
th:text="${eventCategory.name}">
</option>
</select>
<p class="error" th:errors="${event.eventCategory}"></p>
</label>
</div>
<div th:replace="fragments :: create-button"></div>
</form>
As per your code you are only trying to save Event entity and ignoring EventCategory.
You need to set Event to EventCategory as well as EventCategory to Event and make the cascade save.
First add cascade property in Event entity as below.
#ManyToOne(cascade = CascadeType.ALL)
#NotNull(message = "Category is required")
private EventCategory eventCategory;
Then in the Controller make the following changes.
#PostMapping("create")
public String processCreateEventForm(#Valid #ModelAttribute("newEvent") Event newEvent, Errors errors, Model model) {
if (errors.hasErrors()) {
model.addAttribute("title", "Create Event");
return "events/create";
}
model.addAttribute("events", eventRepository.findAll());
EventCategory eventCategory = newEvent.getEventCategory();
eventCategory.setEvent(newEvent);
eventRepository.save(newEvent);
return "redirect:";
}

ManyToMany select query is correct and the query is viewed in console. But I cant put values into jsp

I added many to many relationship to importers and agents table..data save successfully and middle table created...but i cannot retrieve data to my jsp ...How can i retrieve agents table data to my jsp.
My model is
package lk.slsi.domain;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name = "importers")
public class Importer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "importer_id")
private long importerId;
#NotEmpty
#Column(unique = true, nullable = false)
private String importerBrc;
private String importerVatNumber;
private String importerName;
private String importerAddress1;
private String importerAddress2;
private String importerAddress3;
private String importerCityName;
private String officePhoneNumber;
private String mobilePhoneNumber;
#Email
private String email;
#Email
private String optemail1;
#Email
private String optemail2;
public String getOptemail1() {
return optemail1;
}
public void setOptemail1(String optemail1) {
this.optemail1 = optemail1;
}
public String getOptemail2() {
return optemail2;
}
public void setOptemail2(String optemail2) {
this.optemail2 = optemail2;
}
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinTable(name = "importer_agents",
joinColumns = {#JoinColumn(name = "importerId")},
inverseJoinColumns = {#JoinColumn(name = "agentId")})
private List<Agent> agentList;
public String getImporterBrc() {
return importerBrc;
}
public void setImporterBrc(String importerBrc) {
this.importerBrc = importerBrc;
}
public String getImporterVatNumber() {
return importerVatNumber;
}
public void setImporterVatNumber(String importerVatNumber) {
this.importerVatNumber = importerVatNumber;
}
public String getImporterName() {
return importerName;
}
public void setImporterName(String importerName) {
this.importerName = importerName;
}
public String getImporterAddress1() {
return importerAddress1;
}
public void setImporterAddress1(String importerAddress1) {
this.importerAddress1 = importerAddress1;
}
public String getImporterAddress2() {
return importerAddress2;
}
public void setImporterAddress2(String importerAddress2) {
this.importerAddress2 = importerAddress2;
}
public String getImporterAddress3() {
return importerAddress3;
}
public void setImporterAddress3(String importerAddress3) {
this.importerAddress3 = importerAddress3;
}
public String getImporterCityName() {
return importerCityName;
}
public void setImporterCityName(String importerCityName) {
this.importerCityName = importerCityName;
}
public String getOfficePhoneNumber() {
return officePhoneNumber;
}
public void setOfficePhoneNumber(String officePhoneNumber) {
this.officePhoneNumber = officePhoneNumber;
}
public String getMobilePhoneNumber() {
return mobilePhoneNumber;
}
public void setMobilePhoneNumber(String mobilePhoneNumber) {
this.mobilePhoneNumber = mobilePhoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getImporterId() {
return importerId;
}
public void setImporterId(long importerId) {
this.importerId = importerId;
}
public List<Agent> getAgentList() {
return agentList;
}
public void setAgentList(List<Agent> agentList) {
this.agentList = agentList;
}
}
my agent table model is
package lk.slsi.domain;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
#Entity
#Table(name = "agents")
public class Agent {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "agent_id")
private long agentId;
#NotEmpty
#Column(unique = true, nullable = false)
private String nic;
private String vatNumber;
private String name;
private String agentAddress1;
private String agentAddress2;
private String agentAddress3;
private String agentCityName;
private String officePhoneNumber;
private String mobilePhoneNumber;
#Email
private String email;
public long getAgentId() {
return agentId;
}
public void setAgentId(long agentId) {
this.agentId = agentId;
}
public String getNic() {
return nic;
}
public void setNic(String nic) {
this.nic = nic;
}
public String getVatNumber() {
return vatNumber;
}
public void setVatNumber(String vatNumber) {
this.vatNumber = vatNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAgentAddress1() {
return agentAddress1;
}
public void setAgentAddress1(String agentAddress1) {
this.agentAddress1 = agentAddress1;
}
public String getAgentAddress2() {
return agentAddress2;
}
public void setAgentAddress2(String agentAddress2) {
this.agentAddress2 = agentAddress2;
}
public String getAgentAddress3() {
return agentAddress3;
}
public void setAgentAddress3(String agentAddress3) {
this.agentAddress3 = agentAddress3;
}
public String getAgentCityName() {
return agentCityName;
}
public void setAgentCityName(String agentCityName) {
this.agentCityName = agentCityName;
}
public String getOfficePhoneNumber() {
return officePhoneNumber;
}
public void setOfficePhoneNumber(String officePhoneNumber) {
this.officePhoneNumber = officePhoneNumber;
}
public String getMobilePhoneNumber() {
return mobilePhoneNumber;
}
public void setMobilePhoneNumber(String mobilePhoneNumber) {
this.mobilePhoneNumber = mobilePhoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
my repository is
package lk.slsi.repository;
import java.util.List;
import lk.slsi.domain.Importer;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
/**
* Created by ignotus on 2/8/2017.
*/
public interface ImporterRepository extends CrudRepository<Importer,Long> {
#Override
Importer save(Importer importer);
#Override
Importer findOne(Long importerId);
#Override
List<Importer> findAll();
#Override
void delete(Long aLong);
#Override
void delete(Importer importer);
#Override
void delete(Iterable<? extends Importer> iterable);
#Query("select u from Importer u where u.importerVatNumber = :importerVatNumber")
Importer getImporterByimporterVatNumber(#Param("importerVatNumber") String importerVatNumber);
#Query("select u from Importer u inner join u.agentList where u.importerId = :importerId")
List<Importer> findAgents(#Param("importerId") long importerId);
#Query("select u from Importer u where u.importerId = :importerId")
Importer getImporterByimporterID(#Param("importerId") long importerId);
}
my services is
public List<Importer> getAllIAgents(long importerId) {
return importerRepository.findAgents(importerId);
}
My controller is
#RequestMapping(path = "/viewImporter", method = RequestMethod.POST)
public String updateImporterAll(#RequestParam("importerId") long importerId, Model model) {
slsiLogger.info("Updating user with Id [{}]", importerId);
System.out.println("Importer id is " + importerId);
model.addAttribute("importerDetails", importerServices.getImporterByimporterID(importerId));
model.addAttribute("Agentsdetail", importerServices.getAllIAgents(importerId));
return "importerEdit";
}
Jsp is
<th width="15%">Registered Agents</th>
<c:forEach items="${Agentsdetail}" var="Agent">
<tr>
<td>${Agent.agentList.vatNumber}</td>
</tr>
/c:forEach>
</thead>
The query shows in netbeans console like this
Hibernate: select importer0_.importer_id as importer1_2_, importer0_.email as email2_2_, importer0_.importer_address1 as importer3_2_, importer0_.importer_address2 as importer4_2_, importer0_.importer_address3 as importer5_2_, importer0_.importer_brc as importer6_2_, importer0_.importer_city_name as importer7_2_, importer0_.importer_name as importer8_2_, importer0_.importer_vat_number as importer9_2_, importer0_.mobile_phone_number as mobile_10_2_, importer0_.office_phone_number as office_11_2_, importer0_.optemail1 as optemai12_2_, importer0_.optemail2 as optemai13_2_ from importers importer0_ inner join importer_agents agentlist1_ on importer0_.importer_id=agentlist1_.importer_id inner join agents agent2_ on agentlist1_.agent_id=agent2_.agent_id where importer0_.importer_id=?
How can i insert agent table values to my jsp.Please help me

Null value returned from jsp form:options to controller

The value returned by the JSP page for the path constituency is NULL. I have opted for a drop down list to display all the possible constituencies that can be selected. I have elaborated on the problem below.
Here is the Person Class:
#Entity
#Table(name="person")
public class person{
#Id
#Column(name = "NIC")
private Integer NIC;
#Column(name= "firstname")
private String fname;
#Column(name= "lastname")
private String lname;
#ManyToOne
#JoinColumn(name= "constituency_id")
private constituency constituency;
#OneToOne
#JoinColumn(name="NIC")
private login log;
public person(){
this.NIC = 1234;
this.fname = "Undefined";
this.lname = "Undefined";
}
public person(String fname, String lname, Integer NIC) {
this.fname = fname;
this.lname = lname;
this.NIC = NIC;
}
public Integer getNIC() {
return this.NIC;
}
public void setNIC(Integer NIC) {
this.NIC = NIC;
}
public String getfname() {
System.out.println(this.fname);
return this.fname;
}
public void setfname(String name) {
this.fname = name;
}
public String getlname() {
return this.lname;
}
public void setlname(String lname) {
this.lname = lname;
}
public constituency getConstituency() {
return this.constituency;
}
public void setConstituency(constituency id) {
this.constituency = id;
}
public login getlogin() {
return this.log;
}
public void setlogin(login log) {
this.log = log;
}
#Override
public String toString() {
return this.lname + " : " + this.fname;
}
}
Here is the Constituency Class:
#Entity
#Table(name="constituency")
public class constituency {
#Column(name="address")
private String address;
#Column(name="name")
private String name;
#Id
#Column(name="constituency_id")
private Integer constituency_id;
#Column(name="noofvoters")
private Integer voters;
#OneToMany(mappedBy="constituency", cascade = {CascadeType.ALL})
private Set <person> persons;
public constituency(){
this.constituency_id = 0;
this.name = "Undefined";
this.address = "Undefined";
this.voters = 0;
}
public constituency(String name, String address, Integer voters, Integer id) {
this.name = name;
this.address = address;
this.voters = voters;
this.constituency_id = id;
}
public String getname() {
System.out.println(this.name);
return this.name;
}
public void setname(String name) {
this.name = name;
}
public String getaddress() {
System.out.println(this.address);
return this.address;
}
public void setaddress(String name) {
this.address = name;
}
public Integer getvoters() {
return this.voters;
}
public void setvoters(Integer voters) {
this.voters = voters;
}
public Integer getconstituency_id() {
return this.constituency_id;
}
public void setconstituency_id(Integer id) {
this.constituency_id = id;
}
#Override
public String toString() {
return this.name;
}
}
Here is the portion of the controller responsible for handling the operation:
#RequestMapping(value="/Add", method=RequestMethod.GET)
public String add(Model model){
List <constituency> constit = constituencyDAO.details();
model.addAttribute("message", "Add a person for voting");
model.addAttribute("per", new person());
model.addAttribute("constituency", constit);
return "Add";
}
#RequestMapping(value="/Add", method=RequestMethod.POST)
public ModelAndView addperson(#ModelAttribute("per") person per, BindingResult bind){
System.out.println("In controller");
System.out.println(per.getfname()+" First-name");
System.out.println(per.getConstituency()+" constituency");
return hello();
}
Finally, this is the portion of the JSP page with the form:select tag:
<div class = "form-group">
<label for = "element1" class="control-label col-xs-2">Constituency ID</label>
<div class="col-xs-10">
<form:select path="constituency" name="constituency">
<form:option value="NONE" label="--- Select ---" />
<form:options items="${constituency}" itemValue="constituency_id" itemLabel="name" />
</form:select>
<p>Constituency ID</p>
</div>
</div>
Now, the problem is that even though the JSP page is able to successfully display the constituency attribute in the form:options, when the "per" model attribute is retrieved in the controller, the value for constituency and only constituency is NULL.
Below is the output in Eclipse.
The Form:
The output in the RequestMethod.POST:

spring data neo4j ,i can't solve it

I use spring data neo4j,i have user.class.movie.class,rating.class,i create relationship between movie and rating,when i run the programer,i can get the rating(star,comment)but cannot get the movie's title(null)
movie.class
package com.oberon.fm.domain;
#NodeEntity
public class Movie {
#GraphId
Long nodeId;
#Indexed(indexType = IndexType.FULLTEXT, indexName = "id")
String id;
#Indexed(indexType = IndexType.FULLTEXT, indexName = "search", numeric = false)
String title;
String description;
#RelatedTo(type = "DIRECTED", direction = INCOMING)
Person director;
#RelatedTo(type = "ACTS_IN", direction = INCOMING)
Set<Person> actors;
#RelatedToVia(elementClass = Role.class, type = "ACTS_IN", direction = INCOMING)
// Iterable<Role> roles;
Set<Role> roles = new HashSet<>();
#RelatedToVia(elementClass = Rating.class, type = "RATED", direction = INCOMING)
#Fetch
Iterable<Rating> ratings;
// Set<Rating> ratings = new HashSet<>();
private String language;
private String imdbId;
private String tagline;
private Date releaseDate;
private Integer runtime;
private String homepage;
private String trailer;
private String genre;
private String studio;
private Integer version;
private Date lastModified;
private String imageUrl;
public Movie() {
}
public Long getNodeId() {
return nodeId;
}
public void setNodeId(Long nodeId) {
this.nodeId = nodeId;
}
public Movie(String id, String title) {
this.id = id;
this.title = title;
}
public Collection<Person> getActors() {
return actors;
}
public Collection<Role> getRoles() {
return IteratorUtil.asCollection(roles);
}
public int getYear() {
if (releaseDate == null)
return 0;
Calendar cal = Calendar.getInstance();
cal.setTime(releaseDate);
return cal.get(Calendar.YEAR);
}
public String getId() {
return id;
}
public String getTitle() {
return title;
}
#Override
public String toString() {
return String.format("%s (%s) [%s]", title, releaseDate, id);
}
public String getDescription() {
return description;
}
public int getStars() {
Iterable<Rating> allRatings = ratings;
if (allRatings == null)
return 0;
int stars = 0, count = 0;
for (Rating rating : allRatings) {
stars += rating.getStars();
count++;
}
return count == 0 ? 0 : stars / count;
}
public Collection<Rating> getRatings() {
Iterable<Rating> allRatings = ratings;
return allRatings == null ? Collections.<Rating> emptyList()
: IteratorUtil.asCollection(allRatings);
}
/*
* public Set<Rating> getRatings() { return ratings; }
*/
public void setRatings(Set<Rating> ratings) {
this.ratings = ratings;
}
/*
* public void addRating(Rating rating) { ratings.add(rating); }
*/
public void setTitle(String title) {
this.title = title;
}
public void setLanguage(String language) {
this.language = language;
}
public void setImdbId(String imdbId) {
this.imdbId = imdbId;
}
public void setTagline(String tagline) {
this.tagline = tagline;
}
public void setDescription(String description) {
this.description = description;
}
public void setReleaseDate(Date releaseDate) {
this.releaseDate = releaseDate;
}
public void setRuntime(Integer runtime) {
this.runtime = runtime;
}
public void setHomepage(String homepage) {
this.homepage = homepage;
}
public void setTrailer(String trailer) {
this.trailer = trailer;
}
public void setGenre(String genre) {
this.genre = genre;
}
public void setStudio(String studio) {
this.studio = studio;
}
public void setVersion(Integer version) {
this.version = version;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getLanguage() {
return language;
}
public String getImdbId() {
return imdbId;
}
public String getTagline() {
return tagline;
}
public Date getReleaseDate() {
return releaseDate;
}
public Integer getRuntime() {
return runtime;
}
public String getHomepage() {
return homepage;
}
public String getTrailer() {
return trailer;
}
public String getGenre() {
return genre;
}
public String getStudio() {
return studio;
}
public Integer getVersion() {
return version;
}
public Date getLastModified() {
return lastModified;
}
public String getImageUrl() {
return imageUrl;
}
public String getYoutubeId() {
String trailerUrl = trailer;
if (trailerUrl == null || !trailerUrl.contains("youtu"))
return null;
String[] parts = trailerUrl.split("[=/]");
int numberOfParts = parts.length;
return numberOfParts > 0 ? parts[numberOfParts - 1] : null;
}
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Movie movie = (Movie) o;
if (nodeId == null)
return super.equals(o);
return nodeId.equals(movie.nodeId);
}
#Override
public int hashCode() {
return nodeId != null ? nodeId.hashCode() : super.hashCode();
}
public Person getDirector() {
return director;
}
}
user.class
package com.oberon.fm.domain;
#NodeEntity
public class User {
#GraphId
Long nodeId;
public static final String SALT = "cewuiqwzie";
public static final String FRIEND = "FRIEND";
public static final String RATED = "RATED";
#Indexed(indexType = IndexType.FULLTEXT, indexName = "login")
String login;
#Indexed
String name;
String password;
public void setPassword(String password) {
this.password = password;
}
String info;
private Roles[] roles;
public User() {
}
public User(String login, String name, String password, Roles... roles) {
this.login = login;
this.name = name;
this.password = encode(password);
this.roles = roles;
}
private String encode(String password) {
return new Md5PasswordEncoder().encodePassword(password, SALT);
}
#RelatedToVia(type = RATED)
#Fetch
Iterable<Rating> ratings;
// Set<Rating> ratings = new HashSet<>();
#RelatedTo(type = RATED)
Set<Movie> favorites;
public Set<Movie> getFavorites() {
return favorites;
}
public void setFavorites(Set<Movie> favorites) {
this.favorites = favorites;
}
#RelatedTo(type = FRIEND, direction = Direction.BOTH)
#Fetch
Set<User> friends;
public void addFriend(User friend) {
this.friends.add(friend);
}
public Rating rate(Neo4jOperations template, Movie movie, int stars,
String comment) {
final Rating rating = template.createRelationshipBetween(this, movie,
Rating.class, RATED, false).rate(stars, comment);
return template.save(rating);
}
/*
* public Rating rate(Movie movie, int stars, String comment) { if (ratings
* == null) { ratings = new HashSet<>(); }
*
* Rating rating = new Rating(this, movie, stars, comment);
* ratings.add(rating); movie.addRating(rating); return rating; }
*/
public Collection<Rating> getRatings() {
return IteratorUtil.asCollection(ratings);
}
/*
* public Set<Rating> getRatings() { return ratings; }
*/
#Override
public String toString() {
return String.format("%s (%s)", name, login);
}
public String getName() {
return name;
}
public Set<User> getFriends() {
return friends;
}
public Roles[] getRole() {
return roles;
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public void updatePassword(String old, String newPass1, String newPass2) {
if (!password.equals(encode(old)))
throw new IllegalArgumentException("Existing Password invalid");
if (!newPass1.equals(newPass2))
throw new IllegalArgumentException("New Passwords don't match");
this.password = encode(newPass1);
}
public void setName(String name) {
this.name = name;
}
public boolean isFriend(User other) {
return other != null && getFriends().contains(other);
}
public enum Roles implements GrantedAuthority {
ROLE_USER, ROLE_ADMIN;
#Override
public String getAuthority() {
return name();
}
}
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
User user = (User) o;
if (nodeId == null)
return super.equals(o);
return nodeId.equals(user.nodeId);
}
public Long getId() {
return nodeId;
}
#Override
public int hashCode() {
return nodeId != null ? nodeId.hashCode() : super.hashCode();
}
}
rating.class
package com.oberon.fm.domain;
#RelationshipEntity
public class Rating {
private static final int MAX_STARS = 5;
private static final int MIN_STARS = 0;
#GraphId
Long id;
#StartNode
User user;
#EndNode
Movie movie;
int stars;
String comment;
public User getUser() {
return user;
}
public Movie getMovie() {
return movie;
}
public int getStars() {
return stars;
}
public void setStars(int stars) {
this.stars = stars;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public Rating rate(int stars, String comment) {
if (stars >= MIN_STARS && stars <= MAX_STARS)
this.stars = stars;
if (comment != null && !comment.isEmpty())
this.comment = comment;
return this;
}
public Rating() {
}
public void setUser(User user) {
this.user = user;
}
public void setMovie(Movie movie) {
this.movie = movie;
}
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Rating rating = (Rating) o;
if (id == null)
return super.equals(o);
return id.equals(rating.id);
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : super.hashCode();
}
}
controller
#RequestMapping(value = "/user", method = RequestMethod.GET)
public String profile(Model model, HttpServletRequest request) {
// User user=populator.getUserFromSession();
HttpSession session = request.getSession(false);
User user = (User) session.getAttribute("user");
model.addAttribute("user", user);
if (user != null) {
List<MovieRecommendation> mr = movieRepository.getRecommendations(user.getLogin());
MovieRecommendation movie = new MovieRecommendation();
Movie m = new Movie();
m.setTitle("AA");
movie.setMovie(m);
mr.add(movie);
model.addAttribute("recommendations", mr);
}
return "user/index";
}![enter image description here][4]
It only loads the movie's id by default, if you don't specify #Fetch on the movie field. But I'd rather recommend to use template.fetch(rating.movie) to load it only when you need it.

Resources