Search code examples
javamysqljpaeclipselink

MySQL auto-increment set to 22378; new record assigned id = 1


MySQL (InnoDB) auto-increment seems to be properly configured, but calling

em.persist(entry)

results in the error:

Exception [EclipseLink 4002] (Eclipse Persistence Services 2.5.0.v20130507 3faac2b): org.eclipse.persistence.exceptions.DatabaseException

Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1' for key 'PRIMARY' Error Code: 1062

The entity to be persisted (Entry), uses the primary key entry_id, by which it is joined to the inventory table.

@Entity
@Table(name="entries")
public class Entry implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = 8144553107778486945L;

/*
 * PRIMARY KEY & ID FOR THE CASE
 */
@Id
@Column(name="ENTRY_ID")
@GeneratedValue(strategy = GenerationType.AUTO)        // was TABLE
    private Long entry_id;

@Version
private Integer version;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "entry",
        cascade={CascadeType.PERSIST, CascadeType.MERGE})
@JoinColumn(name="entry_id")
private List<InventoryEntry> inventory =
    new ArrayList<InventoryEntry>();

Running the query:

select max(entry_id) FROM entries

yields:

max(entry_id)
22377

Running:

show table status from chambers like ‘entries’

in the MySQL Command Line Client shows the next auto-increment number to be:

22378

Question: why then is an id = 1 being assigned to a new record?

It is my understanding that auto-increment is reset on database start-up to max(id) + 1, and the query results confirm this is indeed the case. I should add that this table formerly used: strategy = GenerationType.TABLE, and the Duplicate Entry '1' error first arose using this strategy (which is why I adopted the auto-increment strategy). I have deleted the Sequence table. I have also dropped the database and re-generated the schema from the Java classes, repopulating the data from a backup. All to no avail.

Describe ENTRIES shows the configuration of the entry_id row as:

FIELD: ENTRY_ID, TYPE: bigint(20), NULL: NO, KEY: PRI, DEFAULT: NULL, EXTRA: auto_increment

The row is indexed as PRIMARY. Thus, everything appears to be in order.

I should add that this web application utilizes a MySQL InnoDB database running in a Glassfish 4.0 community server (recently upgraded from a Glassfish 3.1.2.2 embedded server). Eclipse Kepler is the IDE on a Windows 7 64-bit platform.

I have exhausted the limits of my meager abilities. Any help would be greatly appreciated.


Solution

  • You're seeing this problem because MySQL isn't generating the ID for the row, EclipseLink is. You can try using GenerationType.IDENTITY to force JPA to use an identity column (which forces a reread from the database to update the Java object), or you can restore the previous state; I don't know how EclipseLink implements GenerationType.AUTO.