Implementing the domain model

In order to successfully populate the createdUser property, the AuditAware interface needs to be implemented to supply the username and needs to be registered as a Spring Component. More on this in the Using Spring Security for authentication and authorization section.

Implementing the domain model Comment class using JPA annotations will look like the following:

@Entity
@Table(name = "rb_comment")
@EntityListeners(AuditingEntityListener.class)
@Data
public class Comment {

@Id
@GeneratedValue
private Long id;

private String comment;

@Enumerated(EnumType.STRING)
private CommentType type;

@CreatedDate
private Timestamp createdDate;

@CreatedBy
private String createdBy;

}

In the preceding code, the @Entity annotation is used to mark the Comment class as a JPA entity so that it will be eligible to be used in JPA persistence environment. The @Table annotation is used to mention the table name to which the Comment class needs to be mapped. The @EntityListeners annotation is used with the AuditingEntityListener implementation to dynamically populate the createdDate and createdBy properties annotated with @CreatedDate and @CreatedBy in the Comment domain model when persisting the comment entry into the table. The @Data annotation is from the Lombok library and used to mark a POJO as a class that will hold data. This means getters, setters, the equals method, the hashCode method, and the toString method will be generated for that class.

The @Id annotation marks the ID property as the identity field of the entity, whereas @GeneratedValue marks it as an auto-generated value. The @Enumerated annotation with value EnumType.STRING on the type property is used to notify JPA that the value of the enum CommentType needs to be persisted as a String type in the database. 

Implementing the domain model User will look like the following:

@Entity
@Table(name = "rb_user")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

@Id
@GeneratedValue
private Long id;

private String username;

private String password;

private String role;

}

The preceding class also does the same things as the Comment class. The newly added annotations, which are also from the Lombok library,  are @AllArgsConstructor, which will generate a constructor with the id, username, password, and role properties, and @NoArgsConstructor, which will generate a default constructor.

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

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