-->
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.  [ 6 posts ] 
Author Message
 Post subject: Need help in mapping foreign key..Solution not working.
PostPosted: Thu Dec 13, 2007 8:14 am 
Newbie

Joined: Fri Dec 07, 2007 8:58 am
Posts: 8
Guys,

I am new to hibernate.I want to know how to map a foreign key in hibernate configuration.

I have two tables.

Table: Employee

column: SerialNo (INTEGER) (PK)

column: Name (VARCHAR)

column: DepartmentNo(INTEGER) (FK)

Table: Department


column: DepartmentNo(INTEGER) (PK)

column: DepartmentName(VARCHAR)

Classes I use are.

Employee.java

public class Employee {

int serialno;
String name;
int Deptno;
public int getSerialno() {
return serialno;
}
public void setSerialno(int serialno) {
this.serialno = serialno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}


Department.java

public class Department {

int deptno;
String DeptName;
public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}

}


Can Some one please help me how to map the foreign key in the .hbm.xml file?

Hope to hear from one.

Thanks.


Last edited by anoopmenon on Mon Dec 17, 2007 5:34 am, edited 1 time in total.

Top
 Profile  
 
 Post subject:
PostPosted: Sat Dec 15, 2007 10:59 am 
Newbie

Joined: Tue Nov 27, 2007 6:11 am
Posts: 12
I guess the mapping for the person class should be:
Code:
<one-to-one name="departiment" class="Department"/>


Top
 Profile  
 
 Post subject:
PostPosted: Sat Dec 15, 2007 11:05 am 
Beginner
Beginner

Joined: Fri Jun 25, 2004 11:47 am
Posts: 34
Hi,
Check documentation section: 5.1.10. many-to-one

In your employee mapping you will have to declare something similar to:
Code:
<many-to-one name="department" class="Department" column="DepartmentNo"/>


Top
 Profile  
 
 Post subject: Tried it But its not working.Code,Xml files and error posted
PostPosted: Sun Dec 16, 2007 6:19 am 
Newbie

Joined: Fri Dec 07, 2007 8:58 am
Posts: 8
ok I tried it.I am getting errors though.I am pasting the code,xml files and the error from eclipse console below.Please have a look and tell me where I went wrong.
Thanks in advance


Employee.java
public class Employee {



int Deptno;
int serialno;
String name;

public int getSerialno() {
return serialno;
}
public void setSerialno(int serialno) {
this.serialno = serialno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getDeptno() {
return Deptno;
}
public void setDeptno(int deptno) {
Deptno = deptno;
}



}


Employee.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="Employee" table="Employee">
<id name="serialno" type="int" column="serialno" >
<generator class="assigned"/>
</id>
<many-to-one name="Deptno" class="Department" column="Deptno"/>

<property name="name">
<column name="name" />
</property>

</class>
</hibernate-mapping>



Department.java
public class Department {


int Deptno;
String DeptName;

public String getDeptName() {
return DeptName;
}
public void setDeptName(String deptName) {
DeptName = deptName;
}
public int getDeptno() {
return Deptno;
}
public void setDeptno(int deptno) {
Deptno = deptno;
}

}


Department.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="Department" table="Department">
<id name="Deptno" type="int" column="Deptno" >
<generator class="assigned"/>
</id>

<one-to-one name="Deptno" class="Employee" property-ref="Deptno"/>
<property name="DeptName">
<column name="DeptName" />
</property>

</class>
</hibernate-mapping>



Test.java(Test program that I use to call all the functions)


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class test {
public static void main(String[] args) {
Session session = null;

try{

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
Department department = new Department();
Employee employee = new Employee();

department.setDeptName("IT");
department.setDeptno(5);

employee.setName("seby");
employee.setSerialno(4);
Transaction tx=session.beginTransaction();
session.save(department);
session.save(employee);
tx.commit();

System.out.println("INSERTING RECORDS TO DB" );
}catch(Exception e){
System.out.println(e.getMessage());
}finally{

session.flush();
session.close();

}

}
}


hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping files -->

<mapping resource="Department.hbm.xml"/>
<mapping resource="Employee.hbm.xml"/>

</session-factory>
</hibernate-configuration>


Eclipse Console
05:15:32,531 INFO Environment:464 - Hibernate 3.0.5
05:15:32,531 INFO Environment:477 - hibernate.properties not found
05:15:32,531 INFO Environment:510 - using CGLIB reflection optimizer
05:15:32,546 INFO Environment:540 - using JDK 1.4 java.sql.Timestamp handling
05:15:32,625 INFO Configuration:1110 - configuring from resource: /hibernate.cfg.xml
05:15:32,625 INFO Configuration:1081 - Configuration resource: /hibernate.cfg.xml
05:15:33,093 INFO Configuration:444 - Mapping resource: Department.hbm.xml
05:15:33,234 INFO HbmBinder:260 - Mapping class: Department -> Department
05:15:33,265 INFO Configuration:444 - Mapping resource: Employee.hbm.xml
05:15:33,296 INFO HbmBinder:260 - Mapping class: Employee -> Employee
05:15:33,375 INFO Configuration:1222 - Configured SessionFactory: null
05:15:33,375 INFO Configuration:875 - processing extends queue
05:15:33,375 INFO Configuration:879 - processing collection mappings
05:15:33,375 INFO Configuration:888 - processing association property references
05:15:33,375 INFO Configuration:917 - processing foreign key constraints
05:15:33,390 INFO DriverManagerConnectionProvider:41 - Using Hibernate built-in connection pool (not for production use!)
05:15:33,390 INFO DriverManagerConnectionProvider:42 - Hibernate connection pool size: 10
05:15:33,390 INFO DriverManagerConnectionProvider:45 - autocommit mode: false
05:15:33,406 INFO DriverManagerConnectionProvider:80 - using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost/test
05:15:33,406 INFO DriverManagerConnectionProvider:86 - connection properties: {user=root, password=****}
05:15:33,828 INFO SettingsFactory:77 - RDBMS: MySQL, version: 5.0.45-community-nt
05:15:33,828 INFO SettingsFactory:78 - JDBC driver: MySQL-AB JDBC Driver, version: mysql-connector-java-5.1.5 ( Revision: ${svn.Revision} )
05:15:33,843 INFO Dialect:92 - Using dialect: org.hibernate.dialect.MySQLDialect
05:15:33,859 INFO TransactionFactoryFactory:31 - Using default transaction strategy (direct JDBC transactions)
05:15:33,859 INFO TransactionManagerLookupFactory:33 - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended)
05:15:33,859 INFO SettingsFactory:125 - Automatic flush during beforeCompletion(): disabled
05:15:33,859 INFO SettingsFactory:129 - Automatic session close at end of transaction: disabled
05:15:33,859 INFO SettingsFactory:136 - JDBC batch size: 15
05:15:33,859 INFO SettingsFactory:139 - JDBC batch updates for versioned data: disabled
05:15:33,859 INFO SettingsFactory:144 - Scrollable result sets: enabled
05:15:33,859 INFO SettingsFactory:152 - JDBC3 getGeneratedKeys(): enabled
05:15:33,859 INFO SettingsFactory:160 - Connection release mode: null
05:15:33,859 INFO SettingsFactory:184 - Maximum outer join fetch depth: 2
05:15:33,859 INFO SettingsFactory:187 - Default batch fetch size: 1
05:15:33,859 INFO SettingsFactory:191 - Generate SQL with comments: disabled
05:15:33,859 INFO SettingsFactory:195 - Order SQL updates by primary key: disabled
05:15:33,859 INFO SettingsFactory:334 - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory
05:15:33,859 INFO ASTQueryTranslatorFactory:21 - Using ASTQueryTranslatorFactory
05:15:33,859 INFO SettingsFactory:203 - Query language substitutions: {}
05:15:33,859 INFO SettingsFactory:209 - Second-level cache: enabled
05:15:33,859 INFO SettingsFactory:213 - Query cache: disabled
05:15:33,859 INFO SettingsFactory:321 - Cache provider: org.hibernate.cache.EhCacheProvider
05:15:33,875 INFO SettingsFactory:228 - Optimize cache for minimal puts: disabled
05:15:33,875 INFO SettingsFactory:237 - Structured second-level cache entries: disabled
05:15:33,875 INFO SettingsFactory:257 - Echoing all SQL to stdout
05:15:33,875 INFO SettingsFactory:261 - Statistics: disabled
05:15:33,875 INFO SettingsFactory:265 - Deleted entity synthetic identifier rollback: disabled
05:15:33,890 INFO SettingsFactory:279 - Default entity-mode: pojo
05:15:34,046 INFO SessionFactoryImpl:152 - building session factory
05:15:34,046 DEBUG CacheManager:191 - Creating new CacheManager with default config
05:15:34,046 DEBUG CacheManager:164 - Configuring ehcache from classpath.
05:15:34,062 WARN Configurator:126 - No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/C:/Documents%20and%20Settings/anoop/Desktop/hibernate-3.0.5/hibernate-3.0/lib/ehcache-1.1.jar!/ehcache-failsafe.xml
05:15:34,078 DEBUG Configuration$DiskStore:185 - Disk Store Path: C:\DOCUME~1\anoop\LOCALS~1\Temp\
05:15:34,453 INFO SessionFactoryObjectFactory:82 - Not binding factory to JNDI, no JNDI name configured
05:15:34,453 INFO Dialect:92 - Using dialect: org.hibernate.dialect.MySQLDialect
05:15:34,453 INFO DriverManagerConnectionProvider:41 - Using Hibernate built-in connection pool (not for production use!)
05:15:34,453 INFO DriverManagerConnectionProvider:42 - Hibernate connection pool size: 10
05:15:34,453 INFO DriverManagerConnectionProvider:45 - autocommit mode: false
05:15:34,453 INFO DriverManagerConnectionProvider:80 - using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost/test
05:15:34,453 INFO DriverManagerConnectionProvider:86 - connection properties: {user=root, password=****}
05:15:34,453 INFO SchemaUpdate:105 - Running hbm2ddl schema update
05:15:34,453 INFO SchemaUpdate:117 - fetching database metadata
05:15:34,484 INFO SchemaUpdate:133 - updating schema
05:15:34,484 INFO Configuration:875 - processing extends queue
05:15:34,484 INFO Configuration:879 - processing collection mappings
05:15:34,484 INFO Configuration:888 - processing association property references
05:15:34,484 INFO Configuration:917 - processing foreign key constraints
05:15:34,515 INFO TableMetadata:38 - table found: test.department
05:15:34,515 INFO TableMetadata:39 - columns: [deptno, deptname]
05:15:34,515 INFO TableMetadata:40 - foreign keys: []
05:15:34,531 INFO TableMetadata:41 - indexes: [primary]
05:15:34,546 INFO TableMetadata:38 - table found: test.employee
05:15:34,546 INFO TableMetadata:39 - columns: [name, deptno, serialno]
05:15:34,546 INFO TableMetadata:40 - foreign keys: [fk4afd4ace59c8ae38]
05:15:34,546 INFO TableMetadata:41 - indexes: [fk4afd4ace59c8ae38, primary]
05:15:34,546 INFO SchemaUpdate:153 - schema update complete
05:15:34,546 INFO DriverManagerConnectionProvider:147 - cleaning up connection pool: jdbc:mysql://localhost/test
05:15:34,546 INFO SessionFactoryImpl:379 - Checking 0 named queries
05:15:34,625 ERROR BasicPropertyAccessor:115 - IllegalArgumentException in class: Department, getter method of property: Deptno
IllegalArgumentException occurred calling getter of Department.Deptno
05:15:34,640 DEBUG SQL:324 - insert into Department (DeptName, Deptno) values (?, ?)
Hibernate: insert into Department (DeptName, Deptno) values (?, ?)
05:15:34,671 DEBUG SQL:324 - update Employee set Deptno=?, name=? where serialno=?
Hibernate: update Employee set Deptno=?, name=? where serialno=?
05:15:34,671 ERROR BasicPropertyAccessor:115 - IllegalArgumentException in class: Department, getter method of property: Deptno
05:15:34,671 ERROR AbstractFlushingEventListener:277 - Could not synchronize database state with session
org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of Department.Deptno
at org.hibernate.property.BasicPropertyAccessor$BasicGetter.get(BasicPropertyAccessor.java:119)
at org.hibernate.tuple.AbstractTuplizer.getIdentifier(AbstractTuplizer.java:103)
at org.hibernate.persister.entity.BasicEntityPersister.getIdentifier(BasicEntityPersister.java:2944)
at org.hibernate.persister.entity.BasicEntityPersister.isTransient(BasicEntityPersister.java:2705)
at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:181)
at org.hibernate.engine.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:215)
at org.hibernate.type.EntityType.getIdentifier(EntityType.java:99)
at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:63)
at org.hibernate.persister.entity.BasicEntityPersister.dehydrate(BasicEntityPersister.java:1617)
at org.hibernate.persister.entity.BasicEntityPersister.update(BasicEntityPersister.java:1963)
at org.hibernate.persister.entity.BasicEntityPersister.updateOrInsert(BasicEntityPersister.java:1909)
at org.hibernate.persister.entity.BasicEntityPersister.update(BasicEntityPersister.java:2149)
at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:75)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:239)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:223)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:137)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:274)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:730)
at test.main(test.java:33)
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:105)
... 19 more
Exception in thread "main" org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of Department.Deptno
at org.hibernate.property.BasicPropertyAccessor$BasicGetter.get(BasicPropertyAccessor.java:119)
at org.hibernate.tuple.AbstractTuplizer.getIdentifier(AbstractTuplizer.java:103)
at org.hibernate.persister.entity.BasicEntityPersister.getIdentifier(BasicEntityPersister.java:2944)
at org.hibernate.persister.entity.BasicEntityPersister.isTransient(BasicEntityPersister.java:2705)
at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:181)
at org.hibernate.engine.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:215)
at org.hibernate.type.EntityType.getIdentifier(EntityType.java:99)
at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:63)
at org.hibernate.persister.entity.BasicEntityPersister.dehydrate(BasicEntityPersister.java:1617)
at org.hibernate.persister.entity.BasicEntityPersister.update(BasicEntityPersister.java:1963)
at org.hibernate.persister.entity.BasicEntityPersister.updateOrInsert(BasicEntityPersister.java:1909)
at org.hibernate.persister.entity.BasicEntityPersister.update(BasicEntityPersister.java:2149)
at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:75)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:239)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:223)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:137)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:274)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:730)
at test.main(test.java:33)
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:105)
... 19 more

-------------------------------------------------------------------------------------


Top
 Profile  
 
 Post subject:
PostPosted: Mon Dec 17, 2007 5:36 am 
Newbie

Joined: Fri Dec 07, 2007 8:58 am
Posts: 8
Can Someone please have a look and tell me what the problem is ?

Thanks in advance.


Top
 Profile  
 
 Post subject:
PostPosted: Mon Dec 17, 2007 3:46 pm 
Newbie

Joined: Tue Aug 03, 2004 10:31 am
Posts: 7
I think taht you have an error in the classes definition.

You have to define a list in Department (I assume that you've got a one-to-many relationship beteween Department and Employees):
Code:
private List<Employee> employees = new ArrayList<Employee>();
.

In Java classes you have to think in objects... so, this mapping can work:

Code:
<hibernate-mapping>
<class name="Department" table="Department">
...
<list name="employees" lazy="true">
   <key column="DepartmentNo" not-null="true"/>
   <index column="LIST_IDX" /> <!--add it in Employee table-->
   <one-to-many class="Employee" />      

<one-to-one name="Deptno" class="Employee" property-ref="Deptno"/>
...
</class>
</hibernate-mapping>


Therefore you can navigate de Employees from a Department instances by de colletction getter.

Good luck [/quote]


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