-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 4 posts ] 
Author Message
 Post subject: Should bulk delete cascade to list of composite-elements?
PostPosted: Wed May 31, 2006 4:26 pm 
Newbie

Joined: Fri May 26, 2006 10:55 am
Posts: 4
I'm getting an error when I bulk delete an entity with a list of composite-elements. The list has cascade="all-delete-orphan" set. If the elements of the lists are removed first (and the session flushed), deleting the entities succeeds.

Have I configured my model wrong for the deletion of the entities to cascade to the list elements or is it simply not supported?

Is it possible to bulk delete all of the list elements without iterating over each entity?

A test case for the hql test suite is below.

Hibernate version: 3.2.0 CR2, but behaves the same with 3.1.3

Database version: HSQLDB-1.8.0

Mapping documents:
Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping SYSTEM "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="org.hibernate.test.hql">
   <class name="EntityWithCompositeElementList">
      <id name="id">
         <generator class="native"/>
      </id>
      <list name="names" table="names" lazy="false" cascade="all-delete-orphan">
         <key column="eid"/>
         <list-index column="idx"/>
         <composite-element class="Name">
            <property name="first"/>
            <property name="initial"/>
            <property name="last"/>
         </composite-element>
      </list>
   </class>
</hibernate-mapping>


Test code for org.hibernate.test.hql.BulkManipulationTest:
Only relevant test mapping added here, and show sql turned on.
Code:
   protected String[] getMappings() {
      return new String[] {"hql/EntityWithCompositeElementList.hbm.xml"};
   }
   public java.util.Properties getExtraProperties() {
      java.util.Properties cfg = new java.util.Properties();
      cfg.setProperty(org.hibernate.cfg.Environment.SHOW_SQL, "true");
      return cfg;
   }

Test case:
Code:
   public void testDeleteWithCascadedCompositeEntities() {
      Session s = openSession();
      Transaction t = s.beginTransaction();

        EntityWithCompositeElementList ewce = new EntityWithCompositeElementList();
        s.save(ewce);

      ewce.getNames().add(new Name("1", '1', "One"));
      ewce.getNames().add(new Name("2", '2', "Two"));

      t.commit();
      s.close();

      // delete the entities, expecting cascade
      s = openSession();
      t = s.beginTransaction();

      // the following allows the test to succeed
      //ewce = (EntityWithCompositeElementList)
      //   s.createQuery("from EntityWithCompositeElementList").uniqueResult();
      //ewce.getNames().clear();
      //s.flush();

      s.createQuery( "delete EntityWithCompositeElementList" ).executeUpdate();

      t.commit();
      s.close();
   }


EntityWithCompositeElementList.java
Code:
package org.hibernate.test.hql;

import java.util.List;
import java.util.LinkedList;

public class EntityWithCompositeElementList {
   int id;
   List names = new LinkedList();
   protected EntityWithCompositeElementList() {}
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public List getNames() {
      return names;
   }
   public void setNames(List names) {
      this.names = names;
   }
}


Full stack trace of any exception that occurs:
Code:
org.hibernate.exception.ConstraintViolationException: could not execute update query at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43) at org.hibernate.hql.ast.exec.BasicExecutor.execute(BasicExecutor.java:84) at org.hibernate.hql.ast.QueryTranslatorImpl.executeUpdate(QueryTranslatorImpl.java:391) at org.hibernate.engine.query.HQLQueryPlan.performExecuteUpdate(HQLQueryPlan.java:259) at org.hibernate.impl.SessionImpl.executeUpdate(SessionImpl.java:1143) at org.hibernate.impl.QueryImpl.executeUpdate(QueryImpl.java:94) at org.hibernate.test.hql.BulkManipulationTest.testDeleteWithCascadedCompositeEntities(BulkManipulationTest.java:1060) at org.hibernate.test.TestCase.runTest(TestCase.java:161)Caused by: java.sql.SQLException: Integrity constraint violation FK63BD748353F557D table: NAMES in statement [delete from EntityWithCompositeElementList] at org.hsqldb.jdbc.Util.throwError(Unknown Source) at org.hsqldb.jdbc.jdbcPreparedStatement.executeUpdate(Unknown Source) at org.hibernate.hql.ast.exec.BasicExecutor.execute(BasicExecutor.java:75) ... 21 more


The generated SQL (show_sql=true) and debug level Hibernate log:
Code:
16:07:21,149  INFO Environment:499 - Hibernate 3.2 cr2
16:07:21,159  INFO Environment:517 - loaded properties from resource hibernate.properties: {hibernate.connection.driver_class=org.hsqldb.jdbcDriver, hibernate.cache.provider_class=org.hibernate.cache.HashtableCacheProvider, hibernate.max_fetch_depth=1, hibernate.dialect=org.hibernate.dialect.HSQLDialect, hibernate.jdbc.use_streams_for_binary=true, hibernate.format_sql=true, hibernate.query.substitutions=yes 'Y', no 'N', hibernate.proxool.pool_alias=pool1, hibernate.connection.username=sa, hibernate.cache.region_prefix=hibernate.test, hibernate.connection.url=jdbc:hsqldb:., hibernate.bytecode.use_reflection_optimizer=false, hibernate.connection.password=****, hibernate.jdbc.batch_versioned_data=true, hibernate.connection.pool_size=1}
16:07:21,159  INFO Environment:548 - using java.io streams to persist binary types
16:07:21,159  INFO Environment:666 - Bytecode provider name : cglib
16:07:21,169  INFO Environment:583 - using JDK 1.4 java.sql.Timestamp handling
16:07:21,199  INFO Dialect:141 - Using dialect: org.hibernate.dialect.HSQLDialect
16:07:21,420  INFO Configuration:488 - Reading mappings from resource: org/hibernate/test/hql/EntityWithCompositeElementList.hbm.xml
16:07:21,770  INFO HbmBinder:298 - Mapping class: org.hibernate.test.hql.EntityWithCompositeElementList -&gt; EntityWithCompositeElementList
16:07:21,800  INFO HbmBinder:1410 - Mapping collection: org.hibernate.test.hql.EntityWithCompositeElementList.names -&gt; names
16:07:21,921  INFO DriverManagerConnectionProvider:41 - Using Hibernate built-in connection pool (not for production use!)
16:07:21,931  INFO DriverManagerConnectionProvider:42 - Hibernate connection pool size: 1
16:07:21,931  INFO DriverManagerConnectionProvider:45 - autocommit mode: false
16:07:21,931  INFO DriverManagerConnectionProvider:80 - using driver: org.hsqldb.jdbcDriver at URL: jdbc:hsqldb:.
16:07:21,931  INFO DriverManagerConnectionProvider:86 - connection properties: {user=sa, password=****}
16:07:22,261  INFO SettingsFactory:79 - RDBMS: HSQL Database Engine, version: 1.8.0
16:07:22,271  INFO SettingsFactory:80 - JDBC driver: HSQL Database Engine Driver, version: 1.8.0
16:07:22,271  INFO Dialect:141 - Using dialect: org.hibernate.dialect.HSQLDialect
16:07:22,281  INFO TransactionFactoryFactory:31 - Using default transaction strategy (direct JDBC transactions)
16:07:22,281  INFO TransactionManagerLookupFactory:33 - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
16:07:22,281  INFO SettingsFactory:127 - Automatic flush during beforeCompletion(): disabled
16:07:22,281  INFO SettingsFactory:131 - Automatic session close at end of transaction: disabled
16:07:22,291  INFO SettingsFactory:138 - JDBC batch size: 15
16:07:22,291  INFO SettingsFactory:141 - JDBC batch updates for versioned data: enabled
16:07:22,291  INFO SettingsFactory:146 - Scrollable result sets: enabled
16:07:22,291  INFO SettingsFactory:154 - JDBC3 getGeneratedKeys(): disabled
16:07:22,291  INFO SettingsFactory:162 - Connection release mode: auto
16:07:22,291  INFO SettingsFactory:186 - Maximum outer join fetch depth: 1
16:07:22,291  INFO SettingsFactory:189 - Default batch fetch size: 1
16:07:22,291  INFO SettingsFactory:193 - Generate SQL with comments: disabled
16:07:22,291  INFO SettingsFactory:197 - Order SQL updates by primary key: disabled
16:07:22,291  INFO SettingsFactory:358 - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
16:07:22,301  INFO ASTQueryTranslatorFactory:24 - Using ASTQueryTranslatorFactory
16:07:22,301  INFO SettingsFactory:205 - Query language substitutions: {no='N', yes='Y'}
16:07:22,301  INFO SettingsFactory:211 - Second-level cache: enabled
16:07:22,301  INFO SettingsFactory:215 - Query cache: disabled
16:07:22,301  INFO SettingsFactory:345 - Cache provider: org.hibernate.cache.HashtableCacheProvider
16:07:22,301  INFO SettingsFactory:230 - Optimize cache for minimal puts: disabled
16:07:22,311  INFO SettingsFactory:235 - Cache region prefix: hibernate.test
16:07:22,311  INFO SettingsFactory:239 - Structured second-level cache entries: disabled
16:07:22,321  INFO SettingsFactory:259 - Echoing all SQL to stdout
16:07:22,321  INFO SettingsFactory:266 - Statistics: disabled
16:07:22,321  INFO SettingsFactory:270 - Deleted entity synthetic identifier rollback: disabled
16:07:22,321  INFO SettingsFactory:285 - Default entity-mode: pojo
16:07:22,391  INFO SessionFactoryImpl:161 - building session factory
16:07:22,782  INFO SessionFactoryObjectFactory:82 - Not binding factory to JNDI, no JNDI name configured
16:07:22,792  INFO SchemaExport:152 - Running hbm2ddl schema export
16:07:22,802 DEBUG SchemaExport:168 - import file not found: /import.sql
16:07:22,802  INFO SchemaExport:177 - exporting generated schema to database
16:07:22,802 DEBUG SchemaExport:301 -
    alter table names
        drop constraint FK63BD748353F557D
16:07:22,802 DEBUG SchemaExport:286 - Unsuccessful: alter table names drop constraint FK63BD748353F557D
16:07:22,802 DEBUG SchemaExport:287 - Table not found: NAMES in statement [alter table names]
16:07:22,802 DEBUG SchemaExport:301 -
    drop table EntityWithCompositeElementList if exists
16:07:22,812 DEBUG SchemaExport:301 -
    drop table names if exists
16:07:22,812 DEBUG SchemaExport:301 -
    create table EntityWithCompositeElementList (
        id integer generated by default as identity (start with 1),
        primary key (id)
    )
16:07:22,812 DEBUG SchemaExport:301 -
    create table names (
        eid integer not null,
        first varchar(255),
        initial char(1),
        last varchar(255),
        idx integer not null,
        primary key (eid, idx)
    )
16:07:22,822 DEBUG SchemaExport:301 -
    alter table names
        add constraint FK63BD748353F557D
        foreign key (eid)
        references EntityWithCompositeElementList
16:07:22,822  INFO SchemaExport:194 - schema export complete
Hibernate:
    insert
    into
        EntityWithCompositeElementList
        (id)
    values
        (null)
Hibernate:
    call identity()
Hibernate:
    insert
    into
        names
        (eid, idx, first, initial, last)
    values
        (?, ?, ?, ?, ?)
Hibernate:
    insert
    into
        names
        (eid, idx, first, initial, last)
    values
        (?, ?, ?, ?, ?)
Hibernate:
    delete
    from
        EntityWithCompositeElementList
16:07:23,232  WARN JDBCExceptionReporter:71 - SQL Error: -8, SQLState: 23000
16:07:23,232 ERROR JDBCExceptionReporter:72 - Integrity constraint violation FK63BD748353F557D table: NAMES in statement [delete from EntityWithCompositeElementList]
16:07:23,262  INFO SessionFactoryImpl:769 - closing
16:07:23,262  INFO DriverManagerConnectionProvider:147 - cleaning up connection pool: jdbc:hsqldb:.
16:07:23,262  INFO SchemaExport:152 - Running hbm2ddl schema export
16:07:23,262 DEBUG SchemaExport:168 - import file not found: /import.sql
16:07:23,262  INFO SchemaExport:177 - exporting generated schema to database
16:07:23,262 DEBUG SchemaExport:301 -
    alter table names
        drop constraint FK63BD748353F557D
16:07:23,262 DEBUG SchemaExport:301 -
    drop table EntityWithCompositeElementList if exists
16:07:23,272 DEBUG SchemaExport:301 -
    drop table names if exists
16:07:23,272  INFO SchemaExport:194 - schema export complete


Top
 Profile  
 
 Post subject:
PostPosted: Wed May 31, 2006 5:56 pm 
Regular
Regular

Joined: Mon May 22, 2006 2:30 pm
Posts: 74
When you use HQL/SQL directly to perform an operation against the database, you aren't working with Hibernate "persistent objects", so any mappings which include cascade behaviour are irrelevant. You can perform a bulk delete if the relationship is 2-way, so that there is a way to build a query that says to delete all list elements where the "parent" id is equal to some value. The way I dealt with a similar scenario was to modify the table definitions to CASCADE deletes. I let the database deal with maintaining data consistency by deleting the "children".


Top
 Profile  
 
 Post subject:
PostPosted: Wed May 31, 2006 7:22 pm 
Newbie

Joined: Fri May 26, 2006 10:55 am
Posts: 4
hibernate_user wrote:
When you use HQL/SQL directly to perform an operation against the database, you aren't working with Hibernate "persistent objects", so any mappings which include cascade behaviour are irrelevant.

I did find a JIRA issue for the "Ability to specify cascading in HQL delete", but it doesn't look implemented. I see the distinction now though, thanks.

Quote:
The way I dealt with a similar scenario was to modify the table definitions to CASCADE deletes. I let the database deal with maintaining data consistency by deleting the "children".

Is it possible to do this via the mapping files, or Hibernate API? I would hate to have to connect to the DB after creating it, to modify definitions. One reason for this is that, like the hql test suite, my unit tests work on a db in memory, created each time a test suite is run.


Top
 Profile  
 
 Post subject: Any update?
PostPosted: Thu Nov 01, 2007 12:22 pm 
Newbie

Joined: Mon Apr 09, 2007 12:25 pm
Posts: 19
Location: Boston, MA
Any update on this issue?

Hibernate version: 3.2.5
HSQL version: 1.8

I would like to use these two in combination during unit testing. I am using SchemaExport on integration test startup to generate my schema, but even with cascade="delete" set, I'm noticing that the generated HSQL DDL does not include cascade deletes:

Code:
<session-factory>
   <property name="hibernate.jdbc.batch_size">0</property>
   <property name="myeclipse.connection.profile">HSQL Driver</property>
   <property name="connection.url">jdbc:hsqldb:mem:DBSHR</property>
   <property name="connection.username">sa</property>
   <property name="connection.password"></property>
   <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
   <property name="connection.autocommit">true</property>
   <property name="dialect">org.hibernate.dialect.HSQLDialect</property>
   <property name="hbm2ddl.auto">create-drop</property>
   <property name="show_sql">true</property>
   <mapping
      resource="com/fidelity/shares/domain/ServiceProvider.hbm.xml" />
   <mapping resource="com/fidelity/shares/domain/TaxEntity.hbm.xml" />
   <mapping resource="com/fidelity/shares/domain/Holding.hbm.xml" />
   <mapping resource="com/fidelity/shares/domain/AccessType.hbm.xml" />
   <mapping resource="com/fidelity/shares/domain/Confirmation.hbm.xml" />
   <mapping resource="com/fidelity/shares/domain/ServiceProviderElection.hbm.xml" />
</session-factory>


Code:
<hibernate-mapping default-lazy="false" default-cascade="delete">
   <class name="com.fidelity.shares.domain.ServiceProviderElection" table="service_provider_election" lazy="false">
      <id name="id" column="id"></id>
      <many-to-one name="accessType" column="accessType"/>
      <many-to-one name="serviceProvider" column="service_provider_id" ></many-to-one>
      <many-to-one name="confirmInfo" column="confirmation_id"></many-to-one>
      <many-to-one name="taxEntity" column="tax_entity_id"></many-to-one>
   </class>
</hibernate-mapping>


Here's the resulting schema export:

Code:
create table service_provider_election (id bigint not null, accessType bigint, service_provider_id bigint, confirmation_id bigint, tax_entity_id bigint, primary key (id))
alter table service_provider_election add constraint FKDECD2B9D6CCF1BE5 foreign key (confirmation_id) references confirmation
alter table service_provider_election add constraint FKDECD2B9D558C2C66 foreign key (tax_entity_id) references tax_entity
alter table service_provider_election add constraint FKDECD2B9D2E28267 foreign key (accessType) references access_type
alter table service_provider_election add constraint FKDECD2B9D48CA093A foreign key (service_provider_id) references service_provider


No ON DELETE CASCADES. :(


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 4 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.