You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@openjpa.apache.org by "Karsten Priegnitz (JIRA)" <ji...@apache.org> on 2018/03/21 17:17:00 UTC

[jira] [Commented] (OPENJPA-1066) Generated ID starting with 0 can cause unexpected results

    [ https://issues.apache.org/jira/browse/OPENJPA-1066?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=16408265#comment-16408265 ] 

Karsten Priegnitz commented on OPENJPA-1066:
--------------------------------------------

I would flag this as a serious bug. OpenJPA overwrites data when it is supposed to do an INSERT.

The reason for this behaviour is, that when an entity is to be merged ...
 * OpenJPA checks its id
 * If it is null, then it is handled as if it were zero (see constructor of org.apache.openjpa.util.LongId).
 * OpenJPA checks if my object is detached or not, by checking the database.
 * In this case it checks if there is an DB-Entity with id=0 (null => 0, remember?).
 * Now it thinks my object is detached (not managed, but in database) ...
 * ... and does an UPDATE on the one with id 0 - which is not the one I wanted to insert

The workaround may be to not use IDs that are zero, but eg. in my case we changed to OpenJPA after already producing the app for several years and we have hundreds of tables, which all might have (and many do have) already entries with ID=0 and foreign keys that refer to these.

> Generated ID starting with 0 can cause unexpected results
> ---------------------------------------------------------
>
>                 Key: OPENJPA-1066
>                 URL: https://issues.apache.org/jira/browse/OPENJPA-1066
>             Project: OpenJPA
>          Issue Type: Improvement
>          Components: kernel
>    Affects Versions: 2.2.0
>         Environment: any DB that allows a generated id to start with 0.  And an entity that maps that generated id to an int instead of an Integer
>            Reporter: B.J. Reed
>            Priority: Minor
>         Attachments: GeneratedIDStartsWith0.ZIP
>
>
> Several DB's allow a generated id column to start with 0.
> For instance, DB2 allows  "GENERATED ALWAYS AS IDENTITY (START WITH 0)...."
> When this is used, the very first object will have an id of 0.  When entities are first created, the user usually won't fill in the corresponding id field (since it will be generated by the DB when the entity is put in the DB), so it defaults to 0.  The entity manager then uses this 0 and sees that an entity already exists and will update the old entity in stead of creating a new one.
> This is not a large issue, because a user could simply specify "START WITH 1" as a very simple workaround or they could use an Integer instead of an int, but it would be nice to fix so that new users don't hit this problem.



--
This message was sent by Atlassian JIRA
(v7.6.3#76005)