Announcement Announcement Module
Collapse
No announcement yet.
Problem binding to domain layer POJOs Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Problem binding to domain layer POJOs

    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:
    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();
      }
    }
    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 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);
      }
    }
    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).

    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

  • #2
    Are you cascading your changes between User and Organization? If so that should take care of the relationship so you don't have to do that step of removing a user from an organization.

    I'm not sure what
    that when the ServletRequestDataBinder pushes in the Organization object when populating a new User in the CreateUserController
    means. Are you creating a new user? If so that's the time where you want to set his name. After you've created the user and an organization to it and then save.

    Comment

    Working...
    X