Discussions

General J2EE: Data Access Object & Value Objects

  1. Data Access Object & Value Objects (2 messages)

    Scenario : User table contains 3 fields - UserID, UserName, UserAddress.
    If I want to use the DAO pattern to create a new user then I would need UserBusinessObject, User(value object), UserDAO. Here's the code snippet:

    public class UserBusinessObject {
       public addUser(String userName, String userAddress) {
          User user = new User();
          user.setUserAddress(userAddress);
          user.setUserName(userName);
          new UserDAO().create(user);
        }
        .....
    }

    public class User {
        //getters & setters for userName & userAddress
    }

    public class UserDAO {
       public User create(String userName, String userAddress) {
          //generate UserID
          //apply SQL to insert values into these 3 fields
          return new User(userID, userName, userAddress);
       }
       ....
    }

    As you see, I'm creating the User value object in the business object even though I do not have the userID. So basically the user value object is not really valid at this point! Is my assumption/implementation correct or wrong?

    Thanks,

    Poorav
  2. If you do database stuff in your UserDAO.create() method, then you should get a hold of an userID also.

    public User create(String userName, String userAddress)
    {
      // 1. get a database connection
      // 2. get a unique userID for the to-be-created user
      // 3. insert userID, userName and userAddress to database
      return new User(userID, userName, userAddress);
    }
  3. If User Value Object was as below :

    public class User {
      
      public User create(User userVO) {
        // 1. get a database connection
        // 2. get a unique userID for the to-be-created user
        // 3. insert userID, userName and userAddress to db
        return new User(userID, userName, userAddress);
      }
    }

    then could I have the following in the Business Object :

    public class UserBusinessObject {
       public addUser(String userName, String userAddress) {
          User user = new User();
          user.setUserAddress(userAddress);
          user.setUserName(userName);
          new UserDAO().create(user);
        }
        .....
    }

    So basically I'm creating a User value object without the userID and passing it as a paramater to the UserDAO. So its only a partial object at that instant. Is that ok?