1

I have requirement where I need to insert user name and group name to which the user belongs (both available in SecurityContext) in the same table.

class Entity

{ 

   @createdBy 
   String username 

   @createdBy 
   String groupname 

   other fields ...

}

As per requirement. I cant solve this issue by making a user class and referencing it through a foreign key.

With current implementation of AuditingHandler both fields are getting the same value. How do I make sure they get respective values.

Can this be achieved using current implementation ? If not thn how can I provide custom implementation of AuditingHandler ?

1 Answers1

6

You could make a separate embeddable class and annotate it with @CreatedBy in your parent class. One way is to define a bean implementing AuditorAware, then you can make it return custom object, containing your two required fields. For example, your parent class would look like this (note the listener annotation):

@Entity
@EntityListeners(AuditingEntityListener.class)
public class AuditedEntity {

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid")
    private String id;

    @Embedded
    @CreatedBy
    private AuditorDetails createdBy;

    // setters and getters
}

where AuditorDetails is:

@Embeddable
public class AuditorDetails {
    private String username;
    private String groupname;

    // setters and getters

}

and finally, your AuditorAware bean:

@Component
class AuditorAwareImpl implements AuditorAware<AuditorDetails> {

    @Override
    public AuditorDetails getCurrentAuditor() {
        return new AuditorDetails()
                .setUsername("someUser")
                .setGroupname("someGroup");
    }
}

AuditingHandler fetches your custom AuditorDetails from your AuditorAware bean (it must be single bean implementing it) and sets it in your auditable entity.

J R
  • 223
  • 3
  • 12