简体   繁体   中英

JPA: InvalidStateException Error + Composite Key/EmbeddableId/Sequence Generated IDs

I currently have a schema set up with my database and Java Application using OpenJPA that works most of the time, but sometimes I get the error for a few users:

org.apache.openjpa.persistence.InvalidStateException: Attempt to set column "table1.ID" to two different values

table1 actually has a composite Key (two values) and each value in that key is a foreign key to another table. I used RSA (Rational Software Architect) to set up the entities for me (generated code). It set up a PK class (using @EmbeddableId to reference the PK class) in the Entity class for table1, and then two @ManyToOne relationships in the same table1 Entity class (and also in the entity classes that those columns reference) since they are foreign keys

Now, as I mentioned above, each value in the composite key is a foreign key. Well, each of those foreign keys is actually generated using an outside Sequencer in their own entity classes. I am using DB2 and using @GeneratedValue on the columns (ie the IDs in table2's and table3's entity classes). I use strategy=GenerationType.SEQUENCE also for each.

Again, everything works USUALLY but not 100% of the time and I'm unsure why. I have gotten rid of this error by wiping out everything and resetting the Sequence Generators, but I know this is definitely not a solution. Could it have something to do with the fact that the two Composite Key values in the database are foreign keys to columns which were generated using a sequence, but the PK entity might not know?

I have noticed too that it only works for users who have a record in the Users table (one of the foreign keys mentioned above is to a Users table, while the other FK is to another table). What happens, if a user is not in the table, it creates one, something like:

User newUser = userManager.getNewUser();
newUser.setName(..);
newUser.setEmail(..);
...

When it's done, the PK class I mentioned above has a new instance of that created, which is then called into another table. The ID from the user above is passed into the PK. Like:

PK newPK = pkManager.getNewPK();
newPk.setAID(newUser.getID());

Has anybody run into this? Any solutions?

Sorry, fixed the problem. I went through my code and realized I had forgot to refactor one line of code (change in data model).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM