Exception:Creating bean with name ‘entityManagerFactory’ defined in class path [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed

Exception:Creating bean with name ‘entityManagerFactory’ defined in class path [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed

The error you’re encountering, org.hibernate.MappingException: An audited relation from com.entity.UserDetails to a not audited entity com.entity.Role, suggests that Hibernate Envers is trying to audit a relationship between an audited entity (UserDetails) and a non-audited entity (Role). Hibernate Envers requires that if an entity is audited and it has a relationship with another entity, then the related entity must also be audited. Here are a few ways to resolve this issue:

  1. Audit the Related Entity: Assuming you want to audit both entities, the following example shows how to ensure both entities are audited
@Audited
@Entity
public class UserDetails {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    // Other fields

    @Audited
    @OneToMany(mappedBy = "UserDetails")
    private List<Role> Roles;

    // Getters and Setters
}
@Audited
@Entity
public class Role{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    // Other fields

    @ManyToOne
    @JoinColumn(name = "user_details_id")
    private UserDetails userDetails;

    // Getters and Setters
}

By auditing both entities, we can fix the problem. This tells Hibernate Envers to track changes to this entity as well. You will comply with Hibernate Envers’ requirements, and the MappingException should be resolved.

2. Exclude the Relationship from Auditing: If you don’t need to track changes in the relationship, you can exclude the relationship from being audited by using the @NotAudited annotation.

@Audited
@Entity
public class UserDetails {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    // Other fields

    @NotAudited
    @OneToMany(mappedBy = "UserDetails")
    private List<Role> roles;

    // Getters and Setters
}

By marking the relationship as @NotAudited, you tell Hibernate Envers not to track changes in the Role relationship.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *