net.sf.hibernate.exception.ConstraintViolationException: could not insert: [model.User#3]

Hibernate JIRA | Nathan Egge | 1 decade ago
  1. 0

    I have the following JUnit test: public void testUniqueUser() throws Exception { /* verify that violation occurs when attempting to add a user with a * non-unique email address */ User user=new User(); user.setEmail("valid@abc.com"); try { userDAO.saveUser(user); fail("saveUser didn't throw DataIntegrityViolationException"); } catch (DataIntegrityViolationException _dive) { assertNotNull(_dive); } } That uses these methods to handle the session: protected void setUp() throws Exception { super.setUp(); sessionFactory=(SessionFactory)ctx.getBean("sessionFactory"); Session session=sessionFactory.openSession(); TransactionSynchronizationManager.bindResource(sessionFactory,new SessionHolder(session)); userDAO=(UserDAO)ctx.getBean("userDAO"); } protected void tearDown() throws Exception { super.tearDown(); SessionHolder sessionHolder=(SessionHolder)TransactionSynchronizationManager.getResource(sessionFactory); Session session=sessionHolder.getSession(); session.flush(); TransactionSynchronizationManager.unbindResource(sessionFactory); SessionFactoryUtils.closeSessionIfNecessary(session,sessionFactory); sessionFactory=null; userDAO=null; } The UserDAO implements saveUser() as follows: public void saveUser(User _user) { getHibernateTemplate().saveOrUpdate(_user); } When this test is run, the testUniqueUser method executes as expected, producing the DataIntegrityViolationException. However, when session.flush() is executed, after the test has run, I get this error: [junit] ERROR - SessionImpl.execute(2400) | Could not synchronize database state with session [junit] Testsuite: dao.UserDAOTest [junit] Tests run: 1, Failures: 0, Errors: 1, Time elapsed: 0.166 sec [junit] Testcase: testUniqueUser(dao.UserDAOTest): Caused an ERROR [junit] could not insert: [model.User#3] [junit] net.sf.hibernate.exception.ConstraintViolationException: could not insert: [model.User#3] [junit] at net.sf.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:62) [junit] at net.sf.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29) [junit] at net.sf.hibernate.persister.AbstractEntityPersister.convert(AbstractEntityPersister.java:1331) [junit] at net.sf.hibernate.persister.EntityPersister.insert(EntityPersister.java:472) [junit] at net.sf.hibernate.persister.EntityPersister.insert(EntityPersister.java:436) [junit] at net.sf.hibernate.impl.ScheduledInsertion.execute(ScheduledInsertion.java:37) [junit] at net.sf.hibernate.impl.SessionImpl.execute(SessionImpl.java:2449) [junit] at net.sf.hibernate.impl.SessionImpl.executeAll(SessionImpl.java:2435) [junit] at net.sf.hibernate.impl.SessionImpl.execute(SessionImpl.java:2392) [junit] at net.sf.hibernate.impl.SessionImpl.flush(SessionImpl.java:2261) [junit] at dao.UserDAOTest.tearDown(UserDAOTest.java:45) [junit] Caused by: org.postgresql.util.PSQLException: ERROR: duplicate key violates unique constraint "vc_user_email_key" [junit] at org.postgresql.util.PSQLException.parseServerError(PSQLException.java:139) [junit] at org.postgresql.core.QueryExecutor.executeV3(QueryExecutor.java:154) [junit] at org.postgresql.core.QueryExecutor.execute(QueryExecutor.java:101) [junit] at org.postgresql.core.QueryExecutor.execute(QueryExecutor.java:43) [junit] at org.postgresql.jdbc1.AbstractJdbc1Statement.execute(AbstractJdbc1Statement.java:515) [junit] at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:50) [junit] at org.postgresql.jdbc1.AbstractJdbc1Statement.executeUpdate(AbstractJdbc1Statement.java:271) [junit] at net.sf.hibernate.impl.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:22) [junit] at net.sf.hibernate.persister.EntityPersister.insert(EntityPersister.java:462) [junit] ... 17 more It really seems like Hibernate should be trying to save the User object if saveUser threw an exception. When the test is run, a org.springframework.dao.DataIntegrityViolationException is thrown (which extends java.lang.RuntimeException) Shouldn't this be enough to tell Hibernate not to add the User object to the Session?

    Hibernate JIRA | 1 decade ago | Nathan Egge
    net.sf.hibernate.exception.ConstraintViolationException: could not insert: [model.User#3]
  2. 0

    I have the following JUnit test: public void testUniqueUser() throws Exception { /* verify that violation occurs when attempting to add a user with a * non-unique email address */ User user=new User(); user.setEmail("valid@abc.com"); try { userDAO.saveUser(user); fail("saveUser didn't throw DataIntegrityViolationException"); } catch (DataIntegrityViolationException _dive) { assertNotNull(_dive); } } That uses these methods to handle the session: protected void setUp() throws Exception { super.setUp(); sessionFactory=(SessionFactory)ctx.getBean("sessionFactory"); Session session=sessionFactory.openSession(); TransactionSynchronizationManager.bindResource(sessionFactory,new SessionHolder(session)); userDAO=(UserDAO)ctx.getBean("userDAO"); } protected void tearDown() throws Exception { super.tearDown(); SessionHolder sessionHolder=(SessionHolder)TransactionSynchronizationManager.getResource(sessionFactory); Session session=sessionHolder.getSession(); session.flush(); TransactionSynchronizationManager.unbindResource(sessionFactory); SessionFactoryUtils.closeSessionIfNecessary(session,sessionFactory); sessionFactory=null; userDAO=null; } The UserDAO implements saveUser() as follows: public void saveUser(User _user) { getHibernateTemplate().saveOrUpdate(_user); } When this test is run, the testUniqueUser method executes as expected, producing the DataIntegrityViolationException. However, when session.flush() is executed, after the test has run, I get this error: [junit] ERROR - SessionImpl.execute(2400) | Could not synchronize database state with session [junit] Testsuite: dao.UserDAOTest [junit] Tests run: 1, Failures: 0, Errors: 1, Time elapsed: 0.166 sec [junit] Testcase: testUniqueUser(dao.UserDAOTest): Caused an ERROR [junit] could not insert: [model.User#3] [junit] net.sf.hibernate.exception.ConstraintViolationException: could not insert: [model.User#3] [junit] at net.sf.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:62) [junit] at net.sf.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29) [junit] at net.sf.hibernate.persister.AbstractEntityPersister.convert(AbstractEntityPersister.java:1331) [junit] at net.sf.hibernate.persister.EntityPersister.insert(EntityPersister.java:472) [junit] at net.sf.hibernate.persister.EntityPersister.insert(EntityPersister.java:436) [junit] at net.sf.hibernate.impl.ScheduledInsertion.execute(ScheduledInsertion.java:37) [junit] at net.sf.hibernate.impl.SessionImpl.execute(SessionImpl.java:2449) [junit] at net.sf.hibernate.impl.SessionImpl.executeAll(SessionImpl.java:2435) [junit] at net.sf.hibernate.impl.SessionImpl.execute(SessionImpl.java:2392) [junit] at net.sf.hibernate.impl.SessionImpl.flush(SessionImpl.java:2261) [junit] at dao.UserDAOTest.tearDown(UserDAOTest.java:45) [junit] Caused by: org.postgresql.util.PSQLException: ERROR: duplicate key violates unique constraint "vc_user_email_key" [junit] at org.postgresql.util.PSQLException.parseServerError(PSQLException.java:139) [junit] at org.postgresql.core.QueryExecutor.executeV3(QueryExecutor.java:154) [junit] at org.postgresql.core.QueryExecutor.execute(QueryExecutor.java:101) [junit] at org.postgresql.core.QueryExecutor.execute(QueryExecutor.java:43) [junit] at org.postgresql.jdbc1.AbstractJdbc1Statement.execute(AbstractJdbc1Statement.java:515) [junit] at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:50) [junit] at org.postgresql.jdbc1.AbstractJdbc1Statement.executeUpdate(AbstractJdbc1Statement.java:271) [junit] at net.sf.hibernate.impl.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:22) [junit] at net.sf.hibernate.persister.EntityPersister.insert(EntityPersister.java:462) [junit] ... 17 more It really seems like Hibernate should be trying to save the User object if saveUser threw an exception. When the test is run, a org.springframework.dao.DataIntegrityViolationException is thrown (which extends java.lang.RuntimeException) Shouldn't this be enough to tell Hibernate not to add the User object to the Session?

    Hibernate JIRA | 1 decade ago | Nathan Egge
    net.sf.hibernate.exception.ConstraintViolationException: could not insert: [model.User#3]
  3. Speed up your debug routine!

    Automated exception search integrated into your IDE

  4. 0

    SubscriberImpl has a lazy map, named emailingProperties: <map name="emailingProperties" table="subscriberemailingproperties" lazy="true" sort="unsorted" inverse="false" cascade="all" > <key column="subscriber" > </key> <index-many-to-many class="com.fullsix.newsletter.impl.EmailingImpl" column="emailing" /> <one-to-many class="com.fullsix.newsletter.impl.BaseSubscriberEmailingPropertiesImpl" /> </map> BaseSubscriberEmailingPropertiesImpl has some properties, including a boolean property named "import_xls". Code between sessionFactory.openSession() and session.close(): I'm just calling session.delete() on an instance of a SubscriberImpl object, which emailingProperties map has not yet been initialized. Here my problem is that my "import_xls" property is not present in the database (this property has been added later, the database has not been altered yet). Of course, hibernate throws an exception (because of an underlying SQLException). However, I would expect an HibernateException here (because Hibernate did not succeeded in deleting my object), instead of a LazyInitializationException (which is the reason why my object didn't get deleted). I think that Hibernate should convert the LazyInitializationException to an HibernateException. Full stack trace of any exception that occurs: net.sf.hibernate.LazyInitializationException: Failed to lazily initialize a collection at net.sf.hibernate.collection.PersistentCollection.initialize(PersistentCollection.java:201) at net.sf.hibernate.collection.PersistentCollection.read(PersistentCollection.java:71) at net.sf.hibernate.collection.Map.values(Map.java:166) at net.sf.hibernate.type.MapType.getElementsIterator(MapType.java:28) at net.sf.hibernate.engine.Cascades.getAllElementsIterator(Cascades.java:570) at net.sf.hibernate.engine.Cascades.access$100(Cascades.java:28) at net.sf.hibernate.engine.Cascades$1.getCascadableChildrenIterator(Cascades.java:65) at net.sf.hibernate.engine.Cascades.cascadeCollection(Cascades.java:525) at net.sf.hibernate.engine.Cascades.cascade(Cascades.java:452) at net.sf.hibernate.engine.Cascades.cascade(Cascades.java:503) at net.sf.hibernate.engine.Cascades.cascade(Cascades.java:482) at net.sf.hibernate.impl.SessionImpl.doDelete(SessionImpl.java:1237) at net.sf.hibernate.impl.SessionImpl.delete(SessionImpl.java:1172) ... 54 more Caused by: net.sf.hibernate.JDBCException: could not initialize collection: [com.fullsix.newsletter.impl.SubscriberImpl.emailingProperties#00000005] at net.sf.hibernate.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:287) at net.sf.hibernate.impl.SessionImpl.initializeCollection(SessionImpl.java:3264) at net.sf.hibernate.collection.PersistentCollection.initialize(PersistentCollection.java:195) ... 66 more Caused by: org.postgresql.util.PSQLException: ERROR: column emailingpr0_.import_xls does not exist at org.postgresql.util.PSQLException.parseServerError(PSQLException.java:139) at org.postgresql.core.QueryExecutor.executeV3(QueryExecutor.java:154) at org.postgresql.core.QueryExecutor.execute(QueryExecutor.java:101) at org.postgresql.core.QueryExecutor.execute(QueryExecutor.java:43) at org.postgresql.jdbc1.AbstractJdbc1Statement.execute(AbstractJdbc1Statement.java:515) at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:50) at org.postgresql.jdbc1.AbstractJdbc1Statement.executeQuery(AbstractJdbc1Statement.java:231) at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:205) at net.sf.hibernate.impl.BatcherImpl.getResultSet(BatcherImpl.java:87) at net.sf.hibernate.loader.Loader.getResultSet(Loader.java:800) at net.sf.hibernate.loader.Loader.doQuery(Loader.java:189) at net.sf.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:133) at net.sf.hibernate.loader.Loader.loadCollection(Loader.java:915) at net.sf.hibernate.loader.Loader.loadCollection(Loader.java:890) at net.sf.hibernate.loader.OneToManyLoader.initialize(OneToManyLoader.java:93) at net.sf.hibernate.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:284) ... 68 more

    Hibernate JIRA | 1 decade ago | Frank Pavageau
    net.sf.hibernate.LazyInitializationException: Failed to lazily initialize a collection
  5. 0

    When you specify a default_scheme in the hibernate.cfg.xml the sequence generator doesn't respect the default_schema. Instead it uses the sequence in the "public" schema which is what PostgreSQL's schema search defaults to. Here is the generated SQL from when public.items_id_sequence exists: Hibernate: select nextval ('items_id_sequence') Hibernate: insert into beta2.items (name, id) values (?, ?) Note that the first line doens't specify a schema. Here is the generated SQL and following log lines when public.items_id_sequence doesn't exists: Hibernate: select nextval ('items_id_sequence') Sep 10, 2004 12:07:45 PM net.sf.hibernate.util.JDBCExceptionReporter logExceptions WARNING: SQL Error: 0, SQLState: 42P01 Sep 10, 2004 12:07:45 PM net.sf.hibernate.util.JDBCExceptionReporter logExceptions SEVERE: ERROR: relation "items_id_sequence" does not exist Sep 10, 2004 12:07:45 PM net.sf.hibernate.util.JDBCExceptionReporter logExceptions WARNING: SQL Error: 0, SQLState: 42P01 Sep 10, 2004 12:07:45 PM net.sf.hibernate.util.JDBCExceptionReporter logExceptions SEVERE: ERROR: relation "items_id_sequence" does not exist Sep 10, 2004 12:07:45 PM net.sf.hibernate.JDBCException <init> SEVERE: Could not save object org.postgresql.util.PSQLException: ERROR: relation "items_id_sequence" does not exist at org.postgresql.util.PSQLException.parseServerError(PSQLException.java:139) at org.postgresql.core.QueryExecutor.executeV3(QueryExecutor.java:154) at org.postgresql.core.QueryExecutor.execute(QueryExecutor.java:101) at org.postgresql.core.QueryExecutor.execute(QueryExecutor.java:43) at org.postgresql.jdbc1.AbstractJdbc1Statement.execute(AbstractJdbc1Statement.java:515) at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:50) at org.postgresql.jdbc1.AbstractJdbc1Statement.executeQuery(AbstractJdbc1Statement.java:231) at net.sf.hibernate.id.SequenceGenerator.generate(SequenceGenerator.java:69) at net.sf.hibernate.impl.SessionImpl.saveWithGeneratedIdentifier(SessionImpl.java:765) at net.sf.hibernate.impl.SessionImpl.save(SessionImpl.java:738) at net.sf.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:1388) at test.Something.main(Something.java:24) Exception in thread "main" net.sf.hibernate.JDBCException: Could not save object at net.sf.hibernate.impl.SessionImpl.saveWithGeneratedIdentifier(SessionImpl.java:783) at net.sf.hibernate.impl.SessionImpl.save(SessionImpl.java:738) at net.sf.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:1388) at test.Something.main(Something.java:24) Caused by: org.postgresql.util.PSQLException: ERROR: relation "items_id_sequence" does not exist at org.postgresql.util.PSQLException.parseServerError(PSQLException.java:139) at org.postgresql.core.QueryExecutor.executeV3(QueryExecutor.java:154) at org.postgresql.core.QueryExecutor.execute(QueryExecutor.java:101) at org.postgresql.core.QueryExecutor.execute(QueryExecutor.java:43) at org.postgresql.jdbc1.AbstractJdbc1Statement.execute(AbstractJdbc1Statement.java:515) at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:50) at org.postgresql.jdbc1.AbstractJdbc1Statement.executeQuery(AbstractJdbc1Statement.java:231) at net.sf.hibernate.id.SequenceGenerator.generate(SequenceGenerator.java:69) at net.sf.hibernate.impl.SessionImpl.saveWithGeneratedIdentifier(SessionImpl.java:765) ... 3 more After some debugging I found that the params passed into net.sf.hibernate.id.SequenceGenerator.configure(...) do not contain a property under the "schema" key, which seems to be why SequenceGenerator.generate(..) doesn't know about the schema.

    Hibernate JIRA | 1 decade ago | Sandy McArthur
    org.postgresql.util.PSQLException: ERROR: relation "items_id_sequence" does not exist

    Not finding the right solution?
    Take a tour to get the most out of Samebug.

    Tired of useless tips?

    Automated exception search integrated into your IDE

    Root Cause Analysis

    1. org.postgresql.util.PSQLException

      ERROR: duplicate key violates unique constraint "vc_user_email_key"

      at org.postgresql.util.PSQLException.parseServerError()
    2. PostgreSQL JDBC Driver
      QueryExecutor.execute
      1. org.postgresql.util.PSQLException.parseServerError(PSQLException.java:139)
      2. org.postgresql.core.QueryExecutor.executeV3(QueryExecutor.java:154)
      3. org.postgresql.core.QueryExecutor.execute(QueryExecutor.java:101)
      4. org.postgresql.core.QueryExecutor.execute(QueryExecutor.java:43)
      4 frames
    3. org.postgresql.jdbc1
      AbstractJdbc1Statement.execute
      1. org.postgresql.jdbc1.AbstractJdbc1Statement.execute(AbstractJdbc1Statement.java:515)
      1 frame
    4. PostgreSQL JDBC Driver
      AbstractJdbc2Statement.execute
      1. org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:50)
      1 frame
    5. org.postgresql.jdbc1
      AbstractJdbc1Statement.executeUpdate
      1. org.postgresql.jdbc1.AbstractJdbc1Statement.executeUpdate(AbstractJdbc1Statement.java:271)
      1 frame
    6. net.sf.hibernate
      SessionImpl.flush
      1. net.sf.hibernate.impl.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:22)
      2. net.sf.hibernate.persister.EntityPersister.insert(EntityPersister.java:462)
      3. net.sf.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:62)
      4. net.sf.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
      5. net.sf.hibernate.persister.AbstractEntityPersister.convert(AbstractEntityPersister.java:1331)
      6. net.sf.hibernate.persister.EntityPersister.insert(EntityPersister.java:472)
      7. net.sf.hibernate.persister.EntityPersister.insert(EntityPersister.java:436)
      8. net.sf.hibernate.impl.ScheduledInsertion.execute(ScheduledInsertion.java:37)
      9. net.sf.hibernate.impl.SessionImpl.execute(SessionImpl.java:2449)
      10. net.sf.hibernate.impl.SessionImpl.executeAll(SessionImpl.java:2435)
      11. net.sf.hibernate.impl.SessionImpl.execute(SessionImpl.java:2392)
      12. net.sf.hibernate.impl.SessionImpl.flush(SessionImpl.java:2261)
      12 frames
    7. dao
      UserDAOTest.tearDown
      1. dao.UserDAOTest.tearDown(UserDAOTest.java:45)
      1 frame