@Entity
@Data
@DoAudit
@Table(name = "product")
@EntityListeners(AuditListener.class)
public class Product implements Serializable {
@Id
@Column(name = "code", length = 50, nullable = false, unique = true, insertable = false, updatable = false)
private String code; // Primary Key: code (VARCHAR(50))
private String name;
private Double price;
}
< /code>
CREATE TABLE product (
code VARCHAR(50) NOT NULL UNIQUE,
name VARCHAR(255),
price DOUBLE,
PRIMARY KEY (code)
);
< /code>
Whenever I try to save this class, there is no issue.
However, when I try to save the following version:
@Entity
@Data
@DoAudit
@Table(name = "product")
@EntityListeners(AuditListener.class)
public class Product implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private Double price;
}
< /code>
CREATE TABLE product (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
price DOUBLE
);
< /code>
I encounter the following error in this class in logChange method
issue is with all DB I am using.
@Component
public class AuditListener implements PostUpdateEventListener, PostInsertEventListener, PostDeleteEventListener {
@Autowired
private AuditRepository auditRepository;
@Transactional(Transactional.TxType.REQUIRES_NEW)
private void logChanges(Object entity, String operation, Object[] oldState, Object[] newState, String[] propertyNames) {
if (entity instanceof AuditLog) {
return;
}
try {
AuditLog auditLog = new AuditLog();
auditLog.setTableName(entity.getClass().getSimpleName());
auditLog.setOperationType(operation);
auditLog.setChangedBy("Ankit");
auditLog.setTimestamp(LocalDateTime.now());
auditLog.setEntityId("UNKNOWN");
auditLog.setTraceId("traceId");
auditLog.setChanges("Changes as per logic");
auditRepository.save(auditLog);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onPostInsert(PostInsertEvent event) {
System.out.println("
logChanges(event.getEntity(), "INSERT", null, event.getState(), event.getPersister().getPropertyNames());
}
@Override
public boolean requiresPostCommitHandling(EntityPersister entityPersister) {
return false;
}
@Override
public void onPostUpdate(PostUpdateEvent event) {
logChanges(event.getEntity(), "UPDATE", null, event.getState(), event.getPersister().getPropertyNames());
}
@Override
public void onPostDelete(PostDeleteEvent event) {
logChanges(event.getEntity(), "DELETE", null, null, event.getPersister().getPropertyNames());
}
}
< /code>
@Configuration
public class HibernateEventListenerConfig {
private final AuditListener auditListener;
@Autowired
public HibernateEventListenerConfig(AuditListener auditListener) {
this.auditListener = auditListener;
}
@Autowired
public void registerListeners(EntityManagerFactory entityManagerFactory) {
SessionFactoryImplementor sessionFactory = entityManagerFactory.unwrap(SessionFactoryImplementor.class);
EventListenerRegistry registry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class);
registry.appendListeners(EventType.POST_INSERT, auditListener);
registry.appendListeners(EventType.POST_UPDATE, auditListener);
registry.appendListeners(EventType.POST_DELETE, auditListener);
}
}
< /code>
@Entity
@Data
@Table(name = "audit_log")
public class AuditLog {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String traceId;
private String tableName;
private String entityId;
private String operationType;
private String changedBy;
private LocalDateTime timestamp;
@Column(columnDefinition = "TEXT")
private String changes;
}
< /code>
Error:
2025-01-30T19:20:49.095+05:30 WARN 2541 --- [nio-8080-exec-7] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 23505, SQLState: 23505
2025-01-30T19:20:49.095+05:30 ERROR 2541 --- [nio-8080-exec-7] o.h.engine.jdbc.spi.SqlExceptionHelper : Unique index or primary key violation: "PUBLIC.PRIMARY_KEY_1 ON PUBLIC.PRODUCT(CODE) VALUES ( /* 5 */ 'ffc' )"; SQL statement:
insert into product (name,price,code) values (?,?,?) [23505-232]
org.springframework.dao.DataIntegrityViolationException: could not execute statement [Unique index or primary key violation: "PUBLIC.PRIMARY_KEY_1 ON PUBLIC.PRODUCT(CODE) VALUES ( /* 5 */ 'ffc' )"; SQL statement:
insert into product (name,price,code) values (?,?,?) [23505-232]] [insert into product (name,price,code) values (?,?,?)]; SQL [insert into product (name,price,code) values (?,?,?)]; constraint [PUBLIC.PRIMARY_KEY_1]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:290)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:241)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:560)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:343)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:160)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:147)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:223)
at jdk.proxy2/jdk.proxy2.$Proxy113.save(Unknown Source)
at com.example.AuditLog.listner.AuditListener.logChanges(AuditListener.java:36)
at com.example.AuditLog.listner.AuditListener.onPostInsert(AuditListener.java:46)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:569)
< /code>
I have tried every possible solution available online, including ChatGPT suggestions.
I want to audit all my entries. Alternative solutions are also welcome.
Подробнее здесь: https://stackoverflow.com/questions/794 ... eleteevent