Primary Key Class

Hi there,
In an entity bean, why do we need a primary key class? I read from some book that an entity bean can work all right without it. Is it true?
Regards

Hi,
In cases of Primary Keys defined as Strings, the creation of Primary Key class can be ignored by the bean provider/developer. However the primary key must be generated in the program either in the setprimarykey() defined in class implementing the EntityBean interface.
The ejb-jar.xml can have the entry as <prim-key-class>java.lang.String</prim-key-class> in such cases of both CMP and BMP EB.
As long as you generate the Primary Key and pass it in the various callback methods like ejbFindByPrimaryKey, ejbCreate etc, you can avoid creating the primary key class.
Remember in CMP the ejbCreate in the Home interface returns NULL while in BMP it is the primary key returned.
HTH,
Seetesh

Similar Messages

  • Comp. Primary key class-field mapping to DB columns problem.(EJB 2.0 CMP)

    Hi!
    I have deal with EJB 2.0 CMP bean.
    I have a composite PK so use the java class to store it. And there is a corresponding field in the Entity Bean with its primary key class type.
    The problem is: when deployment tool creates sql query for the findByPrimaryKey(PKClass ck)
    where ck is an object with 3 fielde : a_id, b_id, c_id.
    it says:
    <sql>SELECT "ck" FROM "MyTable" WHERE "ck" = ? </sql>
    And it means by the "ck" simple a column in DB but NOT the composite key which has to be splited into 3 different fields. So the container can't do the proper mapping.
    Does anyone know solutions?

    I was wrong about primary key class fields, take a look at Ejb2.0 Specification (10.8.2):
    The primary key class must be public, and must have a public constructor with no parameters.
    All fields in the primary key class must be declared as public.
    The names of the fields in the primary key class must be a subset of the names of the container-managed
    fields. (This allows the container to extract the primary key fields from an instance�s container-managed
    fields, and vice versa.)
    Right now I'm using BMP and I don't have this problems. Primary keys, calculated fields and types not supported by the DB can be easily achieved. But I understand your interest on CMP, is clearly evolving!

  • CMP Entity Beans with custom finders an primary key class

    Hi everybody.
    I've got a Entity with a primary key class and a custom finder. I've defined
    the finder into the xml file like iPlanet's documentation say, but, when I
    try to run the aplication I get the following error:
    Exception: SERVLET-run_failed: Failed in running template:
    /PruebaGI/PruebaGI/pruebagi.jsp, java.lang.ClassCastException:
    com.netscape.server.deployment.SessionBeanDescriptor
    Exception Stack Trace:
    java.lang.ClassCastException:
    com.netscape.server.deployment.SessionBeanDescriptor
    at
    com.netscape.server.servlet.servletrunner.AppInfo.popWebAppDescriptor(Unknow
    n Source)
    at com.netscape.server.servlet.servletrunner.ServletInfo.service(Unknown
    Source)
    at com.netscape.server.servlet.servletrunner.ServletRunner.callJSP(Unknown
    Source)
    at
    com.netscape.server.servlet.platformhttp.PlatformHttpServletResponse.callJsp
    Compiler(Unknown Source)
    at
    com.netscape.server.servlet.platformhttp.PlatformHttpServletResponse.callUri
    (Unknown Source)
    at
    com.netscape.server.servlet.platformhttp.PlatformHttpServletResponse.callUri
    RestrictOutput(Unknown Source)
    at
    com.netscape.server.servlet.platformhttp.PlatformRequestDispatcher.forward(U
    nknown Source)
    at com.netscape.server.servlet.jsp.JSPRunner.service(Unknown Source)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:865)
    at com.netscape.server.servlet.servletrunner.ServletInfo.service(Unknown
    Source)
    at com.netscape.server.servlet.servletrunner.ServletRunner.execute(Unknown
    Source)
    at com.kivasoft.applogic.AppLogic.execute(Unknown Source)
    at com.kivasoft.applogic.AppLogic.execute(Unknown Source)
    at com.kivasoft.thread.ThreadBasic.run(Native Method)
    at java.lang.Thread.run(Thread.java:479).
    Could anybody help my? I need to resolve this question quickly.
    Thx
    ..

    Hi Juan,
    Sounds like you've defined either a java.lang.String where it should have
    said Java.util.Vector (or the other way around) in the part of the
    deployment descriptor that defines your custom finder method parameter.
    Regards,
    Raymond
    "Juan Jos� Ayuso" <[email protected]> wrote in message
    news:[email protected]...
    Hi everybody.
    I've got a Entity with a primary key class and a custom finder. I'vedefined
    the finder into the xml file like iPlanet's documentation say, but, when I
    try to run the aplication I get the following error:
    Exception: SERVLET-run_failed: Failed in running template:
    /PruebaGI/PruebaGI/pruebagi.jsp, java.lang.ClassCastException:
    com.netscape.server.deployment.SessionBeanDescriptor
    Exception Stack Trace:
    java.lang.ClassCastException:
    com.netscape.server.deployment.SessionBeanDescriptor
    at
    com.netscape.server.servlet.servletrunner.AppInfo.popWebAppDescriptor(Unknow
    n Source)
    at com.netscape.server.servlet.servletrunner.ServletInfo.service(Unknown
    Source)
    atcom.netscape.server.servlet.servletrunner.ServletRunner.callJSP(Unknown
    Source)
    at
    com.netscape.server.servlet.platformhttp.PlatformHttpServletResponse.callJsp
    Compiler(Unknown Source)
    at
    com.netscape.server.servlet.platformhttp.PlatformHttpServletResponse.callUri
    (Unknown Source)
    at
    com.netscape.server.servlet.platformhttp.PlatformHttpServletResponse.callUri
    RestrictOutput(Unknown Source)
    at
    com.netscape.server.servlet.platformhttp.PlatformRequestDispatcher.forward(U
    nknown Source)
    at com.netscape.server.servlet.jsp.JSPRunner.service(Unknown Source)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:865)
    at com.netscape.server.servlet.servletrunner.ServletInfo.service(Unknown
    Source)
    atcom.netscape.server.servlet.servletrunner.ServletRunner.execute(Unknown
    Source)
    at com.kivasoft.applogic.AppLogic.execute(Unknown Source)
    at com.kivasoft.applogic.AppLogic.execute(Unknown Source)
    at com.kivasoft.thread.ThreadBasic.run(Native Method)
    at java.lang.Thread.run(Thread.java:479).
    Could anybody help my? I need to resolve this question quickly.
    Thx

  • Entity Bean with Primary Key Class

    Hi
    I am trying to develop an entity bean attached to a key which have a
    composite key using Primary Key Class. When I use the findByPrimaryKey
    method of the bean it throws an exception as follows,
    java.sql.SQLException: Parameter typecheck failed: invalid parameter type:
    ORA-00000: normal, successful completion
    at com.netscape.server.jdbc.PreparedStatement.verifyError(Unknown Source)
    at com.netscape.server.jdbc.PreparedStatement.afterVerify(Unknown Source)
    at com.netscape.server.jdbc.PreparedStatement.executeQuery(Unknown Source)
    at com.netscape.server.ejb.SQLPersistenceManager.find(Unknown Source)
    at
    com.netscape.server.ejb.EntityDelegateManagerImpl.doPersistentFind(Unknown
    Source)
    at com.netscape.server.ejb.EntityDelegateManagerImpl.find(Unknown Source)
    at com.kivasoft.eb.EBHomeBase.findSingleByParms(Unknown Source)
    at
    TestBean2.ejb_home_TestBean2_EntityBean2Bean.findByPrimaryKey(ejb_home_TestB
    ean2_EntityBean2Bean.java:120)
    at
    TestBean2.ejb_kcp_skel_EntityBean2Home.findByPrimaryKey__TestBean2_EntityBea
    n2__TestBean2_TestBKey(ejb_kcp_skel_EntityBean2Home.java:258)
    at com.kivasoft.ebfp.FPRequest.invokenative(Native Method)
    at com.kivasoft.ebfp.FPRequest.invoke(Unknown Source)
    at
    TestBean2.ejb_kcp_stub_EntityBean2Home.findByPrimaryKey(ejb_kcp_stub_EntityB
    ean2Home.java:341)
    at
    TestBean2.ejb_stub_EntityBean2Home.findByPrimaryKey(ejb_stub_EntityBean2Home
    ..java:88)
    at TestBean2.Simple1.defaultAction(Simple1.java:115)
    at TestBean2.Simple1.doGet(Simple1.java:26)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:865)
    at com.netscape.server.servlet.servletrunner.ServletInfo.service(Unknown
    Source)
    at com.netscape.server.servlet.servletrunner.ServletRunner.execute(Unknown
    Source)
    at com.kivasoft.applogic.AppLogic.execute(Unknown Source)
    at com.kivasoft.applogic.AppLogic.execute(Unknown Source)
    at com.kivasoft.thread.ThreadBasic.run(Native Method)
    at java.lang.Thread.run(Thread.java:479)
    javax.ejb.FinderException
    at com.netscape.server.ejb.SQLPersistenceManager.find(Unknown Source)
    at
    com.netscape.server.ejb.EntityDelegateManagerImpl.doPersistentFind(Unknown
    Source)
    at com.netscape.server.ejb.EntityDelegateManagerImpl.find(Unknown Source)
    at com.kivasoft.eb.EBHomeBase.findSingleByParms(Unknown Source)
    at
    TestBean2.ejb_home_TestBean2_EntityBean2Bean.findByPrimaryKey(ejb_home_TestB
    ean2_EntityBean2Bean.java:120)
    at
    TestBean2.ejb_kcp_skel_EntityBean2Home.findByPrimaryKey__TestBean2_EntityBea
    n2__TestBean2_TestBKey(ejb_kcp_skel_EntityBean2Home.java:258)
    at com.kivasoft.ebfp.FPRequest.invokenative(Native Method)
    at com.kivasoft.ebfp.FPRequest.invoke(Unknown Source)
    at
    TestBean2.ejb_kcp_stub_EntityBean2Home.findByPrimaryKey(ejb_kcp_stub_EntityB
    ean2Home.java:341)
    at
    TestBean2.ejb_stub_EntityBean2Home.findByPrimaryKey(ejb_stub_EntityBean2Home
    ..java:88)
    at TestBean2.Simple1.defaultAction(Simple1.java:115)
    at TestBean2.Simple1.doGet(Simple1.java:26)
    [03/Aug/2001 15:26:41:7] error: Exception: SERVLET-execution_failed: Error
    in executing servlet Simat
    javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
    at javax.servlet.http.HttpServletple1: java.lang.ClassCastException:
    com.netscape.server.deployment.EntityBeanDescriptor
    Exception .service(HttpServlet.java:865)
    at com.netscape.server.servlet.servletrunner.ServletInfo.service(Unknown
    Source)
    at com.netscape.server.servlet.servletrunner.ServletRunner.execute(Unknown
    Source)Stack Trace:
    java.lang.ClassCastException:
    com.netscape.server.deployment.EntityBeanDescriptor
    a
    at com.kivasoft.applogic.AppLogic.execute(Unknown Source)
    at com.kivasoft.applogic.AppLogic.ext
    com.netscape.server.servlet.servletrunner.AppInfo.popWebAppDescriptor(Unknow
    n Source)
    at com.netscape.server.servlet.servletrunner.ServletInfo.service(Unknown
    Source)
    at com.netscape.server.seecute(Unknown Source)
    at com.kivasoft.thread.ThreadBasic.run(Native Method)
    at java.lang.Threadrvlet.servletrunner.ServletRunner.execute(Unknown
    Source)
    at com.kivasoft.applogic.AppLogic.execu.run(Thread.java:479)
    te(Unknown Source)
    at com.kivasoft.applogic.AppLogic.execute(Unknown Source)
    at com.kivasoft.thread.ThreadBasic.run(Native Method)
    at java.lang.Thread.run(Thread.java:479)
    Any kind of help is appreciated. I am using iPlanet App Builder 6.0 with iAS
    6.0 SP1.
    Thanks
    Bhaskara Murthy
    Eclipse Networks Inc

    "Bhamu" <[email protected]> wrote in message
    news:9keuo4$[email protected]..
    I am trying to develop an entity bean attached to a key which have a
    composite key using Primary Key Class. When I use the findByPrimaryKey
    method of the bean it throws an exception as follows,I notice that you are using the reference CMP plugin.
    at com.netscape.server.ejb.SQLPersistenceManager.find(Unknown Source)I'm also willing to bet that you may have created your own primary key class
    with a single field, rather than using the fields type as a primitive
    primary key class. If you do this, then SQLPersistenceManager will break.
    It is badly written, and has some stupid assumptions. The one I remember
    the most is that if you only have one primary key field, then
    SQLPersistenceManager assumes you have used a primitive type such as
    java.lang.String or java.lang.Integer, to represent it, rather than creating
    your own <Enity>Pk.java file.
    SQLPersistenceManager works for toy examples, but in general I would say it
    is broken and unusable. Either use BMP, or splash out the money for Coco
    Base from Thought Inc. Currently the only CMP plugin for iPlanet App server,
    other than the reference implementation, that I know of.

  • Foreign Keys in Primary Key Class

    I am a newbie on toplink. I am getting an error when i run ejbc against the jar file with EJB2.0. One of the primary key classes two primary keys and both are foreign Keys to other tables. Primary Key class looks like this:
    public class LcaCyberzoneAssocPK implements java.io.Serializable
    public ValueHolderInterface lcaHolder;
    public ValueHolderInterface cyberzoneDefHolder;
    public LcaCyberzoneAssocPK(ValueHolderInterface lcaHolder,
    ValueHolderInterface cyberzoneDefHolder)
    super();
    this.lcaHolder = lcaHolder;
    this.cyberzoneDefHolder = cyberzoneDefHolder;
    Bean Class has following four methods:
    public abstract Lca getLcaHolder()
    throws RemoteException;
    public abstract CyberzoneDef getCyberzoneDefHolder()
    throws RemoteException;
    public abstract void setLcaHolder(Lca arg1)
    throws RemoteException;
    public abstract void setCyberzoneDefHolder(CyberzoneDef arg1)
    throws RemoteException;
    The error it is throwing is:
    ERROR: Error from ejbc: In EJB LcaCyberzoneAssoc, lcaHolder is declared as oracle.toplink.indirection.ValueHolderInterface in the
    pk class, but the corresponding getLcaHolder() method in the bean class returns com.qwest.danconfig.server.ejb.entity.Lca. These t
    ypes must match.
    Can you please help how to fix this or what is the correct way of doing it.
    Second question is, is there any document which explains migrating toplink from EJB1.1 to EJB2.0?
    Thanks

    The EJB 2.0 spec does not really allow relationships in the primary key class. You may be able to get it to work by using the EJB classes, not ValueHolderInterface in primary key class.
    Otherwise you will need to double map the foreign key fields as direct fields to be compliant with the spec. You can still have the one-to-one mappings but your model will need to keep both in synch and mark the one-to-one mappings as read-only.

  • Deployment Tool Problem (J2EE -Composite primary Key Class)

    Hi !!
    e.g. I have an entiybean which has composite primary key class. So while deploying in J2EE tool u need to specify the Primary key class and the primary key field. well in case of a composite primary key class(if u have more than one field)...how do u declare all the fields for primary key class....
    if u r not getting me please tell me... See in J2EE deployment tool there is on section called Entity..in that see the Primary Key class (there u specify the Primary key class) and the Primary Key Field Name (the field name) Here u can just give only one Field name..if you have mulitple fields, then where you will specify... Please let me know..
    if anybody wants the code I will give the code...Please try to help..(how to deploy this kind of entity bean in J2EE deployment tool)
    -Bhumika

    Hi Bhumika,
    in case you have more than one field you need to write a Primary key class where the fields you want to be the key are member variables.
    your p.key class could look like this (it has to implement hash() and equals() ):
    public class PersonPK implements java.io.Serializable
    public int person_ID;
    public PersonPK()
    public PersonPK(int aPersonId)
    person_ID = aPersonId;
    public int hashCode()
    return person_ID;
    public boolean equals(Object ob)
    if (ob == this) return true;
    if (!(ob instanceof PersonPK)) return false;
    PersonPK other = (PersonPK) ob;
    if (person_ID != other.person_ID) return false;
    return true;
    -Hope this helps a bit,
    Anke

  • Why do we need a primary key class?

    i found a sample ejb, which contains a class only used to store the primary key. is it necessary? why? i guess it's for security issue, anybody can help me to clarify? thanks in advance!

    A primary key class is used next to an entity bean. It's used to represent the primary key of the table on which the entity bean is mapped.
    When the primary key of the table is only one column, you don't need to implement a primary key class. You can then define java.lang.Integer or java.lang.String or another build in Java object in you deployment descriptor.

  • Why in primary key class overrided in EJB?

    in EJB ... why in primary key class Object's Equals() and HashCode() method's were overridden ??

    please see the other question.. sorry for inconvinance..

  • Do I need to Create Primary Key Class for Entity beans with Local interface

    Do I need to Create Primary Key Class for Entity beans with Local interface?
    I have created my entity bean with the wizard in Sun One Studio and it does not create a primary key class for you.
    I thought that the primary key class was required. My key is made up of only one field.
    Anyone know the answer.
    Jim

    u dont need to create a primary key class for a entity bean.if ur table's primary key feild(int ,float) is a built in or primitive data type,then u dont need one.But if ur table has a primary key field which is non primitive (for example StudentID,ItemID etc)then u have to create a primary key class.
    hope this helps :-)

  • Primary Key Class Indicator mapping

    Hi
    We are using a Class Inidcator Field as described within Toplink documentation.
    We have encountered a problem, relating to the Class Indicator field not being populated within the Object within the cache,
    For example, the creation of one of our indictated objects successfully inserts the relevant class indicator value in the database, but the Object in the cache does not have the value set. This casues issues when attempting to identify the object in the cache.
    When re-reading the documentation at http://www.oracle.com/technology/products/ias/toplink/doc/1013/main/_html/descun007.htm#sthref2899 I noted the following line:
    "If the indicator field is part of the primary key, define a write-only transformation mapping for the indicator field (see Chapter 48, "Configuring a Relational Transformation Mapping"). "
    However following the documentaion trail, to http://www.oracle.com/technology/products/ias/toplink/doc/1013/main/_html/relmapun013.htm#CHDDBJJJ there is a statement:
    "Use transformation mappings only when mapping multiple fields into a single attribute. Because of the complexity of transformation mappings, it is often easier to perform the transformation with a converter or getter and setter methods of a direct-to-field mapping. See Chapter 38, "Configuring a Relational Direct-to-Field Mapping" for more information."
    Is there any definitive answer to correctly use a Class Indicator on a Primary Key field.
    Many Thanks
    Marc

    Hi,
    I'm still really struggling to find the correct way of implementing the mapping, as described within the documentation.
    As per the amended documentation quoted above, we are using a Primary Key field as the indentifier of a Class Indicator Mapping, and should therefore implement a "Read-Only Transformation Mapping for the indicator field".
    The explanation of how to implement Transformation Mappings in section 33-15,
    stipluates that both the "attribute transformer" - reading from the database,
    and the "field transformer" must be specified. By default, this would appear to
    be describing a read and write transformational mapping. Please correct me, if
    I am wrong.
    Therefore, we have currently found no method of implementing a "Read Only"
    transformational mapping for a Class Indicator Mapping.
    Any assistance in advising of the method of implementing this, would be greatly appreciated.
    Regards
    Marc

  • Entity bean with another class as primary key generator class

    Hi All,
    I have a CMP entity bean in which I generate the primary key using my own class know as unique id generator.
    I use it in ejbCreate method in the following manner
    public Long ejbCreate(HospitalData hospitalData) throws CreateException{
              Long myid = new Long(UniqueIdGenerator.getId());
              System.out.println("My id generated ====== "+myid);
              this.hospitalid = myid;
              System.out.println("My id generated ====== "+this.hospitalid);
              System.out.println("Came in ejbCreate method of HospitalEJB");
              this.hospitalname = hospitalData.getHospitalname();          
              return null;
    Can you tell me how I map this primary key in my ejb-jar.xml and jbosscmp-jdbc.xml.
    Anyhelp would be appreciated.
    Thanks
    Sameer

    "Bhamu" <[email protected]> wrote in message
    news:9keuo4$[email protected]..
    I am trying to develop an entity bean attached to a key which have a
    composite key using Primary Key Class. When I use the findByPrimaryKey
    method of the bean it throws an exception as follows,I notice that you are using the reference CMP plugin.
    at com.netscape.server.ejb.SQLPersistenceManager.find(Unknown Source)I'm also willing to bet that you may have created your own primary key class
    with a single field, rather than using the fields type as a primitive
    primary key class. If you do this, then SQLPersistenceManager will break.
    It is badly written, and has some stupid assumptions. The one I remember
    the most is that if you only have one primary key field, then
    SQLPersistenceManager assumes you have used a primitive type such as
    java.lang.String or java.lang.Integer, to represent it, rather than creating
    your own <Enity>Pk.java file.
    SQLPersistenceManager works for toy examples, but in general I would say it
    is broken and unusable. Either use BMP, or splash out the money for Coco
    Base from Thought Inc. Currently the only CMP plugin for iPlanet App server,
    other than the reference implementation, that I know of.

  • Primary key based on multiple fields which are of a custom class type

    Hello!
    I have the following two classes.
    public class Application
    protected String appName;
    protected Set moduleOptions = new HashSet(); //Set<ModuleOption>
    public class Option
    protected String name;
    protected Application application;
    Now, I need for Option to have a composite primary key based on both its
    fields. How do I do this?
    For starters, I just need a few hints on how this should be done in Kodo
    because I already have this thing working in JPOX and that solution does
    not map directly to Kodo. JPOX defines the OptionPK (primary key class)
    to contain field ApplicationPK, and not Application. But Kodo does not
    accept this because of a mismatch between fields in class and its primary
    key class. (Not implying that Kodo should accept the same kind of
    solution.)
    Btw, I'm evaluating version 3.2.3.
    Thanks in advance!

    Viktor,
    The typical Kodo pattern for doing this is to create a private field in
    Option for each primary key in Application, map those fields as
    primary-key (but not the field of type Application), and therefore put
    those fields in the OptionPK. These fields should then be mapped to the
    same columns as the Application reference. Then, set the primary key
    fields to the same value as they are in the related object.
    Kodo allows multiple fields to be mapped to the same column in the
    database, and throws an exception if your actions would set the column
    to different values. So, typically, this might look like:
    public class Application
    protected String appName; // I'm assuming that this is the PK
    protected Set moduleOptions = new HashSet ();
    public class Option
    protected String name; // pk
    protected Application application; // not pk
    private String applicationAppName; // pk
    public Option (String n, Application a)
    name = n;
    application = a;
    applicationAppName = a.appName;
    -Patrick
    Viktor Matic wrote:
    Hello!
    I have the following two classes.
    public class Application
    protected String appName;
    protected Set moduleOptions = new HashSet(); //Set<ModuleOption>
    public class Option
    protected String name;
    protected Application application;
    Now, I need for Option to have a composite primary key based on both its
    fields. How do I do this?
    For starters, I just need a few hints on how this should be done in Kodo
    because I already have this thing working in JPOX and that solution does
    not map directly to Kodo. JPOX defines the OptionPK (primary key class)
    to contain field ApplicationPK, and not Application. But Kodo does not
    accept this because of a mismatch between fields in class and its primary
    key class. (Not implying that Kodo should accept the same kind of
    solution.)
    Btw, I'm evaluating version 3.2.3.
    Thanks in advance!

  • Error While Deploying A CMP Entity Bean With A Composite Primary Key

    Hello all,
    I have a problem deploying CMP Entity beans with composite primary keys. I have a CMP Entity Bean, which contains a composite primary key composed of two local stubs. If you know more about this please respond to my post on the EJB forum (subject: CMP Bean Local Stub as a Field of a Primary Key Class).
    In the mean time, can you please tell me what following error message means and how to resolve it? From what I understand it might be a problem with Sun ONE AS 7, but I would like to make sure it's not me doing something wrong.
    [05/Jan/2005:12:49:03] WARNING ( 1896):      Validation error in bean CustomerSubscription: The type of non-static field customer of the key class
    test.subscription.CustomerSubscriptionCMP_1530383317_JDOState$Oid must be primitive or must implement java.io.Serializable.
         Update the type of the key class field.
         Warning: All primary key columns in primary table CustomerSubscription of the bean corresponding to the generated class test.subscription.CustomerSubscriptionCMP_1530383317_JDOState must be mapped to key fields.
         Map the following primary key columns to key fields: CustomerSubscription.CustomerEmail,CustomerSubscription.SubscriptionType. If you already have fields mapped to these columns, verify that they are key fields.Is it enough that a primary key class be serializable or all fields have to implement Serializable or be a primitive?
    Please let me know if you need more information to answer my question.
    Thanks.
    Nikola

    Hi Nikola,
    There are several problems with your CMP bean.
    1. Fields of a Primary Key Class must be a subset of CMP fields, so yes, they must be either a primitive or a Serializable type.
    2. Sun Application Server does not support Primary Key fields of an arbitrary Serializable type (i.e. those that will be stored
    as BLOB in the database), but only primitives, Java wrappers, String, and Date/Time types.
    Do you try to use stubs instead of relationships or for some other reason?
    If it's the former - look at the CMR fields.
    If it's the latter, I suggest to store these fields as regular CMP fields and use some other value as the PK. If you prefer that
    the CMP container generates the PK values, use the Unknown
    PrimaryKey feature.
    Regards,
    -marina

  • Can I have more than one primary key ???????

    Hi
    Assuming an application has designed as CMP with findByPrimaryKey( ) method having more than one parameter.
    Example :- findByPrimarykey(String val1, String val2)
    Is it possible to have two parameters fot the finder methods instead using PrimaryKey class ?
    If yes, what are the changes required for following deployment descriptor element. ?
    1. <prim-key-class></prim-key-class>
    2. <primkey-field></primkey-field>
    Regards
    Edward.I

    If a primary key has more than one primary key fields; is a composite primary key, a primary key class is required.
    The parameter of the findByPrimaryKey() method is the primary key class.
    findByPrimaryKey(PrimaryKeyClass pkClass)
    Deepak

  • Deploying BMP Entity Bean with primary key calss

    Hi,
    I am using EJB 2.0 with and websphere studio 5.0 and database is sql server 2000.
    My BMP Entity bean has a primary key class.From my client I am invoking the Entity Bean by calling it's findbyprimarykey method.
    The home interface of my findbyprimarykey method returns a class of type Remote.But in the Entity Bean class,the return type is the primarykey class type.
    My problem is invoking this findbyprimarykey from the client to get the remote interface so that the other business methods of the entity bean can be called.
    The control goes into the ejbFindbyPrimaryKey but when it is returing from the Entity Bean class,it gives a remote exception (as the return type in Entity Bean class and Home interface are different for the findbyprimarykey method).
    I think that somewhere in the deployment decriptor in my websphere,i have to specify the primarykey class type,which i am missing out and hence getting the error.
    Please help me out with your advice and solution.
    Thanks
    Rahul Priyadarshi

    Hi,
    Sorry to disturb you again.
    Even my code is also almost the same....i am pasting the code below...Please go through it and let me know if I have made any mistake..
    EditVendorEntityBean.....(Bean Class)
    package code.beans.EditVendor;
    import code.beans.dataAccess.*;
    import javax.ejb.CreateException;
    import javax.ejb.RemoveException;
    import javax.ejb.EntityBean;
    import javax.ejb.EntityContext;
    import javax.ejb.EJBException;
    import javax.ejb.FinderException;
    import javax.ejb.ObjectNotFoundException;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import java.sql.*;
    import javax.sql.*;
    import java.util.*;
    * Bean implementation class for Enterprise Bean: EditVendorEntity
    public class EditVendorEntityBean implements javax.ejb.EntityBean {
         private static Hashtable dataSources = new Hashtable();
         private String username;
    private int Vendor_ID;
    private int Category_Id;
    private String Category_Name;
    private String Vendor_Name;
    private String Vendor_Address1;
    private String Vendor_Address2;
    private String Contact_Name;
    private String Home_Phone;
    private String Work_Phone;
    private String email;
    private String faxno;
    private String userloginname;
    private boolean dirtyFlag = false;
    private EntityContext context;
    private static final String DS_NAME = "jdbc/spiPOPS";
    Connection con = null;
    Statement stmt = null;
    PreparedStatement st = null;
    ResultSet res = null;
         //***********************Business Methods*********************
    // Begin of Busines Methods
    public void setData (String[] catname, String vendorname,String vendadd1,String vendadd2,String vendcontact,String venoff,String venres,String mailid,String venfax) {
              System.out.println("in setData where Vendor Id= "+ Vendor_ID);
                   boolean status=false;
                   boolean existing=false;
                   ArrayList cat=new ArrayList();
                   try
                        cat=getcategorylist(this.Vendor_ID);
                   catch(SQLException e)
                        System.out.println("Could not get category list");
                   System.out.println("Size of cat array -->" + cat.size() + " and string array size -->" + catname.length);
                   if(catname.length>0)
                        //Removing unwanted vendor categories for a particular vendor id
                        for(int i=0;i<cat.size();i++)
                                  existing=false;
                                  String tempdata=(String)cat.get(i);
                                  for(int j=0;j<catname.length;j++)
                                       if(tempdata.equals(catname[j]))
                                            existing=true;
                                  if(!existing)
                                       try
                                            delvencat(this.Vendor_ID,tempdata.trim());
                                       catch(SQLException e)
                                            System.out.println("Could not delete record in POPS_VENDOR_CATEGORY for -->" + tempdata);
                   //Adding new vendor categories for a particular vendor
                        try
                                  for(int i=0;i<catname.length;i++)
                                       status=false;
                                       String strcat=catname;
                                       status=checkcat(this.Vendor_ID,strcat.trim());
                                       if(!status)
                                            insertvencat(this.Vendor_ID,strcat.trim());
                        catch(SQLException e)
                                  System.out.println("Could not insert or select from POPS_VENDOR_CATEGORY table");
                   this.Vendor_Name          =vendorname;
              this.Vendor_Address1     =vendadd1;
              this.Vendor_Address2     =vendadd2;
              this.Contact_Name          =vendcontact;
              this.Work_Phone               =venoff;
              this.Home_Phone               =venres;
              this.email                    =mailid;
              this.faxno                    =venfax;
                   dirtyFlag = true;
                   System.out.println("Leaving set data method");
    public Vector getData() {
         Vector vctRec=new Vector();
         ArrayList arrdatas = new ArrayList();
         arrdatas.add(""+this.Vendor_ID);
         arrdatas.add(this.Vendor_Name);
         arrdatas.add(this.Vendor_Address1);
         arrdatas.add(this.Vendor_Address2);
         arrdatas.add(this.Contact_Name);
         arrdatas.add(this.Work_Phone);
         arrdatas.add(this.Home_Phone);
         arrdatas.add(this.email);
         arrdatas.add(this.faxno);
         vctRec.addElement(arrdatas);
         ArrayList cat=new ArrayList();
              try
              System.out.println("Calling getcategorylist from getdata with vendorid-->" + this.Vendor_ID);
              cat          = getcategorylist(this.Vendor_ID);
         catch(SQLException e)
                   System.out.println("Could not get datas for category list");
         vctRec.addElement(cat);
         ArrayList allcats=new ArrayList();
         try
                        allcats          = getallcategorylist();
              catch(SQLException e)
                        System.out.println("Could not get datas for category list");
         vctRec.addElement(allcats);
              dirtyFlag = false;
         System.out.println("Before return statement in getdata with vector size -->" + vctRec.size());
              return vctRec;
    // End of Business Methods
    //**************************Entity Bean Methods*******************************
         * ejbActivate
         public void ejbActivate() {
              Vendor_ID = Integer.parseInt((String)context.getPrimaryKey());
         System.out.println("Inside ejbActivate Vendor_ID-->"+ Vendor_ID);
         * ejbLoad
         public void ejbLoad() {
              System.out.println("Inside ejbLoad ********" );
    try {
    loadRow();
    }catch (Exception ex) {
              System.out.println("Failed in loadRow()");
    throw new EJBException("ejbLoad: " +
    ex.getMessage());
         * ejbPassivate
         public void ejbPassivate() {
         System.out.println("Inside ejbPassivate " );
    Vendor_ID = 0;
         * ejbRemove
         public void ejbRemove() throws javax.ejb.RemoveException {
              //Empty Method
         * ejbStore
         public void ejbStore() {
    System.out.println("Inside ejbStore " );
    try {
    storeRow();
    }catch (Exception ex) {
              System.out.println("Exception thrown in storeRow" + ex.getMessage());
    throw new EJBException("ejbLoad: " +
    ex.getMessage());
         * getEntityContext
         public javax.ejb.EntityContext getEntityContext() {
              return context;
         * setEntityContext
         public void setEntityContext(javax.ejb.EntityContext ctx) {
              System.out.println("Inside setEntityContext " );
    try{
         con = getConnection(DS_NAME);
         System.out.println("DB Connection Created!!");
    catch(Exception e){
    this.context = ctx;
         * unsetEntityContext
         public void unsetEntityContext() {
    System.out.println("Inside unsetEntityContext " );
    closeDbConnection(con, res, st);
    this.context = null;
         * ejbCreate
         //code.beans.EditVendor.EditVendorEntityKey
         public code.beans.EditVendor.EditVendorEntityKey ejbCreate(String vendorid)
              throws javax.ejb.CreateException {          
              return new EditVendorEntityKey(vendorid);
              //return null;
         * ejbPostCreate
         public void ejbPostCreate(String vendorid) throws javax.ejb.CreateException {
              //Empty
         * ejbFindByPrimaryKey
         //code.beans.EditVendor.EditVendorEntityKey
         public code.beans.EditVendor.EditVendorEntityKey ejbFindByPrimaryKey(
              code.beans.EditVendor.EditVendorEntityKey primaryKey)
              throws javax.ejb.FinderException {
    try {
    if(selectByPrimaryKey(Integer.parseInt(primaryKey.getVendorId()))) {
              System.out.println("Leaving the findbyprimarykey method from the entity bean");
         return primaryKey;
         //return null;
    }else {
         throw new ObjectNotFoundException
         ("Row for id " + primaryKey + " not found.");
    }catch (Exception ex) {
    throw new EJBException("EXCEPTION IN ejbFindByPrimaryKey :- " + ex.getMessage());
         /*********************** Database Utility Routines *************************/
    private boolean selectByPrimaryKey(int priKey)
    throws SQLException {
         System.out.println("inside selectByPrimaryKey for primary key " + priKey);
    String queryStr ="SELECT VENDOR_ID FROM POPS_VENDOR WHERE VENDOR_ID = " + priKey;
    System.out.println("in selectByPrimaryKey where queryString is: "+ queryStr);
              stmt = con.createStatement();
    ResultSet result = stmt.executeQuery(queryStr);
    if(!result.next()) {
    stmt.close();
         System.out.println("Did not find "+priKey);
    return false;
    else { //Found the primaryKey
    Vendor_ID = result.getInt("VENDOR_ID");
    stmt.close();
    return true;
    private void loadRow() throws SQLException {
              System.out.println("inside loadRow ...");
              stmt = con.createStatement();
              String queryStr = "SELECT VENDOR_NAME,VENDOR_ADDRESS1,VENDOR_ADDRESS2,CONTACT_NAME,HOME_PHONE,WORK_PHONE,EMAIL_ID,FAX_NO " +
                                  "FROM POPS_VENDOR WHERE VENDOR_ID=" + Vendor_ID;
              System.out.println("Inside loadRow()***********"+queryStr);
              ResultSet result = stmt.executeQuery(queryStr);
              ArrayList catadatas=new ArrayList();
         if(!result.next())
         throw new SQLException("No record for primary key" + Vendor_ID);
              this.Vendor_ID               =Vendor_ID;
                        this.Vendor_Name          =result.getString("VENDOR_NAME");
                        this.Vendor_Address1     =result.getString("VENDOR_ADDRESS1");
                        this.Vendor_Address2     =result.getString("VENDOR_ADDRESS2");
                        this.Contact_Name          =result.getString("CONTACT_NAME");
                        this.Home_Phone               =result.getString("HOME_PHONE");
                        this.Work_Phone               =result.getString("WORK_PHONE");
                        this.email                    =result.getString("EMAIL_ID");
                        this.faxno                    =result.getString("FAX_NO");
                             System.out.println("Leaving loadrow method with loaded datas for vendor -->" + Vendor_ID);
                             stmt.close();
    private ArrayList getcategorylist(int vendor) throws SQLException{
              String queryStr ="SELECT DISTINCT(VENDOR_CAT) FROM POPS_VENDOR_CATEGORY WHERE VENDOR_ID=" + vendor;
              System.out.println("Query for the cat list --> " + queryStr);
              stmt = con.createStatement();
              ResultSet result = stmt.executeQuery(queryStr);
              ArrayList catdatas=new ArrayList();
    try{
                   while(result.next())
                        catdatas.add(result.getString("VENDOR_CAT"));
              catch (SQLException e){
                   stmt.close();
                   System.out.println("Could not retrieve datas for Category list");
              stmt.close();
              System.out.println("size off array for cat -->" + catdatas.size() + " and datas ->" + catdatas);
              return catdatas;
         private ArrayList getallcategorylist() throws SQLException{
                   //String queryStr ="SELECT DISTINCT(VENDOR_CAT) FROM POPS_VENDOR_CATEGORY";
                   StringBuffer strquery=new StringBuffer(20);
                   strquery.append("SELECT DISTINCT(CATEGORY_NAME) FROM POPS_CATEGORY");
                   stmt = con.createStatement();
                   //ResultSet result = stmt.executeQuery(queryStr);
                   ResultSet result = stmt.executeQuery(strquery.toString());
                   ArrayList catdatas=new ArrayList();
                   try{
                        while(result.next())
                                  //catdatas.add(result.getString("VENDOR_CAT"));
                                  catdatas.add(result.getString("CATEGORY_NAME"));
                   catch (SQLException e){
                             stmt.close();
                             System.out.println("Could not retrieve datas for All Category list");
                   stmt.close();
                   return catdatas;
         private void delvencat(int vendor,String vencat) throws SQLException {
              int update=-1;
              stmt = con.createStatement();
              String queryStr ="DELETE FROM POPS_VENDOR_CATEGORY WHERE VENDOR_ID = " + vendor + " AND VENDOR_CAT = '" + vencat.toUpperCase() + "'";
              System.out.println("Delete query --> " + queryStr);
              update= stmt.executeUpdate(queryStr);
              if(update!=1)
                   System.out.println("Did not find data to delete");
              stmt.close();
         private void insertvencat(int vendor,String vencat) throws SQLException {
              int update=-1;
              String queryStr ="INSERT INTO POPS_VENDOR_CATEGORY(VENDOR_ID,VENDOR_CAT)" +
                                  " VALUES(" + vendor +",'" + vencat + "')";
              System.out.println("Insert query --> " + queryStr);
              stmt = con.createStatement();
              update=stmt.executeUpdate(queryStr);
              if(update!=1)
                   System.out.println("Could not insert records in the database");
              stmt.close();
         private boolean checkcat(int vendor,String catven) throws SQLException {
              boolean datastatus=false;
              String queryStr ="SELECT VENDOR_ID FROM POPS_VENDOR_CATEGORY WHERE VENDOR_ID = " + vendor + " AND VENDOR_CAT = '" + catven.toUpperCase() + "'";
              stmt = con.createStatement();
              ResultSet result = stmt.executeQuery(queryStr);
              datastatus=result.next();
              stmt.close();
              return datastatus;
    private void storeRow() throws SQLException {
                   System.out.println("Inside ejb store");
         if (!dirtyFlag) {
         System.out.println("Skipping the UPDATE because object is not dirty");
         return;
         CallableStatement cs=null;
    try{
                        cs = con.prepareCall("EXEC POPS_VENDOR_UPDATE " + this.Vendor_ID + ",'" + this.Vendor_Name + "','" + this.Vendor_Address1 + "','" + this.Vendor_Address2 + "','" + this.Contact_Name + "','" + this.Work_Phone + "','" + this.Home_Phone + "','" + this.email + "','" + this.faxno +"'");
                        System.out.println("\n\n SQL Statement : \n " + "EXEC POPS_VENDOR_UPDATE " + this.Vendor_ID + ",'" + this.Vendor_Name + "','" + this.Vendor_Address1 + "','" + this.Vendor_Address2 + "','" + this.Contact_Name + "','" + this.Work_Phone + "','" + this.Home_Phone + "','" + this.email + "','" + this.faxno +"'");
                        cs.executeUpdate();
              catch (SQLException e){
                        cs.close();
                        System.out.     println("\n\n Error in calling stored procedure POPS_INSERT_NEW_REQUEST \n\n"+ e.getMessage() + "\n\n");
              cs.close();
              dirtyFlag = false;
         private Connection getConnection(String dbName) throws SQLException
              String configuredDataSourceName = null;
              if (dbName == null) {
                   System.out.println("Attemp to get connection failed. The requested database name is null");
              DataSource dbSource = getDataSource(dbName);
              return dbSource.getConnection();
         private DataSource getDataSource(String dbName)
              // looking from cache;
              DataSource dbSource = (DataSource) dataSources.get(dbName);
              if (dbSource == null) { //we need to find it from JNDI
                   try {
                        Context ic = new InitialContext();
                        dbSource = (DataSource) ic.lookup(dbName);
                        dataSources.put(dbName, dbSource);
                   }catch (NamingException e){
              return dbSource;
         * User calls this function to safely close an connection
         * @param connt The connection a datasource
         * @param rs The resulSet inside this connection
         * @param statement The statement associate with this connection
         private void closeDbConnection(Connection cont,ResultSet rs,Statement statement)
              if (rs != null)
              try {
                        rs.close();
                   } catch (SQLException ignored) {
                        ignored.printStackTrace();
              if (statement != null)
                   try {
                        statement.close();
                   } catch (SQLException ignored) {
                        ignored.printStackTrace();
              if (cont != null)
                   try {
                        cont.close();
                   } catch (SQLException ignored) {
                        ignored.printStackTrace();
         } //closeDbConnection
    EditVendorEntity (Remote Interface)
    package code.beans.EditVendor;
    import javax.ejb.EJBObject;
    import java.rmi.RemoteException;
    import java.util.*;
    * Remote interface for Enterprise Bean: EditVendorEntity
    public interface EditVendorEntity extends javax.ejb.EJBObject {
         public void setData (String[] catname, String vendorname,String vendadd1,String vendadd2,String vendcontact,String venoff,String venres,String mailid,String venfax)
                   throws RemoteException;
    public Vector getData() throws RemoteException;
    EditVendorEntityHome (Home Interface)
    package code.beans.EditVendor;
    import java.rmi.RemoteException;
    import javax.ejb.CreateException;
    import javax.ejb.FinderException;
    import javax.ejb.DuplicateKeyException;
    import javax.ejb.EJBHome;
    import java.util.*;
    * Home interface for Enterprise Bean: EditVendorEntity
    public interface EditVendorEntityHome extends javax.ejb.EJBHome {
         * Creates an instance from a key for Entity Bean: EditVendorEntity
         public code.beans.EditVendor.EditVendorEntity create(String vendorid)
              throws javax.ejb.CreateException, java.rmi.RemoteException;
         * Finds an instance using a key for Entity Bean: EditVendorEntity
         public code.beans.EditVendor.EditVendorEntity findByPrimaryKey(
              code.beans.EditVendor.EditVendorEntityKey Vendor_ID)
              throws javax.ejb.FinderException, java.rmi.RemoteException;
    EditVendorEntityKey (Primary Key Class)
    package code.beans.EditVendor;
    * Key class for Entity Bean: EditVendorEntity
    public class EditVendorEntityKey implements java.io.Serializable {
         static final long serialVersionUID = 3206093459760846163L;
         public String primkey;
         * Creates an empty key for Entity Bean: EditVendorEntity
         public EditVendorEntityKey() {  }
         public EditVendorEntityKey(String primarykey) {     
              this.primkey=primarykey;
         public String getVendorId() {
    return primkey;
         * Returns true if both keys are equal.
         public boolean equals(java.lang.Object otherKey) {
              if (otherKey instanceof code.beans.EditVendor.EditVendorEntityKey) {
                   code.beans.EditVendor.EditVendorEntityKey o =
                        (code.beans.EditVendor.EditVendorEntityKey) otherKey;
                   return (primkey.equals(otherKey));
              return false;
         * Returns the hash code for the key.
         public int hashCode() {
              return (primkey.hashCode());
    Please go through and give me your comments and solution...
    Thanks in advance
    Rahul

Maybe you are looking for