java - issue in saving PostUpdateEventListener,PostInsertEventListener, PostDeleteEventListener, getting duplicate error in case

I have the following entity:@Entity@Data@DoAudit@Table(name = "product")@EntityListeners

I have the following entity:

@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;
}
CREATE TABLE product (
    code VARCHAR(50) NOT NULL UNIQUE,
    name VARCHAR(255),
    price DOUBLE,
    PRIMARY KEY (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;
}
CREATE TABLE product (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255),
    price DOUBLE
);

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("

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745237035a4617953.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信