-->
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: Foreign key not populated for one-to-many association
PostPosted: Fri Jun 06, 2008 7:28 pm 
Newbie

Joined: Fri Jun 06, 2008 2:03 pm
Posts: 9
This is my first post to the hibernate forum and I hope that this is not a stupid question. I am trying to write a simple one-many association between a Customer and Account. I am trying to insert Account and Customer into the database. What I am seeing is that foreign key in Customer table is being stored as null.

Hibernate version:3.2

Customer.hbm.xml

<?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 = "com.jbe.test.hibernate.model.Customer" table="customer">
<id name = "customerId" column="customer_id">
<generator class="increment" />
</id>

<property name = "firstName" column ="first_name" type = "string" />
<property name = "lastName" column = "last_name" type = "string" />
<property name = "address" type = "string" />
<property name = "age" type = "int" />
<property name = "dateOfBirth" column = "dob" type = "date" />

<set name="accounts">
<key column="customer_id" />
<one-to-many class="com.jbe.test.hibernate.model.Account" />
</set>
</class>
</hibernate-mapping>


Accounts.hbm.xml


<?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="com.jbe.test.hibernate.model.Account" table="account">
<id name="accountId" column="account_id" type="int" length="11">
<generator class="increment" />
</id>

<property name="accountNumber" column="account_number" type="int"
length="11" />
<property name="accountType" column="account_type" type="string" />
<property name="balance" type="int" column="balance" />
<property name="deposit" type="int" column="deposit" />
<property name="withdrawal" column="withdrawal" type="int" />
</class>
</hibernate-mapping>


My Code

session.beginTransaction();
for (Iterator<Account> iter = customer.getAccounts().iterator();
iter.hasNext();) {
session.save(iter.next());
}
session.save(customer);
session.getTransaction().commit();


Full stack trace of any exception that occurs:

Name and version of the database you are using: MySQL, version 5.0.22-Debian_0ubuntu6.06.10-log

SQl Statement
Hibernate: select max(account_id) from account
Hibernate: select max(customer_id) from customer
Hibernate: insert into account (account_number, account_type, balance, deposit, withdrawal, account_id) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into customer (first_name, last_name, address, age, dob, customer_id) values (?, ?, ?, ?, ?, ?)
Hibernate: update account set customer_id=? where account_id=?


Hibernate Log
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.Configuration configure
INFO: configuring from resource: /hibernate.cfg.xml
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: Configuration resource: /hibernate.cfg.xml
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource : com/jbe/test/hibernate/User.hbm.xml
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: com.jbe.test.hibernate.model.User -> user
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource : com/jbe/test/hibernate/Customer.hbm.xml
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: com.jbe.test.hibernate.model.Customer -> customer
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource : com/jbe/test/hibernate/Account.hbm.xml
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: com.jbe.test.hibernate.model.Account -> account
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.Configuration doConfigure
INFO: Configured SessionFactory: null
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.HbmBinder bindCollectionSecondPass
INFO: Mapping collection: com.jbe.test.hibernate.model.Customer.accounts -> account
Jun 6, 2008 3:47:43 PM org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: Using Hibernate built-in connection pool (not for production use!)
Jun 6, 2008 3:47:43 PM org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: Hibernate connection pool size: 20
Jun 6, 2008 3:47:43 PM org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: autocommit mode: false
Jun 6, 2008 3:47:43 PM org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/test
Jun 6, 2008 3:47:43 PM org.hibernate.connection.DriverManagerConnectionProvider configure
INFO: connection properties: {user=root, password=****}
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: RDBMS: MySQL, version: 5.0.22-Debian_0ubuntu6.06.10-log
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-3.1.13 ( $Date: 2005-11-17 15:53:48 +0100 (Thu, 17 Nov 2005) $, $Revision$ )
Jun 6, 2008 3:47:43 PM org.hibernate.dialect.Dialect <init>
INFO: Using dialect: org.hibernate.dialect.MySQLDialect
Jun 6, 2008 3:47:43 PM org.hibernate.transaction.TransactionFactoryFactory buildTransactionFactory
INFO: Using default transaction strategy (direct JDBC transactions)
Jun 6, 2008 3:47:43 PM org.hibernate.transaction.TransactionManagerLookupFactory getTransactionManagerLookup
INFO: No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic flush during beforeCompletion(): disabled
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Automatic session close at end of transaction: disabled
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC batch size: 15
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC batch updates for versioned data: disabled
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Scrollable result sets: enabled
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JDBC3 getGeneratedKeys(): enabled
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Connection release mode: auto
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Maximum outer join fetch depth: 2
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default batch fetch size: 1
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Generate SQL with comments: disabled
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Order SQL updates by primary key: disabled
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Order SQL inserts for batching: disabled
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory createQueryTranslatorFactory
INFO: Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
Jun 6, 2008 3:47:43 PM org.hibernate.hql.ast.ASTQueryTranslatorFactory <init>
INFO: Using ASTQueryTranslatorFactory
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query language substitutions: {}
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: JPA-QL strict compliance: disabled
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Second-level cache: enabled
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Query cache: disabled
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory createRegionFactory
INFO: Cache region factory : org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge
Jun 6, 2008 3:47:43 PM org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge <init>
INFO: Cache provider: org.hibernate.cache.NoCacheProvider
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Optimize cache for minimal puts: disabled
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Structured second-level cache entries: disabled
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Echoing all SQL to stdout
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Statistics: disabled
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Deleted entity synthetic identifier rollback: disabled
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Default entity-mode: pojo
Jun 6, 2008 3:47:43 PM org.hibernate.cfg.SettingsFactory buildSettings
INFO: Named query checking : enabled
Jun 6, 2008 3:47:43 PM org.hibernate.impl.SessionFactoryImpl <init>
INFO: building session factory
Jun 6, 2008 3:47:43 PM org.hibernate.impl.SessionFactoryObjectFactory addInstance
INFO: Not binding factory to JNDI, no JNDI name configured
Jun 6, 2008 3:47:43 PM org.hibernate.tool.hbm2ddl.SchemaValidator validate
INFO: Running schema validator
Jun 6, 2008 3:47:43 PM org.hibernate.tool.hbm2ddl.SchemaValidator validate
INFO: fetching database metadata
Jun 6, 2008 3:47:43 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: table found: test.account
Jun 6, 2008 3:47:43 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: columns: [balance, account_number, account_id, withdrawal, deposit, customer_id, account_type]
Jun 6, 2008 3:47:43 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: table found: test.customer
Jun 6, 2008 3:47:43 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: columns: [first_name, account_id, address, dob, age, last_name, customer_id]
Jun 6, 2008 3:47:43 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: table found: test.user
Jun 6, 2008 3:47:43 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: columns: [first_name, dob, age, last_name, userno]
Hibernate: select max(account_id) from account
Hibernate: select max(customer_id) from customer
Hibernate: insert into account (account_number, account_type, balance, deposit, withdrawal, account_id) values (?, ?, ?, ?, ?, ?)
Hibernate: insert into customer (first_name, last_name, address, age, dob, customer_id) values (?, ?, ?, ?, ?, ?)
Hibernate: update account set customer_id=? where account_id






Top
 Profile  
 
 Post subject:
PostPosted: Sat Jun 07, 2008 7:41 am 
Expert
Expert

Joined: Tue May 13, 2008 3:42 pm
Posts: 919
Location: Toronto & Ajax Ontario www.hibernatemadeeasy.com
Adding an account to the customer might need some code like this:

Code:
customer.getAccounts().add(account);


One thing you might try is using a CascadeType of all. Alternatively, try to save both sides of the association in your code and see if you start getting a valid id instead of a null field.

_________________
Cameron McKenzie - Author of "Hibernate Made Easy" and "What is WebSphere?"
http://www.TheBookOnHibernate.com Check out my 'easy to follow' Hibernate & JPA Tutorials


Last edited by Cameron McKenzie on Tue Jun 10, 2008 9:22 am, edited 1 time in total.

Top
 Profile  
 
 Post subject:
PostPosted: Sat Jun 07, 2008 7:46 am 
Regular
Regular

Joined: Wed Apr 09, 2008 10:28 am
Posts: 52
there are no stupid questions just stupid answers ;). The FK is Null because it is not associated with any customer of the Customer table. You can add a account to the customer like this:
customer.getAccounts().add(newaccount);
if your cascade options are correct after the commit the customer should have a new account.


Top
 Profile  
 
 Post subject:
PostPosted: Mon Jun 09, 2008 5:16 pm 
Newbie

Joined: Fri Jun 06, 2008 2:03 pm
Posts: 9
Thanks for all the replies. I have passed the customer information as follows using Junit 4.

@Parameters()
public static Collection<Object[]> getCustomerData() throws ParseException {
Customer customer = new Customer();
//customer.setCustomerId(1);
customer.setFirstName("Man");
customer.setLastName("Of Logan");
customer.setAge(18);
customer.setAccountId(1);
customer.setAddress("Any Street");
customer.setDateOfBirth(
new SimpleDateFormat("MM/dd/yyyy").parse("1/1/1990"));
Account account = new Account();
account.setAccountNumber(123456789);
account.setAccountType("CHK");
account.setBalance(15000);
account.setDeposit(15000);
account.setWithdrawal(0);
account.setCustomerId(1);
Set<Account> accounts = new HashSet<Account>();
accounts.add(account);
customer.setAccounts(accounts);
return Arrays.asList(new Object[][] {{customer}});
}


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.