?
Solved

EJB Composite Keys

Posted on 2005-03-07
19
Medium Priority
?
442 Views
Last Modified: 2013-11-24
My Entity Home Interface
================
...
public MemberLocal findByPrimaryKey(String sMemberID) throws FinderException;
...


My SessionBean
==========

private MemberLocalHome memberHome;
..
..

MemberLocal c = null;

try {
    // member.getMemberID() returns an ID
    c = memberHome.findByPrimaryKey(member.getMemberID());

    System.out.println("ID = " c.getMemberID());
    System.out.println("Name = " c.getMemberName());
}
catch (...) {
   ...
}


The above is okay in this case because the database table has got only 1 single field as a primary key (String).

What if I have an entity and I wish to retrieve from a database table with composite keys (more than 1 primary key)? What should be in the parameter of findByPrimaryKey(..)? What do I have to be careful of?


Experts, I need your help.

Cheers
hongjun
0
Comment
Question by:hongjun
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 9
19 Comments
 
LVL 35

Accepted Solution

by:
TimYates earned 2000 total points
ID: 13475304
Example PK class:

public class MyPK implements java.io.Serializable
{
  int id1 ;
  int id2 ;

  public MyPK( int id1, int id2 )
  {
    this.id1 = id1 ;
    this.id2 = id2 ;
  }

  public int getId1()
  {
    return id1 ;
  }

  public void setId1( int id1 )
  {
    this.id1 = id1 ;
  }

  public int getId2()
  {
    return id2 ;
  }

  public void setId2( int id2 )
  {
    this.id2 = id2 ;
  }

  // need this, so the container can compare PKs
  // this is a RUBBISH way of getting a hashcode ;-)  But it works! ;-)
  public int hashCode()
  {
    return new String( id1 + ":" + id2 ).hashCode() ;
  }

  public boolean equals( Object o )
  {
    if( ( o == null ) || !( o instanceof MyPK ) )
      return false ;
    return ((AccesscontrolPK)o).id1 == id1 &&
           ((AccesscontrolPK)o).id2 == id2 ;
  }
}

Then,

   public MemberLocal findByPrimaryKey( MyPK pk ) throws FinderException;

and make sure ejbCreate returns an object of class MyPK...

Hope this helps...

Tim
0
 
LVL 35

Expert Comment

by:TimYates
ID: 13475327
Apparently, the PetStore demo you can download off loads of places on the net has an example of composite keys in it :-)
0
 
LVL 6

Expert Comment

by:durgaprasad_j
ID: 13475645
hi,
you can write your own finder  methods  with as many arguments  as you want and associate that with corresponding ejb-ql.

try reading about finder classes.
http://www.cs.unc.edu/Courses/jbs/lessons/java/java_ejb_finder/
http://www.ejbtut.com/EntityFinders.jsp

Hope this helps
0
Quick Cloud Training

Looking for some quick training on the cloud in 2 hours or less? Check out these how-to guides in AWS, Linux, OpenStack, Azure, and more!

 
LVL 33

Author Comment

by:hongjun
ID: 13476421
I will try out tomorrow or in a few days time.
Kinda busy these few days with lots of assignments :'(
I want to cry out loud.

hongjun
0
 
LVL 33

Author Comment

by:hongjun
ID: 13485726
TimYates,

the example given by you is using 2 integers for the constructor. Am I correct to say if I require 3 composite keys, I will have another constructor that will have 3 parameters?

hongjun
0
 
LVL 33

Author Comment

by:hongjun
ID: 13485745
All Experts,

Could you help me out on this question too?
http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21341937.html


hongjun
0
 
LVL 35

Expert Comment

by:TimYates
ID: 13486261
>> Am I correct to say

Yup, and you will have to add the extra parameters into equals() and hashCode() :-)

Tim
0
 
LVL 33

Author Comment

by:hongjun
ID: 13486572
equals() ???
But then the method is accepting only 1 parameter.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 13486684
yeah, but it checks all parts of the key are equal ;-)
0
 
LVL 33

Author Comment

by:hongjun
ID: 13486770
So just 1 primarykey class to carter for all possibilities combination of composite keys?
0
 
LVL 35

Expert Comment

by:TimYates
ID: 13486813
Errr...not sure I get what you mean...

One class to represent one Primary key

eg: http://java.sun.com/j2ee/1.4/docs/tutorial-update2/doc/CMP7.html
0
 
LVL 33

Author Comment

by:hongjun
ID: 13487331
i am using BMP
0
 
LVL 33

Author Comment

by:hongjun
ID: 13487352
>>Errr...not sure I get what you mean
Which part are you uncertain of?

Because there are surely possibilities where there are different combinations of composite keys like "integer and integer", "integer only", "integer integer and integer", "integer and string", etc. Can the primary key class you suggested carter for all these? Or should there be one class for each combination?

hongjun
0
 
LVL 35

Expert Comment

by:TimYates
ID: 13487363
So do it...  it shouldn't matter, the idea is the same :-)

Is it not compiling?

What errors are you getting?

0
 
LVL 35

Expert Comment

by:TimYates
ID: 13487369
> Or should there be one class for each combination?

One PK per EntityBean that needs a Primary key...
0
 
LVL 35

Expert Comment

by:TimYates
ID: 13487378
EG:

  CusomerPK
  OrderPK
  ReportPK

etc...

Not just

  GenericPK

for all of them...
0
 
LVL 33

Author Comment

by:hongjun
ID: 13487947
@TimYates

To be frank with you, I have not tried any of them because of many other project commitments. However, I am certainly not wasting or playing with your precious time here. I do take your every comment seriously and I take effort in asking questions which I feel I will encounter when I try them.

All of the comments you posted sound logical and reasonable. I will put this question on hold for now but I will return after I have tried. Be rest assured that this question will not fall into the "Abandoned" list.


Cheers
hongjun
0
 
LVL 35

Expert Comment

by:TimYates
ID: 13488013
Cool :-)

Hope I helped, and chat soon :-)

Good luck!

Tim
0
 
LVL 33

Author Comment

by:hongjun
ID: 13526730
@TimYates

I used yours and build mine. Below is my primary key class and it can be used for many different combination of composite keys. Hope this will benefit other users reading this PAQ in the future.

/*
 * DBCompositePK.java
 *
 * Created on March 12, 2005, 4:16 AM
 * 01 instanceof 02, Hashtable is Serializable
 */

package com.solarCruise.db;

import java.util.Hashtable;
import java.util.Collection;
import java.lang.NullPointerException;
import java.lang.ClassCastException;

public class DBCompositePK implements java.io.Serializable {
   
    private Hashtable htPK;
   
    /** Creates a new instance of DBCompositePK */
    public DBCompositePK() {
        htPK = new Hashtable(2);
    }
   
    public DBCompositePK(int intPKNos) {
        htPK = new Hashtable(intPKNos);
    }
   
    public boolean findKeyValue(String strKey){
        try{
           return htPK.contains(strKey);
        }
        catch(NullPointerException npe){
            return false;
        }
    }
   
    public Object getKeyValueObj(String strKey) throws NullPointerException{
        return htPK.get(strKey); //Return null if key not found
    }
   
    public int getKeyValueInt(String strKey) throws NullPointerException, NumberFormatException, ClassCastException {
        Object obj = htPK.get(strKey);
       
        if ( obj != null )
            return ((Integer) htPK.get(strKey)).intValue();
        else
            throw new NullPointerException("key not found in object");
    }
   
    public String getKeyValueString(String strKey) throws NullPointerException, ClassCastException {
        Object obj = htPK.get(strKey);
       
        if ( obj != null )
            return ((String) htPK.get(strKey));
        else
            throw new NullPointerException("key not found in object");
    }

    public void setKeyValue(String strKey, Object oValue) throws NullPointerException{
        htPK.put(strKey, oValue);
    }
   
    public void setKeyValueInt(String strKey, int intValue) throws NullPointerException{
        Integer iValue = new Integer(intValue);
        htPK.put(strKey, iValue);
    }
   
    public void setKeyValueString(String strKey, String sValue) throws NullPointerException{
        htPK.put(strKey, sValue);
    }
   
    public void removeKeyValue(String strKey) throws NullPointerException{
        htPK.remove(strKey);
    }

    public Collection getHashCollection(){
        return htPK.values();
    }
   
    public int hashCode(){
        return htPK.hashCode();        
    }
   
    public boolean equals(Object obj) {
        //Check for null object
        if (obj == null) return false;
       
        //Check for class equal
        if (!this.getClass().equals(obj.getClass())) return false;
       
        //Check for Hashtable values
        DBCompositePK obj2 = (DBCompositePK) obj;
       
        if (htPK.values().equals(obj2.getHashCollection())) {
            return true; //Hashtable have the same value
        }
        else
            return false; //Hashtable value is different
    }
       
}

Cheers
hongjun
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month8 days, 5 hours left to enroll

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question