eagle79 wrote:
Could you post a short version of your myapp.model.Staff class (short meaning cut out most of the vanilla implementing code and let us have a look at the structure)?
Ok, here goes:
Code:
package myApp.model;
import java.io.Serializable;
import java.util.*;
public class Staff implements Serializable, Comparable {
public Staff() {}
private Integer id;
public Integer getId() {
public void setId(Integer id) {
private String userName;
public String getUserName() {
public void setUserName(String userName) {
private Collection<Role> roles;
public Collection<Role> getRoles() {
public void setRoles(Collection roles) {
public void addRole(Role role) {
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Staff)) return false;
final Staff staff = (Staff) o;
if (!userName.equals(staff.userName)) return false;
return true;
}
public String toString() {
return "Staff ('" + getId() + "'), " +
"Username: '" + getUserName() + "'";
}
// The natural comparator works with the Staff ID
public int compareTo(Object anotherStaff) throws ClassCastException {
if (!(anotherStaff instanceof Staff))
throw new ClassCastException("A Staff object expected.");
int anotherStaffId= ((Staff) anotherStaff).getId();
return this.id - anotherStaffId;
}
// I would like to include other Comparator classes directly in this class, since the Comparators will serve no purpose to any other classes.
public class NameComparator implements Comparator {
public int compare(Object staff, Object anotherStaff) {
String name= ((Staff) staff).getUserName().toUpperCase();
String anotherName= ((Staff) anotherStaff).getUserName().toUpperCase();
return name.compareTo(anotherName);
}
}
}
Now, I have also tried making the NameComparator class a static property of the Staff class, like this:
Code:
public static Comparator NameComparator = new Comparator() {
public int compare(Object staff, Object anotherStaff) {
...
...and that hasn't worked either.
Using the first method, I have actually run getCanonicalName() on the NameComparator class object and recieved
myApp.model.Staff.NameComparator, which would lead me to believe I could enter that into the sort attribute and Hibernate would be able to find that comparator class. Alas, no.
How is everyone else implementing their custom comparator classes? (sorry about that icky alliteration :) Is everyone putting them in their own seperate classes (ie: in a different .java file possibly in a different package)? Doesn't this add a lot bloat? Wouldn't it be better to put that code directly into the class that it does sorting on, thus keeping it handy? I would really appreciate hearing how others handle this. Does anyone have some "best practices" advice on this?
Thanks again, IA
graham.