The Spring data binding system allows you to bind servlet request data to any command object, e.g. a POJO from your domain layer. However, I'm having a problem with this.
I have the following simple POJO User entity:
As you can see it uses the userName to determine equality. It also has a bidirectional associated with the Organization entity, so Organization has a method:Code:public class User extends Entity { private String userName; private Organization organization; //default constructor for use by Spring binding, Hibernate, ... public User() { } public User(String userName) { this.userName=userName; } //getters and setters omitted public void setLinkedOrganization(Organization org) { org.addUser(this); } public boolean equals(Object obj) { if (obj==this) return true; if (obj==null) return false; if (obj.getClass()!=this.getClass()) return false; User other=(User)obj; return this.getUserName().equals(other.getUserName()); } public int hashCode() { return getUserName().hashCode(); } }
The problem I now have is that when the ServletRequestDataBinder pushes in the Organization object when populating a new User in the CreateUserController, the userName has not yet been set! As a result the equals() method will throw a NullPointerException when the user is added to the "users" set of the organization (using users.add(user) in the code above).Code:public class Organization extends Entity { private Set users=new HashSet(); ... public void addUser(User user) { if (user.getOrganization()!=null) { user.getOrganization().removeUser(user); } user.setOrganization(this); users.add(user); } }
Is there something stupid I'm doing here? How can I fix this while still using the ServletRequestDataBinder to bind to my domain layer POJO? I don't want to create a dummy DTO just to bind to and manually doing all the binding also seems clumsy!
Erwin


Reply With Quote