Skip to content

Instantly share code, notes, and snippets.

@darbyluv2code
Created June 28, 2017 17:40
Show Gist options
  • Select an option

  • Save darbyluv2code/f5b3c8eaf67cfc9916a4ff422a611603 to your computer and use it in GitHub Desktop.

Select an option

Save darbyluv2code/f5b3c8eaf67cfc9916a4ff422a611603 to your computer and use it in GitHub Desktop.
Milos - Sort Order
1. Update the form for sorting drop-down list
To pass the sortfield, we give a named parameter: "thesortfield". Also, update the options to use the same field names as our Hibernate entities. The form also includes a submit button to send data to the controller.
<form action="${pageContext.request.contextPath}/customer/list">
<select name="thesortfield">
<option value="firstName">First Name</option>
<option value="lastName">Last Name</option>
<option value="email">Email</option>
<option value="dateOfBirth">Date</option>
</select>
<input type="submit" value="Search" />
</form>
2. Update the Controller to read the sort field
Use @RequestParam to read form field, "thesortfield". Use "firstName" as a default if none provided.
@GetMapping(value="/list")
public String listCustomers(@RequestParam(value="thesortfield",
defaultValue = "firstName") String theSortField,
Model theModel) {
//get customers from service
List<Customer> theCustomers = customerService.getCustomersBy(theSortField);
//add the customers to the model
//"customers" is the name (we use that in for loop to print data, theCustomers is the value that we got in lane above
theModel.addAttribute("customers", theCustomers);
return "list-customers";
}
3. Update CustomerService with new method to handle sort field
Add a new method to handle sort field
File: CustomerService.java
public List<Customer> getCustomersBy(String theSortField);
File: CustomerServiceImpl.java
@Transactional
public List<Customer> getCustomersBy(String theSortField) {
return customerDAO.getCustomersBy(theSortField);
}
4. Update CustomerDAO to perform the search using the sort field
File: CustomerDAO.java
public List<Customer> getCustomersBy(String theSortField);
File: CustomerDAOImpl.java
public List<Customer> getCustomersBy(String theSortField) {
Session currentSession = sessionFactory.getCurrentSession();
Criteria theCriteria =
currentSession.createCriteria(Customer.class)
.addOrder(Order.asc(theSortField));
//the method getResultList() is undefined for the type Criteria
List<Customer> customers = theCriteria.list();
return customers;
}
Latest code is available here (code only, no jars)
http://www.luv2code.com/temp/milos-sort-web-customer-tracker-source-only.zip
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment