Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

EJB Composite Keys

Posted on 2005-03-07
19
Medium Priority
?
452 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
  • 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

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

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses
Course of the Month11 days, 12 hours left to enroll

564 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