-->
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.  [ 3 posts ] 
Author Message
 Post subject: Peculiar error for foreign key constraint [many-to-one]
PostPosted: Tue Sep 30, 2008 8:52 am 
Newbie

Joined: Tue Sep 30, 2008 6:25 am
Posts: 2
Location: Goa
Hibernate version: 3.2.3

Mapping documents:
Mother.hbm.xml
Child.hbm.xml


Full stack trace of any exception that occurs:
Code:
- Hibernate 3.2.3
- loaded properties from resource hibernate.properties: {hibernate.connection.username=db2inst1, hibernate.connection.password=****, hibernate.dialect=org.hibernate.dialect.DB2Dialect, hibernate.connection.url=jdbc:db2://10.244.6.207:50000/pavan, hibernate.bytecode.use_reflection_optimizer=false, hibernate.connection.driver_class=com.ibm.db2.jcc.DB2Driver, hibernate.hbm2ddl.auto=create}
- Bytecode provider name : cglib
- using JDK 1.4 java.sql.Timestamp handling
- configuring from resource: /hibernate.cfg.xml
- Configuration resource: /hibernate.cfg.xml
- Reading mappings from resource : Mother.hbm.xml
- Mapping class: Mother -> Mother
- Reading mappings from resource : Child.hbm.xml
- Mapping class: Child -> Child
- Configured SessionFactory: null
- C3P0 using driver: com.ibm.db2.jcc.DB2Driver at URL: jdbc:db2://10.244.6.207:50000/pavan
- Connection properties: {user=db2inst1, password=****}
- autocommit mode: false
- MLog clients using log4j logging.
- Initializing c3p0-0.9.1.2 [built 21-May-2007 15:04:56; debug? true; trace: 10]
- JDBC isolation level: READ_COMMITTED
- Initializing c3p0 pool... com.mchange.v2.c3p0.PoolBackedDataSource@ff1526c1 [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@9a6987d2 [ acquireIncrement -> 5, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, debugUnreturnedConnectionStackTraces -> false, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 31epo67w1ddywll4aht98|bb0d0d, idleConnectionTestPeriod -> 120, initialPoolSize -> 3, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 120, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 20, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 3, nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSource@e633ba2a [ description -> null, driverClass -> null, factoryClassLocation -> null, identityToken -> 31epo67w1ddywll4aht98|765a16, jdbcUrl -> jdbc:db2://10.244.6.207:50000/pavan, properties -> {user=******, password=******} ], preferredTestQuery -> null, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false; userOverrides: {} ], dataSourceName -> null, factoryClassLocation -> null, identityToken -> 31epo67w1ddywll4aht98|7f4ec, numHelperThreads -> 3 ]
- RDBMS: DB2/LINUX, version: SQL09014
- JDBC driver: IBM DB2 JDBC Universal Driver Architecture, version: 3.50.152
- Using dialect: org.hibernate.dialect.DB2Dialect
- Using default transaction strategy (direct JDBC transactions)
- No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
- Automatic flush during beforeCompletion(): disabled
- Automatic session close at end of transaction: disabled
- Scrollable result sets: enabled
- JDBC3 getGeneratedKeys(): enabled
- Connection release mode: auto
- Default batch fetch size: 1
- Generate SQL with comments: disabled
- Order SQL updates by primary key: disabled
- Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
- Using ASTQueryTranslatorFactory
- Query language substitutions: {}
- JPA-QL strict compliance: disabled
- Second-level cache: enabled
- Query cache: disabled
- Cache provider: org.hibernate.cache.HashtableCacheProvider
- Optimize cache for minimal puts: disabled
- Structured second-level cache entries: disabled
- Statistics: disabled
- Deleted entity synthetic identifier rollback: disabled
- Default entity-mode: pojo
- Named query checking : enabled
- building session factory
- Not binding factory to JNDI, no JNDI name configured
- Running hbm2ddl schema export
- exporting generated schema to database
- schema export complete
- IllegalArgumentException in class: Mother, getter method of property: id
Exception in thread "main" org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of Mother.id
   at org.hibernate.property.BasicPropertyAccessor$BasicGetter.get(BasicPropertyAccessor.java:171)
   at org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:183)
   at org.hibernate.persister.entity.AbstractEntityPersister.getIdentifier(AbstractEntityPersister.java:3589)
   at org.hibernate.persister.entity.AbstractEntityPersister.isTransient(AbstractEntityPersister.java:3305)
   at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:181)
   at org.hibernate.event.def.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:512)
   at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:80)
   at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
   at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:507)
   at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:499)
   at org.hibernate.engine.CascadingAction$1.cascade(CascadingAction.java:218)
   at org.hibernate.engine.Cascade.cascadeToOne(Cascade.java:268)
   at org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:216)
   at org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:169)
   at org.hibernate.engine.Cascade.cascade(Cascade.java:130)
   at org.hibernate.event.def.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:431)
   at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:265)
   at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:181)
   at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:121)
   at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:187)
   at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)
   at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:172)
   at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)
   at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
   at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:535)
   at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523)
   at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519)
   at InsertProduct.main(InsertProduct.java:49)
Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
   at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
   at java.lang.reflect.Method.invoke(Unknown Source)
   at org.hibernate.property.BasicPropertyAccessor$BasicGetter.get(BasicPropertyAccessor.java:145)
   ... 27 more



Name and version of the database you are using: DB2 9.x

Please find corresponding code for the below explanation immediately after the explanation.

I want to test a simple parent child relationship. Hence, I have written 2 simple beans Mother.java and Child.java and corresponding hbm files, Child will have Mother's id as foreign key.

In the main java program(Insertproduct.java, see below for code), I set simple values for Mother and Child. When I try to save the the Child instance, I get the exception mentioned above.

Code for this simple exercise follows.

Mother.hbm.xml

Code:
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
   <class name="Mother" table="Mother">
      <id name="id" type="long" column="Id">
         <generator class="increment" />
      </id>
      
      <property name="age" type="java.lang.Long" column="age" />
      
      

   </class>
</hibernate-mapping>


Mother.java
Code:

public class Mother {
   
   private long id;
   private Long age;
   
   public long getId() {
      return id;
   }
   public void setId(long id) {
      this.id = id;
   }
   public Long getAge() {
      return age;
   }
   public void setAge(Long age) {
      this.age = age;
   }

}




Child.hbm.xml

Code:
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
   <class name="Child" table="Child">
      <id name="id" type="long" column="Id">
         <generator class="increment" />
      </id>
      
      <property name="age" type="java.lang.Long" column="age" />
      
      <many-to-one name="mothersId" class="Mother"
      column="mothersId" cascade="save-update" />

   </class>
</hibernate-mapping>




Child.java

Code:

public class Child {
   

   private long id;
   private Long age;
   private Long mothersId;
   
   public long getId() {
      return id;
   }
   public void setId(long id) {
      this.id = id;
   }
   public Long getAge() {
      return age;
   }
   public void setAge(Long age) {
      this.age = age;
   }
   public void setMothersId(Long mothersId) {
      this.mothersId = mothersId;
   }
   public Long getMothersId() {
      return mothersId;
   }
}




InsertProduct.java (main program)

Code:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class InsertProduct {

    public static void main(String[] args)
                        throws Exception {

       Mother m=new Mother();
       m.setAge(25L);
       m.setId(1L);       
             

        // 2. Fire up Hibernate
        SessionFactory sf = new Configuration().configure().buildSessionFactory();

        // 3. Open Session
        Session sess = sf.openSession();

        // 4. Save Product and close Session
        Transaction t = sess.beginTransaction();
        sess.save(m);
        t.commit();
        sess.close();
       
       
        Child c=new Child();
       c.setAge(10L);
       c.setId(1L);
       Long l=new Long(1);
       c.setMothersId(l);
       
       
        // 3. Open Session
        sess = sf.openSession();

        // 4. Save Product and close Session
        t = sess.beginTransaction();
        sess.save(c);
        t.commit();
        sess.close();
    }
}



Your help will be greatly appreciated as it has stopped our project from enforcing foreign key constraints this way. And no, I dont want to enforce many-to-one using Set.

Thanks a lot in anticipation.

_________________
--
Pavan.


Top
 Profile  
 
 Post subject:
PostPosted: Tue Sep 30, 2008 9:10 am 
Regular
Regular

Joined: Mon Apr 19, 2004 6:54 pm
Posts: 79
Hibernate expects a Mother in the Child class (not an id)
Code:
class Child {
....
   public void setMother(Mother mother) {
      this.mother = mothers;
   }
   public Mother getMother() {
      return mother;
   }
...
}


Christophe


Top
 Profile  
 
 Post subject: Not possible otherwise?
PostPosted: Tue Sep 30, 2008 10:05 am 
Newbie

Joined: Tue Sep 30, 2008 6:25 am
Posts: 2
Location: Goa
Is it not possible to have a field as a foreign key in the bean?.
Here, I need 'mothersId' in 'Child'.

_________________
--
Pavan.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 3 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.