Implement RegistrationManagement

The RegistrationManagement domain service is where the business logic of registration lives. The business logic includes the following:

  • Existing username/email address cannot register
  • Encrypt password
  • Save the user to the repository

The following diagram, shows the relationship between RegistrationManagement and its dependencies:

Figure 9.12: RegistrationManagement class diagram

As you can see, RegistrationManagement uses UserRepository to find a user. It throws UsernameExistsException or EmailAddressExistsException when there is another user that already exists with the same username or email address. Otherwise, it asks PasswordEncryptor to encrypt the password and then asks UserRepository to save that user.

Before we create the unit test, let's create the User entity first because it is created inside RegistrationManagement, and UserRepository also depends on it. It looks like the following:

...
@Entity
@Table(name = "user")
public class User extends AbstractBaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name="username", nullable=false, length=50, unique=true)
private String username;

@Column(name="email_address", nullable=false, length=100,
unique=true)
private String emailAddress;

@Column(name="password", nullable=false, length=30)
private String password;

@Column(name="first_name", nullable=false, length=45)
private String firstName;

@Column(name="last_name", nullable=false, length=45)
private String lastName;

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_date", nullable=false)
private Date createdDate;

public User() {}

public static User create(String username, String emailAddress,
String password) {
User user = new User();
user.username = username;
user.emailAddress = emailAddress;
user.password = password;
user.firstName = "";
user.lastName = "";
user.createdDate = new Date();
return user;
}
...
}

As you can see, this entity's fields map to the columns we created during the data modeling. And for the id field, we use the GenerationType.IDENTITY strategy to tell Hibernate that the value of the id field is generated by the database. For the other fields, we specify the length, nullability, and uniqueness using the @Column annotation. This is required because, when we test repositories, we will use Hibernate's hbm2ddl feature to create the database inside H2, the embedded database that we will use during testing. With these settings in the @Column annotations, the table that is autogenerated will have these constraints as well. In this entity, we also override the equals() and hashCode() method to only compare username and emailAddress of two User objects; as long as those two fields are the same, we consider those two objects to be equal.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.249.42