• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to assign foreign key relationships in EJB!!

 
clement valentine
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,
Iam in the process of moving to EJB 2 from EJB 1.1 and I have a question regarding the ejbCreate() method.
Lets say I have 2 database tables DEPT and EMP:
1) DEPT (DEPTNO primary key, DNAME, LOCATION)
2) EMP (EMPNO primary key, ENAME, ADDRESS, DEPTNO foreign key NOT NULL)
I have a one-to-many unidirectional relationship from DEPT--->EMP. These are my abstract accessor methods in DeptEJB:
1) get/set deptNo
1) get/set dname
2) get/set location
3) getEmployees / setEmployees (takes and returns a collection object)

My question is how do I create an EMP?
I tried the following steps.
1) findByPrimarykey the dept.
2) call create on EmpEJB (returns local interface)
3) call a business method in DeptEJB that calls the getEmployees and then setEmployees.
This works fine if the foreign key is declared NULLABLE!..But in case of NOT NULLS, the ejbCreate in step 2 fails. So how can I insert a EMP?
TIA
 
Karthik Guru
Ranch Hand
Posts: 1209
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i too am learning the same.
But your EMP bean takes a DEPT bean in it's create right?? I mean if the foreign key is not null then the EMP create s'd have a DEPT bean available when it inserts a record.
Do you have a setDept() in your EMP bean??
You might have to do
Class EMP implements EntityBean{
ejbCreate(<something>,DEPT dept){
}
ejbPostCreate(<something>,DEPT dept){
setDept(dept);
}
}
I guess CMP does'nt allow setting the relationship field in the ejbCreate( ) so you might have to do it in ejbPostCreate()
 
clement valentine
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Thanks for the reply. So you are suggesting the relationship to be bidirectional. I will give it a try.
Thanks
 
clement valentine
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys,
I changed the relationship to bidirectional and called the setDept() accessor method from within the ejbPostCreate() and it worked.
ALternatively changing the relationship to one-to-one (unidirectional) from EMP to DEPT also works. So its just a matter of getting the business relationship right.
Thanks a lot!!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!