JPA merge抛出异常刷新期间键'PRIMARY'的重复条目

时间:2017-04-18 21:52:04

标签: java mysql spring hibernate jpa

我有一个使用hibernate 5.2和JPA处理数据库的spring服务器。

我们有一个收集大量数据并根据该数据保存事件的流程。它每天运行,这些事件有可能改变价值。有时当我尝试保存这些时,我得到以下异常:

15:28:32.819 [pool-6-thread-3] ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Duplicate entry 'VAL-below_avg-2017-04-07' for key 'PRIMARY'
Query is: insert into event_date (description, period, time, date, symbol, type) values (?, ?, ?, ?, ?, ?, ?)
Query is:
insert into event_date (description, period, time, date, symbol, type) values (?, ?, ?, ?, ?, ?, ?)
[org.hibernate.exception.ConstraintViolationException: could not execute statement]
15:28:32.822 [pool-6-thread-3] ERROR org.hibernate.internal.ExceptionMapperStandardImpl - HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [PRIMARY]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:278)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:521)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:761)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:730)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:504)

我们在这里没有做任何想象。我们处理数据。我们创造新的对象。我们在DAO中将它们传递给以下方法:

public void saveOrUpdate(List<EventDate> events) {
    for (EventDate e : events) {
        try{
            entityManager.merge(e);
        }catch(Exception e1){
            logger.error("Something broke!");
        }
    }
}

我已经完成了大约十几个类似的问题,但是在所有这些问题中,问题似乎是由与另一个对象的某种方向关系引起的。就我而言,没有这样的事情。我也看到有些人认为这是一个没有哈希码和等号的问题,所以我实现了这些无济于事。

我的实体类如下所示(有许多实体继承了EventDate,但它们大多只是在这里和那里添加一些元属性,我不认为问题在于它们:

@Entity
@Table(name = "event_date")  
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)  
@DiscriminatorColumn(name="type", discriminatorType=DiscriminatorType.STRING, length=255)
@DiscriminatorOptions(insert=false)
@JsonIgnoreProperties(ignoreUnknown=true)
public abstract class EventDate implements Serializable {
    private static final long serialVersionUID = 1L;

    @EmbeddedId 
    private SymDateTypeId id;

    @Column(columnDefinition=COLUMN_DATETIME)
    private String time = "UNKNOWN";

    @Column(columnDefinition=COLUMN_TEXT)
    private String description;

    @Column(columnDefinition=COLUMN_VARCHAR20)
    private String period;

    //Getters/Setters/Hashcode/Equals omitted...
}

@Embeddable
public class SymDateTypeId implements Serializable{
    private static final long serialVersionUID = 1L;

    @Column(nullable=false)
    private String symbol = "UNKNOWN";
    @Column(nullable=false)
    private String date = "UNKNOWN";
    @Column(nullable=false)
    private String type;

    //Getters and setters omitted...

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((date == null) ? 0 : date.hashCode());
        result = prime * result + ((symbol == null) ? 0 : symbol.hashCode());
        result = prime * result + ((type == null) ? 0 : type.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        SymDateTypeId other = (SymDateTypeId) obj;
        if (date == null) {
            if (other.date != null)
                return false;
        } else if (!date.equals(other.date))
            return false;
        if (symbol == null) {
            if (other.symbol != null)
                return false;
        } else if (!symbol.equals(other.symbol))
            return false;
        if (type == null) {
            if (other.type != null)
                return false;
        } else if (!type.equals(other.type))
            return false;
        return true;
    }
}

1 个答案:

答案 0 :(得分:1)

Duplicate entry 'VAL-below_avg-2017-04-07' for key 'PRIMARY'

明确表示您已在数据库中拥有相关行。试着找出为什么两次保存事件,一切都很好。您可以在源中添加日志条目。