Unable to read one-to-many relations using Hibernate

Hi,
I am trying with a very simple one-to-many relationship. When I am storing the objects, there are no problems. But when I am trying to read out the collection, it says invalid descriptor index. Please help.
Regards,
Hibernate version:
hibernate-3.1rc2
Mapping documents:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
     <class name="Parent">
          <id name="id">
               <generator class="identity"/>
          </id>
          <set name="children">
               <key column="parent_id"/>
               <one-to-many class="Child"/>
          </set>
     </class>
     <class name="Child">
          <id name="id">
               <generator class="identity"/>
          </id>
          <property name="name"/>
     </class>
</hibernate-mapping>
Code between sessionFactory.openSession() and session.close():
The Parent class:
public class Parent
     private Long id ;     
     private Set children;
     Parent(){}
     public Long getId()
          return id;
     public void setId(Long id)
          this.id=id;
     public Set getChildren()
          return children;
     public void setChildren(Set children)
          this.children=children;
The Child class:
public class Child
     private Long id;
     private String name;
     Child(){}
     public Long getId()
          return id;
     private void setId(Long id)
          this.id=id;
     public String getName()
          return name;
     public void setName(String name)
          this.name=name;
The Main class:
public class PCManager
     public static void main(String[] args)
          PCManager mgr = new PCManager();
          List lt = null;
          if (args[0].equals("store"))
               mgr.createAndStoreParent(new HashSet(3));
          else if (args[0].equals("list"))
               mgr.listEvents();
          HibernateUtil.getSessionFactory().close();
     private void createAndStoreParent(HashSet s)
          HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
          Parent p1 = new Parent();
          int size = 3;
          for (int i=size; i>0; i--)
               Child c = new Child();
               c.setName("Child"+i);
               s.add(c);
          p1.setChildren (s);
          Iterator elems = s.iterator();
          do {     
               Child ch = (Child) elems.next();
               HibernateUtil.getSessionFactory().getCurrentSession().save(ch);
          }while(elems.hasNext());
          HibernateUtil.getSessionFactory().getCurrentSession().save(p1);
          HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
     private void listEvents()
          HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
          Parent result = (Parent) HibernateUtil.getSessionFactory().getCurrentSession().load(Parent.class, new Long(1));
          System.out.println("Id is :"+ result.getId());
          Set children = result.getChildren();
          Iterator elems = children.iterator();
          do {     
               Child ch = (Child) elems.next();
               System.out.println("Child Name"+ ch.getName());
          }while(elems.hasNext());
          HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();          
Full stack trace of any exception that occurs:
When I run with "hbm2ddl.auto" property as validate and trying to list the contents, I get the following out put.
C:\Documents and Settings\mirza\Desktop\hibernate-3.1rc2\MyHibernate>ant run -Da
ction=list
Buildfile: build.xml
clean:
[delete] Deleting directory C:\Documents and Settings\mirza\Desktop\hibernate
-3.1rc2\MyHibernate\bin
[mkdir] Created dir: C:\Documents and Settings\mirza\Desktop\hibernate-3.1rc
2\MyHibernate\bin
copy-resources:
[copy] Copying 4 files to C:\Documents and Settings\mirza\Desktop\hibernate
-3.1rc2\MyHibernate\bin
compile:
[javac] Compiling 5 source files to C:\Documents and Settings\mirza\Desktop\
hibernate-3.1rc2\MyHibernate\bin
run:
[java] 09:09:23,433 INFO Environment:474 - Hibernate 3.1 rc2
[java] 09:09:23,449 INFO Environment:489 - loaded properties from resource
hibernate.properties: {hibernate.cglib.use_reflection_optimizer=true, hibernate
.cache.provider_class=org.hibernate.cache.HashtableCacheProvider, hibernate.dial
ect=org.hibernate.dialect.SQLServerDialect, hibernate.max_fetch_depth=1, hiberna
te.jdbc.use_streams_for_binary=true, hibernate.format_sql=true, hibernate.query.
substitutions=yes 'Y', no 'N', hibernate.proxool.pool_alias=pool1, hibernate.cac
he.region_prefix=hibernate.test, hibernate.jdbc.batch_versioned_data=true, hiber
nate.connection.pool_size=1}
[java] 09:09:23,465 INFO Environment:519 - using java.io streams to persis
t binary types
[java] 09:09:23,465 INFO Environment:520 - using CGLIB reflection optimize
r
[java] 09:09:23,481 INFO Environment:550 - using JDK 1.4 java.sql.Timestam
p handling
[java] 09:09:23,559 INFO Configuration:1257 - configuring from resource: /
hibernate.cfg.xml
[java] 09:09:23,559 INFO Configuration:1234 - Configuration resource: /hib
ernate.cfg.xml
[java] 09:09:23,872 INFO Configuration:460 - Reading mappings from resourc
e: PCMapping.hbm.xml
[java] 09:09:24,013 INFO HbmBinder:266 - Mapping class: Parent -> Parent
[java] 09:09:24,045 INFO HbmBinder:266 - Mapping class: Child -> Child
[java] 09:09:24,045 INFO Configuration:1368 - Configured SessionFactory: n
ull
[java] 09:09:24,061 INFO Configuration:1014 - processing extends queue
[java] 09:09:24,061 INFO Configuration:1018 - processing collection mappin
gs
[java] 09:09:24,061 INFO HbmBinder:2233 - Mapping collection: Parent.child
ren -> Child
[java] 09:09:24,076 INFO Configuration:1027 - processing association prope
rty references
[java] 09:09:24,076 INFO Configuration:1049 - processing foreign key const
raints
[java] 09:09:24,155 INFO DriverManagerConnectionProvider:41 - Using Hibern
ate built-in connection pool (not for production use!)
[java] 09:09:24,170 INFO DriverManagerConnectionProvider:42 - Hibernate co
nnection pool size: 1
[java] 09:09:24,170 INFO DriverManagerConnectionProvider:45 - autocommit m
ode: false
[java] 09:09:24,170 INFO DriverManagerConnectionProvider:80 - using driver
: sun.jdbc.odbc.JdbcOdbcDriver at URL: jdbc:odbc:MySQL
[java] 09:09:24,170 INFO DriverManagerConnectionProvider:86 - connection p
roperties: {}
[java] 09:09:24,264 INFO SettingsFactory:77 - RDBMS: Microsoft SQL Server,
version: 08.00.0194
[java] 09:09:24,264 INFO SettingsFactory:78 - JDBC driver: JDBC-ODBC Bridg
e (SQLSRV32.DLL), version: 2.0001 (03.85.1117)
[java] 09:09:24,296 INFO Dialect:100 - Using dialect: org.hibernate.dialec
t.SQLServerDialect
[java] 09:09:24,311 INFO TransactionFactoryFactory:31 - Using default tran
saction strategy (direct JDBC transactions)
[java] 09:09:24,327 INFO TransactionManagerLookupFactory:33 - No Transacti
onManagerLookup configured (in JTA environment, use of read-write or transaction
al second-level cache is not recommended)
[java] 09:09:24,327 INFO SettingsFactory:125 - Automatic flush during befo
reCompletion(): disabled
[java] 09:09:24,327 INFO SettingsFactory:129 - Automatic session close at
end of transaction: disabled
[java] 09:09:24,343 INFO SettingsFactory:144 - Scrollable result sets: ena
bled
[java] 09:09:24,343 INFO SettingsFactory:152 - JDBC3 getGeneratedKeys(): d
isabled
[java] 09:09:24,343 INFO SettingsFactory:160 - Connection release mode: au
to
[java] 09:09:24,358 INFO SettingsFactory:184 - Maximum outer join fetch de
pth: 1
[java] 09:09:24,358 INFO SettingsFactory:187 - Default batch fetch size: 1
[java] 09:09:24,358 INFO SettingsFactory:191 - Generate SQL with comments:
disabled
[java] 09:09:24,358 INFO SettingsFactory:195 - Order SQL updates by primar
y key: disabled
[java] 09:09:24,358 INFO SettingsFactory:338 - Query translator: org.hiber
nate.hql.ast.ASTQueryTranslatorFactory
[java] 09:09:24,374 INFO ASTQueryTranslatorFactory:21 - Using ASTQueryTran
slatorFactory
[java] 09:09:24,374 INFO SettingsFactory:203 - Query language substitution
s: {no='N', yes='Y'}
[java] 09:09:24,374 INFO SettingsFactory:209 - Second-level cache: enabled
[java] 09:09:24,374 INFO SettingsFactory:213 - Query cache: disabled
[java] 09:09:24,374 INFO SettingsFactory:325 - Cache provider: org.hiberna
te.cache.HashtableCacheProvider
[java] 09:09:24,374 INFO SettingsFactory:228 - Optimize cache for minimal
puts: disabled
[java] 09:09:24,374 INFO SettingsFactory:233 - Cache region prefix: hibern
ate.test
[java] 09:09:24,405 INFO SettingsFactory:237 - Structured second-level cac
he entries: disabled
[java] 09:09:24,437 INFO SettingsFactory:257 - Echoing all SQL to stdout
[java] 09:09:24,452 INFO SettingsFactory:264 - Statistics: disabled
[java] 09:09:24,452 INFO SettingsFactory:268 - Deleted entity synthetic id
entifier rollback: disabled
[java] 09:09:24,452 INFO SettingsFactory:283 - Default entity-mode: POJO
[java] 09:09:24,593 INFO SessionFactoryImpl:155 - building session factory
[java] 09:09:24,938 INFO SessionFactoryObjectFactory:82 - Not binding fact
ory to JNDI, no JNDI name configured
[java] 09:09:24,954 INFO SchemaValidator:99 - Running schema validator
[java] 09:09:24,954 INFO SchemaValidator:107 - fetching database metadata
[java] 09:09:24,954 INFO Configuration:1014 - processing extends queue
[java] 09:09:24,954 INFO Configuration:1018 - processing collection mappin
gs
[java] 09:09:24,954 INFO Configuration:1027 - processing association prope
rty references
[java] 09:09:24,954 INFO Configuration:1049 - processing foreign key const
raints
[java] 09:09:24,985 WARN JDBCExceptionReporter:71 - SQL Error: 0, SQLState
: S1002
[java] 09:09:24,985 ERROR JDBCExceptionReporter:72 - [Microsoft][ODBC SQL S
erver Driver]Invalid Descriptor Index
[java] 09:09:25,001 ERROR SchemaValidator:129 - Error closing connection
[java] java.sql.SQLException: [Microsoft][ODBC SQL Server Driver]Invalid transaction state
[java] Initial SessionFactory creation failed.org.hibernate.exception.Gener
icJDBCException: could not get table metadata: Child
[java] java.lang.ExceptionInInitializerError
[java] at HibernateUtil.<clinit>(Unknown Source)
[java] at PCManager.listEvents(Unknown Source)
[java] at PCManager.main(Unknown Source)
[java] Caused by: org.hibernate.exception.GenericJDBCException: could not g
et table metadata: Child
[java] at org.hibernate.exception.SQLStateConverter.handledNonSpecificE
xception(SQLStateConverter.java:91)
[java] at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6879)
[java] at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7036)
[java] at sun.jdbc.odbc.JdbcOdbc.SQLDisconnect(JdbcOdbc.java:2988)
[java] at sun.jdbc.odbc.JdbcOdbcDriver.disconnect(JdbcOdbcDriver.java:9
80)
[java] at sun.jdbc.odbc.JdbcOdbcConnection.close(JdbcOdbcConnection.jav
a:739)
[java] at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaVal
idator.java:125)
[java] at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryIm
pl.java:299)
[java] at org.hibernate.cfg.Configuration.buildSessionFactory(Configura
tion.java:1145)
[java] at HibernateUtil.<clinit>(Unknown Source)
[java] at org.hibernate.exception.SQLStateConverter.convert(SQLStateCon
verter.java:79)
[java] at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExcep
tionHelper.java:43)
[java] at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExcep
tionHelper.java:29)
[java] at org.hibernate.tool.hbm2ddl.DatabaseMetadata.getTableMetadata(
DatabaseMetadata.java:100)
[java] at org.hibernate.cfg.Configuration.validateSchema(Configuration.
java:946)
[java] at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaVal
idator.java:116)
[java] at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryIm
pl.java:299)
[java] at org.hibernate.cfg.Configuration.buildSessionFactory(Configura
tion.java:1145)
[java] ... 3 more
[java] Caused by: java.sql.SQLException: [Microsoft][ODBC SQL Server Driver
]Invalid Descriptor Index
[java] at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6879)
[java] at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7036)
[java] at sun.jdbc.odbc.JdbcOdbc.SQLGetDataString(JdbcOdbc.java:3862)
[java] at sun.jdbc.odbc.JdbcOdbcResultSet.getDataString(JdbcOdbcResultS
et.java:5561)
[java] at sun.jdbc.odbc.JdbcOdbcResultSet.getString(JdbcOdbcResultSet.j
ava:338)
[java] at sun.jdbc.odbc.JdbcOdbcResultSet.getString(JdbcOdbcResultSet.j
ava:395)
[java] at PCManager.listEvents(Unknown Source)
[java] at PCManager.main(Unknown Source)
[java] at org.hibernate.tool.hbm2ddl.TableMetadata.<init>(TableMetadata
.java:30)
[java] at org.hibernate.tool.hbm2ddl.DatabaseMetadata.getTableMetadata(
DatabaseMetadata.java:85)
[java] ... 7 more
[java] Exception in thread "main"
[java] Java Result: 1
BUILD SUCCESSFUL
Total time: 4 seconds
Name and version of the database you are using:
Microsoft SQLServer2000
The generated SQL (show_sql=true):
When the program is run with "hbm2ddl.auto" property as create, I get the following output.
C:\Documents and Settings\mirza\Desktop\hibernate-3.1rc2\MyHibernate>ant run -Daction=store
Buildfile: build.xml
clean:
[delete] Deleting directory C:\Documents and Settings\mirza\Desktop\hibernate
-3.1rc2\MyHibernate\bin
[mkdir] Created dir: C:\Documents and Settings\mirza\Desktop\hibernate-3.1rc
2\MyHibernate\bin
copy-resources:
[copy] Copying 4 files to C:\Documents and Settings\mirza\Desktop\hibernate
-3.1rc2\MyHibernate\bin
compile:
[javac] Compiling 5 source files to C:\Documents and Settings\mirza\Desktop\
hibernate-3.1rc2\MyHibernate\bin
run:
[java] 09:12:54,820 INFO Environment:474 - Hibernate 3.1 rc2
[java] 09:12:54,836 INFO Environment:489 - loaded properties from resource
hibernate.properties: {hibernate.cglib.use_reflection_optimizer=true, hibernate
.cache.provider_class=org.hibernate.cache.HashtableCacheProvider, hibernate.dial
ect=org.hibernate.dialect.SQLServerDialect, hibernate.max_fetch_depth=1, hiberna
te.jdbc.use_streams_for_binary=true, hibernate.format_sql=true, hibernate.query.
substitutions=yes 'Y', no 'N', hibernate.proxool.pool_alias=pool1, hibernate.cac
he.region_prefix=hibernate.test, hibernate.jdbc.batch_versioned_data=true, hiber
nate.connection.pool_size=1}
[java] 09:12:54,852 INFO Environment:519 - using java.io streams to persis
t binary types
[java] 09:12:54,852 INFO Environment:520 - using CGLIB reflection optimize
r
[java] 09:12:54,867 INFO Environment:550 - using JDK 1.4 java.sql.Timestam
p handling
[java] 09:12:54,946 INFO Configuration:1257 - configuring from resource: /
hibernate.cfg.xml
[java] 09:12:54,946 INFO Configuration:1234 - Configuration resource: /hib
ernate.cfg.xml
[java] 09:12:55,259 INFO Configuration:460 - Reading mappings from resourc
e: PCMapping.hbm.xml
[java] 09:12:55,400 INFO HbmBinder:266 - Mapping class: Parent -> Parent
[java] 09:12:55,447 INFO HbmBinder:266 - Mapping class: Child -> Child
[java] 09:12:55,447 INFO Configuration:1368 - Configured SessionFactory: n
ull
[java] 09:12:55,447 INFO Configuration:1014 - processing extends queue
[java] 09:12:55,447 INFO Configuration:1018 - processing collection mappin
gs
[java] 09:12:55,447 INFO HbmBinder:2233 - Mapping collection: Parent.child
ren -> Child
[java] 09:12:55,463 INFO Configuration:1027 - processing association prope
rty references
[java] 09:12:55,479 INFO Configuration:1049 - processing foreign key const
raints
[java] 09:12:55,557 INFO DriverManagerConnectionProvider:41 - Using Hibern
ate built-in connection pool (not for production use!)
[java] 09:12:55,557 INFO DriverManagerConnectionProvider:42 - Hibernate co
nnection pool size: 1
[java] 09:12:55,557 INFO DriverManagerConnectionProvider:45 - autocommit m
ode: false
[java] 09:12:55,573 INFO DriverManagerConnectionProvider:80 - using driver
: sun.jdbc.odbc.JdbcOdbcDriver at URL: jdbc:odbc:MySQL
[java] 09:12:55,573 INFO DriverManagerConnectionProvider:86 - connection p
roperties: {}
[java] 09:12:55,651 INFO SettingsFactory:77 - RDBMS: Microsoft SQL Server,
version: 08.00.0194
[java] 09:12:55,667 INFO SettingsFactory:78 - JDBC driver: JDBC-ODBC Bridg
e (SQLSRV32.DLL), version: 2.0001 (03.85.1117)
[java] 09:12:55,682 INFO Dialect:100 - Using dialect: org.hibernate.dialec
t.SQLServerDialect
[java] 09:12:55,698 INFO TransactionFactoryFactory:31 - Using default tran
saction strategy (direct JDBC transactions)
[java] 09:12:55,714 INFO TransactionManagerLookupFactory:33 - No Transacti
onManagerLookup configured (in JTA environment, use of read-write or transaction
al second-level cache is not recommended)
[java] 09:12:55,714 INFO SettingsFactory:125 - Automatic flush during befo
reCompletion(): disabled
[java] 09:12:55,714 INFO SettingsFactory:129 - Automatic session close at
end of transaction: disabled
[java] 09:12:55,729 INFO SettingsFactory:144 - Scrollable result sets: ena
bled
[java] 09:12:55,729 INFO SettingsFactory:152 - JDBC3 getGeneratedKeys(): d
isabled
[java] 09:12:55,745 INFO SettingsFactory:160 - Connection release mode: au
to
[java] 09:12:55,745 INFO SettingsFactory:184 - Maximum outer join fetch de
pth: 1
[java] 09:12:55,745 INFO SettingsFactory:187 - Default batch fetch size: 1
[java] 09:12:55,745 INFO SettingsFactory:191 - Generate SQL with comments:
disabled
[java] 09:12:55,745 INFO SettingsFactory:195 - Order SQL updates by primar
y key: disabled
[java] 09:12:55,745 INFO SettingsFactory:338 - Query translator: org.hiber
nate.hql.ast.ASTQueryTranslatorFactory
[java] 09:12:55,777 INFO ASTQueryTranslatorFactory:21 - Using ASTQueryTran
slatorFactory
[java] 09:12:55,792 INFO SettingsFactory:203 - Query language substitution
s: {no='N', yes='Y'}
[java] 09:12:55,792 INFO SettingsFactory:209 - Second-level cache: enabled
[java] 09:12:55,792 INFO SettingsFactory:213 - Query cache: disabled
[java] 09:12:55,792 INFO SettingsFactory:325 - Cache provider: org.hiberna
te.cache.HashtableCacheProvider
[java] 09:12:55,808 INFO SettingsFactory:228 - Optimize cache for minimal
puts: disabled
[java] 09:12:55,808 INFO SettingsFactory:233 - Cache region prefix: hibern
ate.test
[java] 09:12:55,808 INFO SettingsFactory:237 - Structured second-level cac
he entries: disabled
[java] 09:12:55,839 INFO SettingsFactory:257 - Echoing all SQL to stdout
[java] 09:12:55,839 INFO SettingsFactory:264 - Statistics: disabled
[java] 09:12:55,839 INFO SettingsFactory:268 - Deleted entity synthetic id
entifier rollback: disabled
[java] 09:12:55,839 INFO SettingsFactory:283 - Default entity-mode: POJO
[java] 09:12:55,980 INFO SessionFactoryImpl:155 - building session factory
[java] 09:12:56,325 INFO SessionFactoryObjectFactory:82 - Not binding fact
ory to JNDI, no JNDI name configured
[java] 09:12:56,341 INFO Configuration:1014 - processing extends queue
[java] 09:12:56,341 INFO Configuration:1018 - processing collection mappin
gs
[java] 09:12:56,341 INFO Configuration:1027 - processing association prope
rty references
[java] 09:12:56,341 INFO Configuration:1049 - processing foreign key const
raints
[java] 09:12:56,356 INFO Configuration:1014 - processing extends queue
[java] 09:12:56,356 INFO Configuration:1018 - processing collection mappin
gs
[java] 09:12:56,356 INFO Configuration:1027 - processing association prope
rty references
[java] 09:12:56,372 INFO Configuration:1049 - processing foreign key const
raints
[java] 09:12:56,372 INFO SchemaExport:153 - Running hbm2ddl schema export
[java] 09:12:56,388 DEBUG SchemaExport:171 - import file not found: /import
.sql
[java] 09:12:56,388 INFO SchemaExport:180 - exporting generated schema to
database
[java] 09:12:56,403 DEBUG SchemaExport:283 -
[java] alter table Child
[java] drop constraint FK3E104FC976A59A
[java] 09:12:56,466 DEBUG SchemaExport:283 -
[java] drop table Child
[java] 09:12:56,544 DEBUG SchemaExport:283 -
[java] drop table Parent
[java] 09:12:56,654 DEBUG SchemaExport:283 -
[java] create table Child (
[java] id numeric(19,0) identity not null,
[java] name varchar(255) null,
[java] parent_id numeric(19,0) null,
[java] primary key (id)
[java] )
[java] 09:12:56,779 DEBUG SchemaExport:283 -
[java] create table Parent (
[java] id numeric(19,0) identity not null,
[java] primary key (id)
[java] )
[java] 09:12:56,873 DEBUG SchemaExport:283 -
[java] alter table Child
[java] add constraint FK3E104FC976A59A
[java] foreign key (parent_id)
[java] references Parent
[java] 09:12:56,952 INFO SchemaExport:200 - schema export complete
[java] 09:12:56,952 WARN JDBCExceptionReporter:48 - SQL Warning: 5701, SQL
State: 01000
[java] 09:12:56,952 WARN JDBCExceptionReporter:49 - [Microsoft][ODBC SQL S
erver Driver][SQL Server]Changed database context to 'master'.
[java] 09:12:56,952 WARN JDBCExceptionReporter:48 - SQL Warning: 5703, SQL
State: 01000
[java] 09:12:56,952 WARN JDBCExceptionReporter:49 - [Microsoft][ODBC SQL S
erver Driver][SQL Server]Changed language setting to us_english.
[java] 09:12:56,983 INFO SessionFactoryImpl:432 - Checking 0 named queries
[java] Hibernate:
[java] insert
[java] into
[java] Child
[java] (name)
[java] values
[java] (?) select
[java] scope_identity()
[java] Hibernate:
[java] insert
[java] into
[java] Child
[java] (name)
[java] values
[java] (?) select
[java] scope_identity()
[java] Hibernate:
[java] insert
[java] into
[java] Child
[java] (name)
[java] values
[java] (?) select
[java] scope_identity()
[java] Hibernate:
[java] insert
[java] into
[java] Parent
[java] default
[java] values
[java] select
[java] scope_identity()
[java] Hibernate:
[java] update
[java] Child
[java] set
[java] parent_id=?
[java] where
[java] id=?
[java] Hibernate:
[java] update
[java] Child
[java] set
[java] parent_id=?
[java] where
[java] id=?
[java] Hibernate:
[java] update
[java] Child
[java] set
[java] parent_id=?
[java] where
[java] id=?
[java] 09:12:57,390 INFO SessionFactoryImpl:831 - closing
[java] 09:12:57,390 INFO DriverManagerConnectionProvider:147 - cleaning up
connection pool: jdbc:odbc:MySQL
BUILD SUCCESSFUL
Total time: 5 seconds
Debug level Hibernate log excerpt:
Included in the above description.

That's not the right mapping for the 1:m relationship in Hibernate.
First of all, I believe the recommendation is to have a separate .hbm.xml file for each class, so you should have one for Parent and Child.
Second, you'll find the proper syntax for a one-to-many relationship here:
http://www.hibernate.org/hib_docs/v3/reference/en/html/tutorial.html#tutorial-associations
See if those help.
The tutorial docs for Hibernate are quite good. I'd recommend going through them carefully.
%

Similar Messages

  • How to create one to many relation database based on existing Tables?

    Let say I have got 10 tables. Out of these 10 tables one table is used to navigate to other tables and at the some time providing some useful information. Therefore other 9 Tables have the identical structure.
    The question is, how can I convert these 10 tables into 2 tables, ie each row of first table correspond to the different data of the other table (one to many relation)?

    Hello,
    >>The question is, how can I convert these 10 tables into 2 tables, ie each row of first table correspond to the different data of the other table (one to many relation)?
    I do not quite understand what you ask and I doubt if Entity Framework supports this scenario, since you mentions these tables already exist, after importing them to the designed windows, we cannot modify them or it would throw an error shows the database
    and model is mismatched.
    Regards.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • JPA: Issue with loading One To Many relation

    Hi All,
    I have a One to Many relation mapped as below
    @Entity
    @Table(name="ACCOUNT_TABLE")
    public class UserAccount {
         // Attributes
         @Id
         @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="USER_SEQ")
         @SequenceGenerator(name="USER_SEQ", sequenceName="USERS_SEQ",allocationSize=1)
         @Column(name="CLIENT_ID")
         private Long clientId;
         @Column(name="USER_ID")
         private String userId;
         @OneToMany(fetch=FetchType.LAZY, mappedBy="userAccount")
         @JoinColumn(name="USER_ID", referencedColumnName="USER_ID", insertable=false, updatable=false)
         private List<UserRole> assignedRoles;
    @Entity
    @Table(name = "ROLE_TABLE")
    public class UserRole extends BaseEntity implements Serializable {
         private static final long serialVersionUID = -1651953276532642312L;
         @Id
         @Column(name = "USER_ID", length = 30, nullable=false, insertable=false, updatable=false)
         private String userId;
         @Column(name = "BUSINESS_CODE", length = 10, nullable=false, insertable=false, updatable=false)
         private String businessCode;
         @Column(name = "ROLE_NAME", length = 30, nullable=false, insertable=false, updatable=false)
         private String roleName;
         @ManyToOne()
         @JoinColumn(name="USER_ID", referencedColumnName="USER_ID", insertable=false, updatable=false)
         private UserAccount userAccount;
    As you may have noticed, the tables are not joined on the Primary key of parent. This is legacy schema and I have to work with it.
    Account and Role are joined by the USER_ID column. This I specified by providing JoinColumn.
    Then I have a DAO to retrieve the relation based on user id.
    public class UserAccountDAOJPAImpl UserAccountDAO{
         private static final String USER_ACCOUNT_BY_USERID = "select distinct ua " +
         "from UserAccount ua " +
         "left outer join fetch ua.assignedRoles ar " +
         "where ua.userId = ?1 ";
         public UserAccount findByUserName(String userName){          
              UserAccount userAccount=null;
              List<UserAccount> userAccounts =null;
         Query query = this.entityManager.createQuery(USER_ACCOUNT_BY_USERID);
         query.setParameter(1, userName.toUpperCase());
         userAccounts = query.getResultList();
         if(!userAccounts.isEmpty()) {
              userAccount=userAccounts.get(0);
              return userAccount;
    When I test this code ( for the user Id I used in test there are 11 roles )
    The SQL generated is correct, when I run the SQL in PL/SQL Developer, it returns the results as expected.
    But the DAO method above returns one UserAccount object with List of 11 UserRole objects as expected. But all of these 11 UserRole objects are same, where as the query returns 11 different roles.
    I couldn't figure out what I was doing wrong.
    Any help is appreciated.
    thanks,
    Raghavan

    @OneToMany(fetch=FetchType.LAZY, mappedBy="userAccount")
    @JoinColumn(name="USER_ID", referencedColumnName="USER_ID", insertable=false, updatable=false)
    private List<UserRole> assignedRoles;
    }What do you get when you remove this @JoinColumn annotation? It shouldn't be necessary. (user_id seems a little suspect as the join column name by the way, I would have expected role_id here...)

  • How to get data from three tables (A,B,C) having one to many relation between A and B .and having one to many reation between b and c

    i have  three tables A,B,C.  there is one to many relation between A and B. and one to many relation existed between table b and c . how will get data from these three tables

    check if this helps:
    select * --you can always frame your column set
    from tableA a
    left join tableB b on a.aid=b.aid
    left join tableC c on c.bid=b.bid
    This is just a general query. However, we can help you a lot more, if you can post the DDL + sample data and required output.
    Thanks,
    Jay
    <If the post was helpful mark as 'Helpful' and if the post answered your query, mark as 'Answered'>

  • Unable to read file. may be in use missing or corrupt

    I'm trying to transfer my music from Zen Micro to pc. Some music transfered but most didn't. When I try to transfer I get that message " Unable to read file, may be in use missing or corrupted. Did the disc cleanup for zen also. Any help would be great.

    Agapyla, two possible reasons you can't see the .idlk files. One, you're looking in the wrong place, or two, your OS doesn't consider .idlk files to be "system files."
    Option 1: In InCopy or InDesign, click inside the story you're locked out of, and open the Links panel. That story will be highlighted. Right-click on the highlighted story and choose Reveal in Finder (or Reveal in Explorer if you're on Windows).  That will bring you to the folder where the InCopy story (ICML) is. It is inside that same folder where you'll find the IDLK file.  A story's IDLK file is always at the same level as its ICML file. It might be at the top or bottom of the list of files in that folder if you're viewing them as a list sorted alphabetically. So scroll through.
    Option 2: See if there's a setting in your OS to view "invisible" files, or Google for a utility.  I think "system" and "invisible" are the same, but maybe not.  Personally I use my FTP program which lets you see your local hard drive on one side of the window and the remote server on the other side. The FTP program defaults to showing *all* files on both sides. So for me it's a quickie way to see the IDLK files. The IDLK files begin with characters that force the OS to not show them, like a period or a tilde.
    Honestly, if you're seeing a slash through a pencil icon, that file is locked, so there's an IDLK file somewhere. That's the only way ID or IC will show that icon. 
    In case of emergency: In InDesign (can't do this in InCopy), select the locked story and Unlink it in the Links panel from the Links panel menu. It breaks the link to the original ICML file an turns it back into a normal InDesign text frame. Then select the frame, and export it to InCopy format again *with a different filename* than before, but saves it to the same place as the other ICML stories for that layout.
    AM

  • Primary one-to-many relation

    What is the best practice to identify the primary entity in a one-to-many relation?
    Lets asume the following:
    I have persons. (Table: PERSON, Primary Key: PERSON_ID)
    I have contact points (Table: CONTACT_POINTS, Foreign Key to PERSON_ID)
    In the E-Business Suite we have a field PRIMARY_FLAG on the CONTACT_POINTS table. This is either Y or N. Now it is upon the application, to verify that only one primary contact point is set. But there is no check in the database. You can have 2 lines, with primary_flag = 'Y'.
    This would make it heavy to do a simple select as:
    SELECT p.first_name, p.last_name, cp.phone_number FROM PERSON p, CONTACT_POINTS cp WHERE cp.PERSON_ID(+) = p.PERSON_ID AND cp.PRIMARY_FLAG(+) = 'Y'
    Because if you have, by mistake, 2 lines with PRIMARY_FLAG = 'Y', you would get 2 result lines in the query above, which is not wanted.
    A second way would be to have the PRIMARY_FLAG field is filled either with Y or NULL. In addition I can set a unique constrain over PERSON_ID and PRIMARY_FLAG and the database will block every try to add a second Y for one person. In that way I can be sure that I either have a primary contact point or I do not have one. So the query will result the same number of lines as there are in the PERSON table. BUT: whenever I go that way, I have to verify my application logic, that every change on the primary flag must set the old primary entry off and then insert or update the new primary entry.
    Which one is the best way, in practice? Are there other solutions? What are advantages ?
    Best Regards
    Alexander

    You can create unique function based index on your CONTACT_POINTS table as follows:
    (person_id, case when primary_flag = 'Y' then primary_flag else null end)
    So as soon as you'll insert another row with Y, you'll get error, but with other values like N, all will be OK.
    And yes - I think it is worth to check data integrity in DB :)
    Gints Plivna
    http://www.gplivna.eu

  • TopLink11 Tutorial problems with one-to-many relation

    Hi,
    I installed TopLink 11 and the related tutorial to work in a simple Eclipse project.
    Everthing works fine except for the storing of the one-to-many relation in the database.
    The tutorial works with employee, address and phone tables/classes. Plain Objects can be stored and one-to-one relations too. However when trying to store a one-to-many relation not the key of the related object (which is at that tome well known) but the object is tried to be entered
    in the Logfile I find:
    [TopLink Fine]: 2008.01.10 10:27:28.748--DatabaseSessionImpl(12916846)--Connection(9550256)--Thread(Thread[main,5,main])--INSERT INTO EMPLOYEE (EMP_ID, L_NAME, F_NAME, ADDR_ID, VERSION) VALUES (?, ?, ?, ?, ?)
         bind => [1501, Pascal, Blaise, 2252, 1]
    [TopLink Finer]: 2008.01.10 10:27:28.748--DatabaseSessionImpl(12916846)--Connection(9550256)--Thread(Thread[main,5,main])--commit transaction
    [TopLink Finer]: 2008.01.10 10:27:28.748--UnitOfWork(14858725)--Thread(Thread[main,5,main])--end unit of work commit
    [TopLink Finer]: 2008.01.10 10:27:28.748--UnitOfWork(14858725)--Thread(Thread[main,5,main])--release unit of work
    [TopLink Finer]: 2008.01.10 10:27:28.748--UnitOfWork(14858725)--Thread(Thread[main,5,main])--release unit of work
    [TopLink Finest]: 2008.01.10 10:27:28.748--UnitOfWork(18511661)--Thread(Thread[main,5,main])--Register the object Employee: Blaise Pascal
    [TopLink Finest]: 2008.01.10 10:27:28.748--UnitOfWork(18511661)--Thread(Thread[main,5,main])--Execute query DoesExistQuery()
    [TopLink Finer]: 2008.01.10 10:28:58.370--UnitOfWork(18511661)--Thread(Thread[main,5,main])--begin unit of work commit
    [TopLink Finer]: 2008.01.10 10:28:58.370--DatabaseSessionImpl(12916846)--Connection(9550256)--Thread(Thread[main,5,main])--begin transaction
    [TopLink Finest]: 2008.01.10 10:28:58.370--UnitOfWork(18511661)--Thread(Thread[main,5,main])--Execute query UpdateObjectQuery(Employee: Blaise Pascal)
    [TopLink Finest]: 2008.01.10 10:28:58.386--UnitOfWork(18511661)--Thread(Thread[main,5,main])--Execute query InsertObjectQuery(PhoneNumber[desk]: (603) 123-4567)
    [TopLink Fine]: 2008.01.10 10:28:58.386--DatabaseSessionImpl(12916846)--Connection(9550256)--Thread(Thread[main,5,main])--INSERT INTO PHONE (P_NUMBER, EMP_ID, AREA_CODE, TYPE) VALUES (?, ?, ?, ?)
         bind => [1234567, {Employee: Blaise Pascal}, 603, desk]
    [TopLink Warning]: 2008.01.10 10:28:58.511--UnitOfWork(18511661)--Thread(Thread[main,5,main])--Local Exception Stack:
    Exception [TOPLINK-4002] (Oracle TopLink - 11g Technology Preview 3 (11.1.1.0.0) (Build 071214)): oracle.toplink.exceptions.DatabaseException
    Internal Exception: java.sql.SQLException: Ungültiger Spaltentyp Error Code: 17004
    the highlighted section should be 1501 (the key of the employee record)
    Any ideas how to fix this?
    Thanks Erika

    Erika,
    You need to specify the other side of the relationship (on the PhoneNumber side), which is done by putting a @ManyToOne annotation on the "employee" attribute in PhoneNumber. That will cause TopLink to know that it is a relationship and not a basic mapping.
    -Mike

  • One to many relation doesn't work

    I tried without success to get a simple one to many relationship to work.
    The select works fine but
    I still have problems with insert.
    I have two tables on a existing schema:
    1     ANAG (ID_ANAG primary key,...)
    2     INDI (ID_INDI primary key, ID_ENTITA,...), where INDI.ID_ENTITA points
    to ANAG.ID_ANAG
    the two classes are:
    1     public class Anagrafica
         private int idAnag; //ID_ANAG
         private String ragSoc;
         private String ragSocFonet;
         private String codFisc;
         private String sesso;
         private Integer codTit;
         private Date dtNasc;
         private HashSet indis;
    2     public class Indirizzo
         private int idIndi; //ID_INDI
         private long idEntita; //ID_ENTITA
         private long tpEntita;
         private String indirizzo;
         private String localita;
         private String prov;
         private String cap;
         private Anagrafica anagrafica;
    the two metadata:
    1      anagrafica.jdo:
    <?xml version="1.0"?>
    <!-- This JDO Metadata file was auto-generated on 08/10/02 17.44.
    See http://www.solarmetric.com for Kodo JDO Documentation and examples. -->
    <jdo>
    <package name="domain">
    <class name="Anagrafica"
    identity-type="application"
    objectid-class="domain.AnagraficaPK">
    <extension key="table" value="ANAG" vendor-name="kodo"/>
    <extension key="class-column" value="none" vendor-name="kodo"/>
    <extension key="lock-column" value="none" vendor-name="kodo"/>
    <field name="idAnag" primary-key="true">
    <extension key="data-column" value="ID_ANAG"
    vendor-name="kodo"/>
    </field>
    <field name="ragSoc">
    <extension key="data-column" value="RAG_SOC"
    vendor-name="kodo"/>
    </field>
    <field name="ragSocFonet">
    <extension key="data-column" value="RAG_SOC_FONET"
    vendor-name="kodo"/>
    </field>
    <field name="codFisc">
    <extension key="data-column" value="COD_FISC"
    vendor-name="kodo"/>
    </field>
    <field name="sesso">
    <extension key="data-column" value="SESSO"
    vendor-name="kodo"/>
    </field>
    <field name="codTit">
    <extension key="data-column" value="COD_TIT"
    vendor-name="kodo"/>
    </field>
    <field name="dtNasc">
    <extension key="data-column" value="DT_NASC"
    vendor-name="kodo"/>
    </field>
    <field name="indis">
    <collection element-type="domain.Indirizzo"/>
    <extension vendor-name="kodo" key="table" value="INDI"/>
    <extension vendor-name="kodo" key="inverse"
    value="anagrafica"/>
    <extension vendor-name="kodo" key="idEntita-ref-column"
    value="ID_ANAG"/>
         </field>
    </class>
    </package>
    </jdo>
    2 Indirizzo.jdo
    <?xml version="1.0"?>
    <!-- This JDO Metadata file was auto-generated on 08/10/02 17.21.
    See http://www.solarmetric.com for Kodo JDO Documentation and examples. -->
    <jdo>
    <package name="domain">
    <class name="Indirizzo"
    identity-type="application" objectid-class="domain.IndiPK">
    <extension key="table" value="INDI" vendor-name="kodo"/>
    <extension key="class-column" value="none" vendor-name="kodo"/>
    <extension key="lock-column" value="none" vendor-name="kodo"/>
    <!--extension vendor-name="kodo" key="idEntita-data-column"
    value="ID_ENTITA"/-->
    <field name="idIndi" primary-key="true">
    <extension key="data-column" value="ID_INDI"
    vendor-name="kodo"/>
    </field>
    <field name="idEntita">
    <extension key="data-column" value="ID_ENTITA"
    vendor-name="kodo"/>
    </field>
    <field name="tpEntita">
    <extension key="data-column" value="TP_ENTITA"
    vendor-name="kodo"/>
    </field>
    <field name="indirizzo">
    <extension key="data-column" value="INDIRIZZO"
    vendor-name="kodo"/>
    </field>
    <field name="localita">
    <extension key="data-column" value="LOCALITA"
    vendor-name="kodo"/>
    </field>
    <field name="prov">
    <extension key="data-column" value="PROV"
    vendor-name="kodo"/>
    </field>
    <field name="cap">
    <extension key="data-column" value="CAP"
    vendor-name="kodo"/>
    </field>
    <field name="anagrafica">
    <extension vendor-name="kodo" key="idAnag-data-column"
    value="ID_ENTITA"/>
    </field>
    </class>
    </package>
    </jdo>
    The problem is:
    I create a new Anagrafica object and then I try to save it in the
    database. These are the SQL
    statements that are generated:
    INSERT INTO ANAG(DT_NASC, COD_FISC, RAG_SOC_FONET, SESSO, ID_ANAG,
    RAG_SOC, COD_TIT)
    VALUES (NULL, NULL, 'NATALE', NULL, 971963921, 'Natale', NULL)
    INSERT INTO INDI(TP_ENTITA, PROV, LOCALITA, ID_ENTITA, ID_INDI, INDIRIZZO,
    CAP)
    VALUES (0, NULL, NULL, 0, 971963921, 'via 25 dicembre', NULL)
    Why is the value of ID_ANAG (971963921) assigned to ID_INDI and not to
    ID_ENTITA?
    Regards
    Mirko

    Abe White wrote:
    <field name="indis">
    <collection element-type="domain.Indirizzo"/>
    <extension vendor-name="kodo" key="table" value="INDI"/>
    <extension vendor-name="kodo" key="inverse"
    value="anagrafica"/>
    <extension vendor-name="kodo" key="idEntita-ref-column"
    value="ID_ANAG"/>
         </field>
    Get rid of all extensions except the inverse:
    <field name="indis">
    <collection element-type="domain.Indirizzo"/>
    <extension vendor-name="kodo" key="inverse" value="anagrafica"/>
    </field>
    As in the examples in our documentation, all 1-many relations should only
    list their inverse 1-1 relation.
    Also, make sure your object model is consistent; i.e. make sure you'resetting
    both sides of the relation:
    indi.setAnagrafica (anag);
    anag.getIndis ().add (indi);
    Let us know if you continue to have problems.Hi Abe,
    I got rid of the unnecessary extensions and I set both sides of the
    relation as you suggest but I still have the same problem:
    INSERT INTO ANAG(ID_ANAG) VALUES (2088176453)
    INSERT INTO INDI(ID_INDI, ID_ENTITA) VALUES (2088176453, NULL)
    while I expect
    INSERT INTO ANAG(ID_ANAG) VALUES (2088176453)
    INSERT INTO INDI(ID_INDI, ID_ENTITA) VALUES (<some ID>, 2088176453)
    any ideas?
    regards

  • One-to-many relation sometimes INSERTs child before parent

    Hi,
    I have a one-to-many relationship, say Company-Employee, that I want to be
    managed by the parent entity (Company), so that when I make persistent the
    Company, its Employees are also made persistent, and when I delete the
    Company, its Employees are deleted. In my Java code, Company has an
    ArrayList of Employees, and Employee has a Company member variable.
    My metadata looks like this:
    <class name="Company" identity-type="application">...
         <field name="employees">
              <collection element-type="Employee"/>
              <extension vendor-name="kodo" key="inverse-owner" value="company"/>
              <!-- delete all Employees when the Company is deleted -->
              <extension vendor-name="kodo" key="element-dependent" value="true"/>
         </field>
    </class>
    <class name="Employee" identity-type="application">...
         <field name="company"/>
    </class>
    I have a test that is creating a Company with an Employee and persisting
    it. It then deletes the Company. The test is passing some of the time and
    failing some of the time. It seems to not be consistent with the ordering
    of the INSERTs - sometimes it inserts Company then Employee, but sometimes
    it first tries to insert into Employee, which fails with a foreign key
    constraint to the parent table.
    How can I force it to insert into the parent table first?
    I notice that the documentation says you need the field of the child
    entity to be the inverse-owner. Is it not possible for the parent entity
    to own the relationship?
    Many thanks,
    Alex

    Alex,
    If you have non-deferred foreign keys between the tables, and you turn
    on Kodo's foreign key reordering algorithm, Kodo will ensure that all
    your foreign key constraints are met, regardless of the ordering of the
    operations in your Java code.
    See http://docs.solarmetric.com/ref_guide_dbsetup_fks.html for details
    about this.
    Regarding inverse-owner specification -- is there any reason why you
    want to specify this on the other side? inverse-owner basically defines
    which side of a shared relationship defines the mappings and should be
    monitored for changes; it does not have any impact on the mappings
    themselves.
    -Patrick
    Alex Robbins wrote:
    Hi,
    I have a one-to-many relationship, say Company-Employee, that I want to be
    managed by the parent entity (Company), so that when I make persistent the
    Company, its Employees are also made persistent, and when I delete the
    Company, its Employees are deleted. In my Java code, Company has an
    ArrayList of Employees, and Employee has a Company member variable.
    My metadata looks like this:
    <class name="Company" identity-type="application">...
         <field name="employees">
              <collection element-type="Employee"/>
              <extension vendor-name="kodo" key="inverse-owner" value="company"/>
              <!-- delete all Employees when the Company is deleted -->
              <extension vendor-name="kodo" key="element-dependent" value="true"/>
         </field>
    </class>
    <class name="Employee" identity-type="application">...
         <field name="company"/>
    </class>
    I have a test that is creating a Company with an Employee and persisting
    it. It then deletes the Company. The test is passing some of the time and
    failing some of the time. It seems to not be consistent with the ordering
    of the INSERTs - sometimes it inserts Company then Employee, but sometimes
    it first tries to insert into Employee, which fails with a foreign key
    constraint to the parent table.
    How can I force it to insert into the parent table first?
    I notice that the documentation says you need the field of the child
    entity to be the inverse-owner. Is it not possible for the parent entity
    to own the relationship?
    Many thanks,
    Alex

  • One to many relationship in hibernate

    I am very much new to hibernate,
    for testing purpose I am using JPA annotations and hibernate.
    While testing one to many relationship , I got a problem
    I have a PurchaseOrder class and OrderLine class having one to many relationship.
    package orderpackage;
    import java.util.ArrayList;
    import java.util.List;
    import javax.persistence.CascadeType;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.OneToMany;
    @Entity
    public class PurchaseOrder {
      @Id
      @GeneratedValue(strategy=GenerationType.AUTO)
      private int id;
      @OneToMany(cascade=CascadeType.ALL,mappedBy="order")
      private List <OrderLine> orderLine = new ArrayList<OrderLine>();
      public PurchaseOrder(String orderName) {
      this.orderName = orderName;
      public List<OrderLine> getOrderLine() {
      return orderLine;
      public void setOrderLine(List<OrderLine> orderLine) {
      this.orderLine = orderLine;
      private String orderName;
      public int getId() {
      return id;
      public void setId(int id) {
      this.id = id;
      public String getOrderName() {
      return orderName;
      public void setOrderName(String orderName) {
      this.orderName = orderName;
    OrderLine.java
    package orderpackage;
    import javax.persistence.CascadeType;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.ManyToOne;
    @Entity
    public class OrderLine {
      @Id
      @GeneratedValue(strategy=GenerationType.AUTO)
      private int id;
      private String itemName;
      private int qty;
      @ManyToOne(cascade=CascadeType.ALL)
      private PurchaseOrder order;
      public OrderLine(String itemName, int qty) {
      this.itemName = itemName;
      this.qty = qty;
      public PurchaseOrder getOrder() {
      return order;
      public void setOrder(PurchaseOrder order) {
      this.order = order;
      public int getId() {
      return id;
      public void setId(int id) {
      this.id = id;
      public String getItemName() {
      return itemName;
      public void setItemName(String itemName) {
      this.itemName = itemName;
      public int getQty() {
      return qty;
      public void setQty(int qty) {
      this.qty = qty;
         OrderTest.java
    package orderpackage;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    public class OrderTest {
      public static void main(String[] args) {
      PurchaseOrder order = new PurchaseOrder("order no 1");
      OrderLine orderLine1 = new OrderLine("item1",25);
      OrderLine orderLine2 = new OrderLine("item2",28);
      OrderLine orderLine3 = new OrderLine("item3",38);
      OrderLine orderLine4 = new OrderLine("item4",48);
      order.getOrderLine().add(orderLine1);
      order.getOrderLine().add(orderLine2);
      order.getOrderLine().add(orderLine3);
      order.getOrderLine().add(orderLine4);
      SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
      Session session = sessionFactory.openSession();
      session.beginTransaction();
      session.persist(order);
      session.getTransaction().commit();
      session.close();
    I can see Order and Order Line are get persisted but Order Line table don't have order_id populated automatically. Please help me out.

    That is because you're not setting it, obviously. Nowhere in your code are you actually populating the order property of the orderlines.

  • One to many relationship using java collections

    I am facing issue on how to store and then retrieve data . In my program which is simple java class i am retrieving data at 3 places from an xml. i need to store this temporarly in particular fashion as data is related and needed to be used later on at end program to generate report.
    first data i am retireving is employee names eg Tom , Reggie, Martha.
    Second data is department (Each employee belongs to 1 or many department ) so in this case
    Tom : Billing
    Reggie : Admin , HR
    Martha : IT
    Third data is Department number (This has 1 : 1 relationship with Department )
    Billing :01
    Admin :02
    HR:03
    IT:04
    So when i am parsing xml first i am getting employee data, then department and lastly department number. I need to store it in collection in such way later on i can retireve and link data and use it.....
    Which java collections i should use....
    Any hints or guidance ....

    Well, the simplest approach is to initially load the employees objects into a List<Employee>. Initially they store the department number only. Then load the departments, probably into a Map<Integer, Department>. Having popluated such a map you then loop through the Employee list, connecting looking up the deparment number in the map and connecting Employee to Department as you wish. (An Employee would probably had a reference to the Department, the Department might contain a List<Employee>).
    The implementations to use depend on how you'll use them. HashMaps are faster than TreeMaps, but a TreeMap orders. LinkedLists are faster to process in sequence than ArrayList, slower to process at random.

  • Mapping a one to many relationship using fluent api

    Hi I can't map my domains to match the database, since database is already created, I can't create or remove any other extra table.
    Database
    CREATE TABLE PLAYER (Id Int, Name varchar(100), PRIMARY KEY (Id))
    CREATE TABLE POSITION (Id Int, Name varchar(100), PRIMARY KEY (Id))
    CREATE TABLE CHAMPIONSHIP (Id Int, Name varchar(100), PRIMARY KEY (Id))
    CREATE TABLE RELATED (PlayerId Int, PositionId Int, ChampionshipId int,
    FOREIGN KEY (PlayerId) references PLAYER(id),
    FOREIGN KEY (PositionId) references POSITION(id),
    FOREIGN KEY (ChampionshipId) references CHAMPIONSHIP(id),
    CONSTRAINT AK_RELATED UNIQUE(PlayerId,PositionId,ChampionshipId))
    Domains:
    public class Player
    public Player()
    this.Relateds = new List<Related>();
    public int Id {get;set;}
    public string Name { get; set; }
    public virtual ICollection<Related> Relateds { get; set; }
    public class Position
    { public int Id {get;set;}
    public string Name { get; set; } public virtual ICollection<Related> Relateds { get; set; }
    public class Championship
    { public int Id {get;set;}
    public string Name { get; set; } public virtual ICollection<Related> Relateds { get; set; }
    public class Related
    public int PlayerId { get; set; }
    public Player Player{ get; set; }
    public int PositionId { get; set; }
    public Position Position { get; set; }
    public int ChamionshipId { get; set; }
    public Championship Championship { get; set; }
    FLUENT API:
    modelBuilder.Entity<Player>().HasKey(m => m.Id);
    modelBuilder.Entity<Player>().Property(m => m.Name).IsRequired();
    modelBuilder.Entity<Position>().HasKey(m => m.Id);
    modelBuilder.Entity<Position>().Property(m => m.Name).IsRequired();
    modelBuilder.Entity<Championship>().HasKey(m => m.Id);
    modelBuilder.Entity<Championship>().Property(m => m.Name).IsRequired();
    Seed.cs
    public DbSet<Player> Players { get; set; }
    public DbSet<Position> Positions { get; set; }
    public DbSet<Championship> Championships { get; set; }
    private void Seed2(ApplicationDbContext context)
    string[] playerNames = new string[] { "Adam", "John", "Lucas" };
    string[] positionNames = new string[] { "Sniper", "Camper", "Assalt" };
    string[] championshipNames = new string[] { "BF4", "CS1.6", "TF2" };
    int relations = 3;
    try
    foreach (var name in playerNames)
    if (!this.Players.Any(m => m.Name == name))
    Player player = new Player { Name = name };
    context.Players.Add(player);
    foreach (var name in positionNames)
    if (!this.Players.Any(m => m.Name == name))
    Position position = new Position { Name = name };
    context.Positions.Add(position);
    foreach (var name in championshipNames)
    if (!this.Championship.Any(m => m.Name == name))
    Championship championship = new Championship { Name = name };
    context.Championships.Add(championship);
    context.SaveChanges();
    for (int i = 1; i <= relations; i++)
    var player = context.Players.ToList()[i];
    var position = context.Positions.ToList()[i];
    var championship = context.Championships.ToList()[i];
    if (!context.Relateds.Any(m =>
    context.Players.Any(t => m.PlayerId == t.Id)
    && context.Positions.Any(t => m.PositionId == t.Id)
    && context.Championships.Any(t => m.ChampionshipId == t.Id)))
    Related related = new Related
    Player = player,
    Position = position,
    Championship = championship
    player.Relateds.Add(related);
    context.Entry(player).State = EntityState.Modified;
    context.SaveChanges();
    catch (Exception ex)
    throw;
    I'm not able to insert into the Related table, I think the fluent api is not maped well, how can I fix it?

    Hello,
    >>I'm not able to insert into the Related table, I think the fluent api is not maped well, how can I fix it?
    As you mentions, your database already exists, so I assume that you are using database first approach, then, as far as I know, the fluent API is made only for Code-First approach and we don't need the fluent API if we create your model via Database-First.
    For database first approach, we just need to import existed tables to the designer surface by “Update Model From Database”. And with your provided model, I noticed that the related table does not contain a primary constraint, in Entity Framework, a table
    without the primary key would be treated as a view that is read only. So please create a primary constraint for the related table as:
    CREATE TABLE RELATED (PlayerId Int, PositionId Int, ChampionshipId int,
    FOREIGN KEY (PlayerId) references PLAYER(id),
    FOREIGN KEY (PositionId) references POSITION(id),
    FOREIGN KEY (ChampionshipId) references CHAMPIONSHIP(id),
    PRIMARY KEY CLUSTERED (PlayerId ASC, PositionId ASC,ChampionshipId asc),
    CONSTRAINT AK_RELATED UNIQUE(PlayerId,PositionId,ChampionshipId))
    With your provided tables, after adding this constraint, the Related table could add a new row as:
    using (DFDBEntities db=new DFDBEntities())
    RELATED related = new RELATED() { PlayerId = 1, ChampionshipId = 1, PositionId = 1 };
    db.RELATEDs.Add(related);
    db.SaveChanges();
    Regards.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How to find if the user has selected one or many files using a file chooser

    I have a file chooser but want it to return either a file or file array depending on whether more than one file is selected but there doesn't seem to be any way to find out if that is the case or not. I want it to look something like:
                if(fileChooser.getSelectedFile().isDirectory()==true)
                    selectedFile=fileChooser.getCurrentDirectory();
                else if(fileChooser.multipleFilesSelected())
                    fileChooser.getSelectedFiles();//we have more than one file selected
                else   
                    fileChooser.getSelectedFile();    //if we have one file selected
                }am I going about dealing with this in the right way?

    OK, I scoured the API again and found I could avoid the problem altogether by using
    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JFileChooser.html#isMultiSelectionEnabled()
    and
    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JFileChooser.html#setFileSelectionMode(int)

  • Cant't get one to many relation to work.

    I tried to without success to retrieve an object that represents a simple
    parent child relation in an existing database. (the object is supposed to
    represent one record of the parent table and contain a Collection of all
    records in the child table)
    I have these two tables:
    table "refrul" is the parent table (column "nr" is the primary key)
    table "reftab" is the child (column "refundrule" points to refrul.nr)
    This is my .jdo file
    <?xml version="1.0"?>
    <jdo>
    <package name="jdbctest">
    <class name="RefundRule" objectid-class="RefundRuleId">
    <extension vendor-name="kodo" key="table" value="refrul"/>
    <extension vendor-name="kodo" key="lock-column" value="none"/>
    <extension vendor-name="kodo" key="class-column" value="none"/>
    <field name="ruleNr" primary-key="true">
    <extension vendor-name="kodo" key="data-column" value="nr"/>
    </field>
    <field name="ruleName">
    <extension vendor-name="kodo" key="data-column"
    value="name"/>
    </field>
    <field name="minSalesAmount">
    <extension vendor-name="kodo" key="data-column"
    value="minsalesamount"/>
    </field>
    <field name="refundTable">
    <collection element-type="RefundTableRow"/>
    <extension vendor-name="kodo" key="table" value="reftab"/>
    <extension vendor-name="kodo" key="ruleNr-ref-column"
    value="refundrule"/>
    </field>
    </class>
    <class name="RefundTableRow" objectid-class="RefundTableRowId">
    <extension vendor-name="kodo" key="table" value="reftab"/>
    <extension vendor-name="kodo" key="lock-column" value="none"/>
    <extension vendor-name="kodo" key="class-column" value="none"/>
    <field name="ruleNr" primary-key="true">
    <extension vendor-name="kodo" key="data-column"
    value="refundrule"/>
    </field>
    <field name="vatRate" primary-key="true">
    <extension vendor-name="kodo" key="data-column"
    value="ustsatz"/>
    </field>
    <field name="fromSalesAmount" primary-key="true">
    <extension vendor-name="kodo" key="data-column"
    value="ab_betrag"/>
    </field>
    <field name="refundPercent">
    <extension vendor-name="kodo" key="data-column"
    value="refund_prozent"/>
    </field>
    <field name="refundAmount">
    <extension vendor-name="kodo" key="data-column"
    value="refund_betrag"/>
    </field>
    </class>
    </package>
    </jdo>
    I get an exception showing this query:
    [SQL=SELECT t0.ab_betrag, t0.refundrule, t0.ustsatz, t0.refund_betrag,
    t0.refund_prozent, t0.RULENAMEX
    FROM reftab t0 WHERE(t0.refundrule = 0 AND t0.ab_betrag =
    t0.FROMSALESAMOUNT_REFUNDTABLEX AND t0.refundrule = t0.RULENR_REFUNDTABLEX
    AND t0.ustsatz = t0.VATRATE_REFUNDTABLEX)]
    All columns in uppercase do not exist in my tables, so this must generate an
    exception.
    Also the join seems strange I would have expected only " ...
    WHERE(t0.refundrule = parenttableRuleNr)".
    Whats wrong?
    I am using kodo 2.3
    Regards,
    Bernhard

    Abe,
    the strange column names are gone now, but it still does not work
    This is my new .jdo file (Iadded the "inverse" line)
    <?xml version="1.0"?>
    <jdo>
    <package name="jdbctest">
    <class name="RefundRule" objectid-class="RefundRuleId">
    <extension vendor-name="kodo" key="table" value="refrul"/>
    <extension vendor-name="kodo" key="lock-column" value="none"/>
    <extension vendor-name="kodo" key="class-column" value="none"/>
    <field name="ruleNr" primary-key="true">
    <extension vendor-name="kodo" key="data-column" value="nr"/>
    </field>
    <field name="ruleName">
    <extension vendor-name="kodo" key="data-column"
    value="name"/>
    </field>
    <field name="minSalesAmount">
    <extension vendor-name="kodo" key="data-column"
    value="minsalesamount"/>
    </field>
    <field name="refundStep">
    <extension vendor-name="kodo" key="data-column"
    value="refundstep"/>
    </field>
    <field name="refundTable">
    <collection element-type="RefundTableRow"/>
    <extension vendor-name="kodo" key="table" value="reftab"/>
    <extension vendor-name="kodo" key="ruleNr-ref-column"
    value="refundrule"/>
    <extension vendor-name="kodo" key="inverse" value="ruleNr"/>
    </field>
    </class>
    <class name="RefundTableRow" objectid-class="RefundTableRowId">
    <extension vendor-name="kodo" key="table" value="reftab"/>
    <extension vendor-name="kodo" key="lock-column" value="none"/>
    <extension vendor-name="kodo" key="class-column" value="none"/>
    <field name="ruleNr" primary-key="true">
    <extension vendor-name="kodo" key="data-column"
    value="refundrule"/>
    </field>
    <field name="vatRate" primary-key="true">
    <extension vendor-name="kodo" key="data-column"
    value="ustsatz"/>
    </field>
    <field name="fromSalesAmount" primary-key="true">
    <extension vendor-name="kodo" key="data-column"
    value="ab_betrag"/>
    </field>
    <field name="refundPercent">
    <extension vendor-name="kodo" key="data-column"
    value="refund_prozent"/>
    </field>
    <field name="refundAmount">
    <extension vendor-name="kodo" key="data-column"
    value="refund_betrag"/>
    </field>
    </class>
    </package>
    </jdo>
    This the generated SQL:
    [SQL=SELECT t0.nr, t0.minsalesamount, t0.refundstep, t0.name FROM refrul t0,
    reftab t1 WHERE (t0.nr = t1.nr)]
    This throws an exception because t1.nr (reftab.nr) does not exist, it should
    be reftab.refundrule. This would be correct:
    SELECT t0.nr, t0.minsalesamount, t0.refundstep, t0.name FROM refrul t0,
    reftab t1 WHERE (t0.nr = t1.refundrule)]
    Regards,
    Bernhard

  • Delete few child objects of One to Many relation.

    Hi
    we have the follwoing relation. Employee -> Addresses
    One employe is having 5 addresses.
    Now we need to delete 2 addresses for this employee.
    Can any one suggest the best way to do this in my java program.
    regards
    Ram kumar

    Are you using JPA or the native TopLink API?
    Either remove them from the Employee then call deleteObject/remove on them. Or mark the relationship as privateOwned in TopLink and just remove them.
    -- James : http://www.eclipselink.org

Maybe you are looking for

  • How do i use the airport extreme to extend my wireless network

    How do i connected my airport extreme up to my existing network so that it can extend my wireless through out the house ?? Can it be done wirelessly or do i need an ethernet cable thats about 10m ? Keith

  • How do I find the names of embedded video

    I have moves embedded in Keynote files that I can no longer trace back to their original movie files.  If the movies are fully embedded, this means I cannot find the original videos to edit or enhance them.  When the movies are only linked, it means

  • CRM 5.0 ERMS - Setting Priority, Due Date etc of Incoming Email

    Hi Gurus We've moved our incoming e-mail processing from a Non-ERMS set-up to an ERMS set-up. Previously we were able to assign the Priority & Due Date for Incoming Emails in Transaction. SPRO -> IMG -> Customer Relationship Management -> Interaction

  • How to insert more than one row in an Oracle table in one go

    Hi All, I am working on a file-XI(BPM)-Oracle scenario. I am sending an xml file to XI via a file adapter. On the receiver end i am using a jdbc adapter to insert the row in the database. There is a transformation step within the BPM which is convert

  • How to make installer of my java application for linux

    I want to make an installer for my java application, I am using Install any where trial version its create an installer but when i installed n execute it, it display that "unable to locate main class, class must be public n having a public static voi