I’m really struggling to understand why I’m getting this error. I’m getting it referring to the GLOBAL_ID field in my Artist Entity. I think I must be missing something about how the JPA inner workings are. Let’s consider these two Entities.
@Entity
public class Music {
@Id
private String MYID;
@Column(unique=true)
private String GLOBAL_ID;
@ManyToOne(cascade=CascadeType.ALL) @JoinColumn(name="ARTIST_ID")
private Artist artist;
}
@Entity
public class Artist {
@Id
private String MYID;
@Column(unique=true)
private String GLOBAL_ID;
}
Before I try persist Music. I lookup the database by the Artist GLOBAL_ID if already exists. If exists I get the instance I got from DB and set the artist in Music. And after that, I do EntityManager.merge(Music). So, I throught that even if I got this artist from DB and the switched the new incoming artist with the existing one, as the Music was new the entity manager would be trying to persist it again. So, I did it differently …
I did the artist lookup, and when there was a artist with the same GLOBAL_ID in the DB, I set the artist field in the Music as null and merged Music. after that I got the managed Music entity and set the existing artist I had previously looked up. No success …
I’m merging like this …. Music = EntityManager.merge(Music)
I have gone through this code all day and could not find out what I’m doing wrong. Isn’t JPA supposed to do not try to persist and entity already managed ? I don’t know. I would appreciate if somebody could help me with this.
Besides a trillion different things I already tried I tried to detach the artist found from DB, but I was not able to re-merge it later.
Thanks in advance for any help,
Regards,
Here is the code that deals with persistence and the stack trace below.
Ok, I’ll try to post and explain …
This is an importing bean, that in a loop reads the mp3 files from a directory, gets the ID3 tags from it and constructs the Music class from it.
This is the code that deals with JPA. I modified it already a couple times to get rid of the error. Now when the Music is new with an existing artist, I remove the artist reference from Music and after the music is merged I link it to the existing artist. Before, I was just switching the artist with the existing one and persisting altogether.
I can see all the log messages with satysfying IDs and all that. I mean that I can notice that the artist query finds an existing artist. Below is the stacktrace. Thanks again for taking a look at it …
if (mediaMusic.getMYID() == null || mediaMusic.getMYID().equals("")) {
Music oldMusic = null;
Query mq = null;
if (mediaMusic.getGLOBAL_ID() != null && !mediaMusic.getGLOBAL_ID().equals("")) {
mq = em.createNamedQuery(Music.QUERY_FIND_BY_GLOBAL_ID);
mq.setParameter(Music.QUERY_PARAMETER_GLOBAL_ID, mediaMusic.getGLOBAL_ID());
Iterator musicsSameGLID = mq.getResultList().iterator();
if (musicsSameGLID.hasNext()) {
oldMusic = (Music) musicsSameGLID.next();
}
} else if (mediaMusic.getTitle() != null && !mediaMusic.getTitle().equals("")) {
mq = em.createNamedQuery(Music.QUERY_FIND_BY_TITLE);
mq.setParameter(Music.QUERY_PARAMETER_TITLE, mediaMusic.getTitle().toUpperCase());
Iterator existingMusics = mq.getResultList().iterator();
Music existingMusic = null;
while (existingMusics.hasNext()) {
existingMusic = (Music) existingMusics.next();
if (mediaMusic.getArtist() != null && existingMusic.getArtist() != null
&& mediaMusic.getArtist().getGLOBAL_ID() != null
&& mediaMusic.getArtist().getGLOBAL_ID().equals(existingMusic.getArtist().getGLOBAL_ID())) {
oldMusic = existingMusic;
break;
} else if (existingMusic.getArtist() != null && mediaMusic.getArtist() != null
&& existingMusic.getArtist().getName().equals(mediaMusic.getArtist().getName())) {
oldMusic = existingMusic;
break;
}
}
}
if (oldMusic != null) {
mediaMusic = oldMusic;
}
}
// IF IT IS A NEW ARTIST, CHECKING FOR EXISTING ONE
if (mediaMusic.getArtist() != null
&& (mediaMusic.getArtist().getMYID() == null || mediaMusic.getArtist().getMYID().equals(""))) {
if (mediaMusic.getArtist().getGLOBAL_ID() != null
&& !mediaMusic.getArtist().getGLOBAL_ID().equals("")) {
Query aq = em.createNamedQuery(Artist.QUERY_FIND_BY_GLOBAL_ID);
aq.setParameter(Artist.GLOBAL_ID_QUERY_PARAMETER, mediaMusic.getArtist().getGLOBAL_ID());
Iterator existingArtists = aq.getResultList().iterator();
if (existingArtists.hasNext()) {
// Persiste primeiro sem artista
logger.log(Level.INFO, "Artista {0}, ArtistaGLID: {1} para a musica MYID: {2} Titulo: {3} found in DB", new Object[]{mediaMusic.getArtist().getName(), mediaMusic.getArtist().getGLOBAL_ID(), mediaMusic.getMYID(), mediaMusic.getTitle()});
if (mediaMusic.getMYID() == null || mediaMusic.getMYID().equals("")) {
artistaExistente = (Artist) existingArtists.next();
mediaMusic.setArtist(null);
logger.log(Level.INFO, "Inserting and removing Artist: New artist is {0}", mediaMusic.getArtist());
} else {
mediaMusic.setArtist((Artist)existingArtists.next());
}
}
}
}
mediaMusic = em.merge(mediaMusic);
// 20110424 TRYING TO LINK EXISTING ARTIST AFTER MUSIC IN DB
if (artistaExistente != null)) {
logger.log(Level.INFO, "Music already in BD with o MYID: {0}", mediaMusic.getMYID());
logger.log(Level.INFO, "Adding artist {0} MYID: {1}", new Object[]{artistaExistente.getName(), artistaExistente.getMYID()});
mediaMusic.setArtist(artistaExistente);
logger.info("After artist had been added to Music");
}
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '01809552-4f87-45b0-a45b0-afff-2c6f0730a3be' for key 'GLOBAL_ID'
at sun.reflect.GeneratedConstructorAccessor178.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:407)
at com.mysql.jdbc.Util.getInstance(Util.java:382)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1039)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3603)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3535)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1989)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2150)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2626)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2119)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2415)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2333)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2318)
at com.sun.gjc.spi.base.PreparedStatementWrapper.executeUpdate(PreparedStatementWrapper.java:120)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:789)
... 74 more
|#]
[#|2011-04-25T10:32:01.004-0300|SEVERE|oracle-glassfish3.1|co.bmq.media.beans.MediaMaintenanceBean|_ThreadID=53;_Thr$
javax.ejb.EJBException: Transaction aborted
at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5121)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4894)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2039)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1990)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:222)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.jav$
at $Proxy201.updateMedia(Unknown Source)
at co.bmq.media.beans.__EJB31_Generated__MediaStorageServiceBean__Intf____Bean__.updateMedia(Unknown Source)
at co.bmq.media.beans.MediaMaintenanceBean.checkImportDir(MediaMaintenanceBean.java:98)
at sun.reflect.GeneratedMethodAccessor374.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1052)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManag
er.java:1124)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:5367)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:619)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:801)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:571)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doAround(SystemInterceptorProxy.java:162)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundTimeout(SystemInterceptorProxy.java:149)
at sun.reflect.GeneratedMethodAccessor373.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:862)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:801)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:371)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:5339)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:5327)
at com.sun.ejb.containers.BaseContainer.callEJBTimeout(BaseContainer.java:4033)
at com.sun.ejb.containers.EJBTimerService.deliverTimeout(EJBTimerService.java:1835)
at com.sun.ejb.containers.EJBTimerService.access$100(EJBTimerService.java:108)
at com.sun.ejb.containers.EJBTimerService$TaskExpiredWork.run(EJBTimerService.java:2708)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Caused by: javax.transaction.RollbackException: Transaction marked for rollback.
at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:475)
at com.sun.enterprise.transaction.JavaEETransactionManagerSimplified.commit(JavaEETransactionManagerSimplified.java:$
at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5115)
... 37 more
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.2.0.v20110202-r8913): org.eclipse.persistence.exce$
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '01809552-4f552-4f87-45b0-afff-2c6f0730a3be' for key 'GLOBAL_ID'
Error Code: 1062
Call: INSERT INTO ARTIST (MYID, ANNOTATION, COMMENT, COUNTRY, GENDER, LASTDATANORMALIZATIONDATE, LASTUPDATEDON, LIKES, GLOBAL_ID, NAME, SINCEDATE, TAGS, TODATE, TYPE, ENTITY_UID, VERSION) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
bind => [14 parameters bound]
Query: InsertObjectQuery(co.bmq.media.entity.Artist@3741c26)
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:324)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:798)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeNoSelect(DatabaseAccessor.java:864)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:583)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:526)
at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:1729)
at org.eclipse.persistence.sessions.server.ClientSession.executeCall(ClientSession.java:234)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.ja$
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.ja$
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.insertObject(DatasourceCallQueryMechanism.j$
at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:162)
at org.eclipse.persistence.internal.queries.StatementQueryMechanism.insertObject(StatementQueryMechanism.java:177)
at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.insertObjectForWrite(DatabaseQueryMechanism.java:$
at org.eclipse.persistence.queries.InsertObjectQuery.executeCommit(InsertObjectQuery.java:80)
at org.eclipse.persistence.queries.InsertObjectQuery.executeCommitWithChangeSet(InsertObjectQuery.java:90)
at org.eclipse.persistence.internal.queries.DatabaseQueryMechanism.executeWriteWithChangeSet(DatabaseQueryMechanism.$
at org.eclipse.persistence.queries.WriteObjectQuery.executeDatabaseQuery(WriteObjectQuery.java:58)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:808)
at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:711)
at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWorkObjectLevelModifyQuery(ObjectLevelModif$
at org.eclipse.persistence.queries.ObjectLevelModifyQuery.executeInUnitOfWork(ObjectLevelModifyQuery.java:85)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2842)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1521)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1503)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1463)
at org.eclipse.persistence.internal.sessions.CommitManager.commitNewObjectsForClassWithChangeSet(CommitManager.java:$
at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsForClassWithChangeSet(CommitManager.java:$
at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsWithChangeSet(CommitManager.java:136)
at org.eclipse.persistence.internal.sessions.AbstractSession.writeAllObjectsWithChangeSet(AbstractSession.java:3766)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabase(UnitOfWorkImpl.java:1404)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.commitToDatabase(RepeatableWriteUnitOfWork.ja$
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1511)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.issueSQLbeforeCompletion(UnitOfWorkImpl.java:3115)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.issueSQLbeforeCompletion(RepeatableWriteUnitO$
at org.eclipse.persistence.transaction.AbstractSynchronizationListener.beforeCompletion(AbstractSynchronizationListe$
at org.eclipse.persistence.transaction.JTASynchronizationListener.beforeCompletion(JTASynchronizationListener.java:6$
at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:437)
... 39 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '01809552-4f87-45b0-a$
at sun.reflect.GeneratedConstructorAccessor178.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:407)
at com.mysql.jdbc.Util.getInstance(Util.java:382)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1039)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3603)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3535)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1989)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2150)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2626)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2119)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2415)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2333)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2318)
at com.sun.gjc.spi.base.PreparedStatementWrapper.executeUpdate(PreparedStatementWrapper.java:120)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:789)
... 74 more
First, thanks for everyone that participated. Actually there was not enough detail for you guys to find out and it was very specific to my project.
The problem was: I have more bi-directional relationships in this object, like … Music -> AlbumTrack -> Album -> Artist. My problem was with this artist here that I had not modified with the one existing from the database and by the logs it was very hard to detect which object was causing it.
Thanks again guys