Using Composite keys in Entity Beans

Hi, I am trying to develop a test application with two entity beans, (1) OrderBean (key is a string called order_no) and (2) LineBean (key is order_no and an integer line_no) using CMP 2.0. Relationship between OrderBean to LineBean is 1 to many. I created a primary key class for LineBean called, LinePK with both order_no and line_no as the public members. My home interface for LineBean has the following three finder methods:
public java.lang.Object findByPrimaryKey(LinePK lkey);
public Collection findByOrder(String order_no);
public Collection findByProduct(String product_id);
I could provide sql for the OrderBean which has only one field(order_no) as primary key, but I don't know how to code appropriate SQL for the finder methods of LineBean involving a user defined primary key class (in my case LinePK with order_no and line_no). I am trying to deploy this application in J2EE RI server, but getting deployment errors saying invalid return types for the finder methods. In the deploytool I provided the primary key class for LineBean as java.lang.Object with no primary key field name. Any help in this matter with sample sql code is greatly appreciated. Thanks !!!

Some things to consider:
- Your findByPrimaryKey in the Remote interface needs to have the remote interface as return type
- The implementation of the finder needs to have your primary key class as return type
- If you're using CMP 2.0, you need to specify the search criteria as EJB QL
Using CMP 2.0, you don't code findByPrimaryKey at all, all you need is the EJB QL for findByOrder/findByProduct in the deployment descriptor. The EJB QL for findByOrder would look like:
select Object o from Line where o.order_no = ?1If you use BMP, you would code the findByPrimaryKey implementation like this:
public LinePK ejbFindByPrimaryKey(LinePK pk) throws FinderException {
  String sql = "select order_no from line_table where line_no=? and order_no=?";
  InitialContext ic = new InitialContext();
  Object obj = ic.lookup("datasourcename");
  DataSource ds = (DataSource)PortableRemoteObject.narrow(obj, DataSource.class);
  Connection conn = ds.getConnection();
  try {
    PreparedStatement stmt = conn.prepareStatement(sql);
    try {
      stmt.setInteger(1, pk.line_no);
      stmt.setInteger(2, pk.order_no);
      ResultSet rs = stmt.executeQuery();
      if (!rs.next())
        throw new ObjectNotFoundException("not found: " + order_no + "." + line_no);
      return pk;
    finally {
      stmt.close();
  finally {
    conn.close();

Similar Messages

  • Compund primary key in entity bean

    hi,
    can somebody please explain how to use the compound primary key in entity beans? i have got a database table, the key of which consists of three fields, which I assign as PK when setting up the entity bean. In turn I get a compoundPK class, but without get/set-methods - is it necessary to write own get/set-methods within this class?
    In the bean class itself I get a compundPK-create() method - but what is the use of it? actually, in my findByPK-method I need the PK already.
    Hints appreciated - btw, help.sap.com is not very helpful in this case...
    regards, matthias

    WebLogic Server supports mapping a cmr field to the primary key.

  • Using CMR field as Primary Key in Entity Bean

    Hi, all!
    Can somebody tell me, is it possible to use CMR field as Primary Key field in Entity Bean?
    Thanks

    WebLogic Server supports mapping a cmr field to the primary key.

  • Problem with foreign key in entity bean in WSED..Plzzzzz help!!!!!

    hi all,
    m very new to ejb...m crerating container managed entity bean in wsed..The steps I have followed r as follows,
    i) created 2 tables in database,one is PARENT with fields ID(Primary Key) and NAME and another is CHILD with fields ID1(Foreign Key) and NAME.
    ii)created 2 entity beans... 1st is parent with fields id(key field) and name(promote getter & setter methods to local interface)...2nd is child
    (choosed parent as bean super type) with fields id1 (promote getter & setter methods to local interface) and name (promote getter & setter methods to local interface)...
    iii)Generated EJB to RDB mapping(choosed crreate new backend folder->meet in the middle->use existing connection->choosed the tables parent & child in the database->match by name->finish)
    now m getting an error in Map.mapxmi--->"The table PARENT does not have a discriminator column"...and a warning--->"A primary key does not exist for table: CHILD in file: platform:/resource/NewFK/ejbModule/META-INF/backends/DB2UDBNT_V8_1/Map.mapxmi.     Map.mapxmi     NewFK/ejbModule/META-INF/backends/DB2UDBNT_V8_1     L/NewFK/ejbModule/META-INF/backends/DB2UDBNT_V8_1/Map.mapxmi"

    Hi Sandra,
    Many thanks for your response and providing time of yours.
    Now, I have done exactly the same thing, but still it is the same.
    I have created two new tables as below:
    ZAAVREF (Check table)
    MANDT (PK)
    COUNTRY (PK) Domain:ZAACOUNT (CHAR 10)
    ZAAV1 (Foreign key table)
    MANDT (PK)
    COUNTRY (PK) Domain:ZAACOUNT (CHAR 10)
    Then I have created FK on country of foreign key table ZAAV1 and then SE16 (for table ZAAVREF)->Create Entries-> Entered values for Country only->Save....Records entered with valid Country values.
    After that SE16 (for table ZAAV1)->Create Entries-->Entered an Invalid country->Save->Still the record entered to the Database successfully....
    Could you please let me know where I am going wrong.
    I am using SAP R/3 4.7 and creating tables using Tools->ABAP Workbench->Development->ABAP dictionary

  • Primary key in Entity beans

    Hi
    If my database doesn't have primary key, then how can I define ejbFindByPrimarykey
    method in Entity Beans. ? or in that case can't I use Entity beans. ?
    Pls clear my doubt.
    Thanks in advance

    Ashish,
    If my database doesn't have primary key, then how can I defineejbFindByPrimarykey
    method in Entity Beans. ? or in that case can't I use Entity beans. ?An entity bean instance needs to be uniquely identifiable. That doesn't
    necessarily mean that you have a PK in the database, but those two things do
    usually go together.
    Peace,
    Cameron Purdy
    Tangosol, Inc.
    Clustering Weblogic? You're either using Coherence, or you should be!
    Download a Tangosol Coherence eval today at http://www.tangosol.com/
    "Ashish Mangla" <[email protected]> wrote in message
    news:3cf5b304$[email protected]..
    >

  • Primary keys in entity beans

    I am creating an assignment for an EJB class that I am teaching. The assignment will ask students to create an entity bean to represent messages posted to an internet bulletin board. The fields in the entity bean are ID number, topic, user name, date, and the message. This bean will use container-managed persistence.
    The ID number of each message will be used for the primary key.
    The client will present the user with a simple menu (at the DOS prompt) with options to list all messages, search for messages, add messages, etc.
    When a new message is added, I don't want the user to have to enter a unique ID - it should be generated in the code somewhere.
    What I'm looking for is the absolute simplest way to get an ID for each new message. (I'm planning a series of assignments, each getting more complex, and this is the simplest one).
    I was thinking of having the client get a list of all the messages, make a list of all the IDs used, find the largest ID, and add 1.
    Can anyone suggest any other techniques? Thanks!
    -J

    Two approaches:
    you could initialize the db with one row and use some (any) number as the primary key
    then when adding a new row, access the last row in the db to get it's primary key and add 1 to it.
    You could also use date+time as a string, and assuming no one adds messages at the exact date+time, then it will work.
    To work around the problem of having two messages with identical date+time (assuming lots of messages coming through), you can catch the DB exception and resubmit the entry with an updated date+time. With very heavy traffic this will eventually fail. But for what you are doing it should work fine.
    Finally, you should not run into the identical problem unless you are using asynchronous message beans. I doubt you are, so the EJB container will handle it I suspect.

  • Using Identity Field in Entity Bean

    hi.....
    i am using Orion 2.0 with SQL Server 2000(professional) on Windows 2k...
    i got database with 10 tables...
    each table got an identity field where i am getting new value by database whenever i enter some data....
    now i don't have any access with the indentity field as it is totally managed by Database.....
    whenever i tried to set in ejb-jar.xml the column name,...while intestion ..it is giving me insert error as i don't have any access to that field( indentity field)
    and if i don't mention primary key...as that field....there is error for deployment...saying that no primary key defined........or primary key is nullll.....
    and i need to use that indentity field....else i need to manage all the other insertion in BMP which i don't want to do...
    Pls help me asap
    THanks
    Aniruddha Navare
    [email protected]

    EJB doesn't support identity field. EJB expects you set primary key values explicitly. There is a well known pattern that makes use of a session bean to generate entity bean primary key. Your best option is to use BMP or give up auto increment identity fields.

  • Using JODA Date in Entity Bean

    We are planning to use JODA open source in our project which is actually a replacement for Java Calendar and Date. Like to know how can we map the JODA Datetime to date columns in the table. Refer the link http://edocs.bea.com/wls/docs60/ejb/cmp.html for the supported data types. Is there any server specific extension available to support new data types.
    If not, we should still use util.Date in the entity bean but expose as DateTime outside. We'll do the conversion between util.Date and DateTime in the entity bean since we don't want to expose java.util.Date outside teh entity bean.
    But this restriction will fail for finder queries implemented through EJB QL unless the servic emethid calling the finder do the conversion to util.Date before calling. Is there a clean way to use JODA DateTime in Entity Bean

    EJB doesn't support identity field. EJB expects you set primary key values explicitly. There is a well known pattern that makes use of a session bean to generate entity bean primary key. Your best option is to use BMP or give up auto increment identity fields.

  • Use same transaction in entity-bean and Datasource

    Hello
    I've got following problem. In my stateless container managed transaction Sessionbean i do some inserts and update on my container managed entity bean. In the same transaction I have to read some informations on the database. Some of those informations are already set by the entity bean, but not yet commited. Now I want to read them through a javax.sql.DataSource. But this Datasource doesn't use the same transaction as the session bean.
    Question: Is it possible to let a Datasoucre use the same Transaction as Sessionbean?
    (i work with WSAD 4.0.3)
    Thanks

    Hi,
    You would have to check that you are using an XADataSource instance, instead of a 'regular' DataSource instance (which will not adopt the transaction started by the application server). In particular, the JNDI lookup name of the DataSource should actually point to an instance of XADataSource; a special type for container transactions.
    The administration/deployment tools of the WS will allow you to do that, under Resource Factories or DataSources somewhere.
    Both types look the same towards your application code, so your session bean is probably fine the way it is and does not need rewriting. It is merely in the setup of the WS server that the difference lies.
    Best,
    Guy
    http://www.atomikos.com

  • Retrieving auto inc primary key from entity bean (MySQL DB)

    Hello,
    I searched the forum intensively, but did not find an answer for the following problem.
    I've set up an MySQL database "Location" with two fields (ID, Description), ID is my primary key and I've added the AUTO_INCREMENT flag to this field. This works fine, i can add a row in the table with my entity bean "Location" from my session bean :
    Location l = new Location();
    l.setDescription("at home");
    em.persist(l);
    and even when I ask this location back from the DB, there is no problem :
    Location l = em.find(Location.class,1);
    return l.getDescription();
    The rows in the table increment nicely. The problem however is, that you don't allways know the ID. So I would like to do the following from my session bean:
    Location l = new Location();
    l.setDescription("at home");
    em.persist(l);
    int id = l.getId();
    the getID method allways returns a null object. The row is added in the DB, but the auto incremented ID is not returned to the entity bean!
    I know I could solve this by generating the ID's myself, but one of the strengths of autoincrement should be not to have to do this, no?
    If anyone has a clue how to solve this issue, I would very much appreciate it !
    Michiel
    Edited by: Michiel82 on Dec 6, 2007 6:01 AM

    No reactions so far ... this is a work-around for the issue :
    I've created an additional table sequence with two fields: gen_key and gen_value. Then, in my Location entity bean I can add the following:
    @TableGenerator(
    name="locationGen",
    table="sequence",
    pkColumnName="gen_key",
    valueColumnName="gen_value",
    pkColumnValue="location",
    allocationSize=1
    @Id
    @GeneratedValue(strategy=GenerationType.TABLE,generator="locationGen")
    @Column(name = "id", nullable=false)
    private Short id;
    This generates the primary key in the bussiness logic, but I would like to get the autogenerated key from my MySQL database (see previous post). Is this perhaps not supported by EJB3.0?
    Michiel

  • Using JDO under BMP entity beans

    I have an entity bean that is a BMP which uses JDO under the hood. The Oc4J document says that "Bean-managed persistence entity beans manage the resource locking within the bean implementation themselves" in the advanced subject chapter. Ok can someone in oracle add an extra line eloborating on that statement ?
    I am stuck in trying to pass a test that can do concurrent modify of an entity bean. I had 2 or more threads trying to modify one single BMP entity bean object concurrently. The database vendor recognizes one bean had the lock and deny locks to any other beans. Who should block the call to the database until one thread releases the lock on the object ? The developer ? J2EE container ? Database ?
    J2EE tenet "Developers are shielded from concurrency and threading issues while implementing business logic" Does that still hold ??
    An object Person's salary value and his benefit information are tried to be modified at the same time by different external system(salary administrator, benefit's administrator). But I dont want the user to see the lock on the object error, but instead I require a pessimistic lock on the BMP. Why does Oc4J not support pessimistic concurrency option for BMP ?

    Kurien,
    If you wish to bring something to the attention of the "Oracle dev team", I suggest you try Oracle's "MetaLink" Web site:
    http://metalink.oracle.com
    It is the official Oracle support Web site.
    These forums are for the Oracle community. Oracle Corporation employees are not obliged to even visit these forums.
    By the way, I am not an Oracle employee.
    Good Luck,
    Avi.
    P.S. For your information, you may find Debu Panda's blogs of help:
    http://radio.weblogs.com/0135826/

  • Need a Tx aware datasource when using CMT with BMP entity beans?

    When using Containter-Managed Transactions with entity beans that have
              bean-managed persistence, do I need to use a transaction-aware datasource?
              Thanks,
              Ken Gertsen
              

    Hi ad13217 and thanks for reply.
    I'm sorry but my code is like this:
    javax.naming.Context ctx=new javax.naming.InitialContext();
    arguments was an error on copy, but it doesn't work.
    Thanks
    Fil

  • @ManyToMany using Composite Key

    I have searched this forum concerning this issue. While I see others with a similar question, I see very little on a possible solution. Here is my problem statement.
    Class 1: Document.java
    Class 2: Collection.java
    Class 3: CollectionType.java
    XRef Table: Document_Collection
    Relationships:
    A DocumentID may be inside many collections.
    A CollectionID may have many documents.
    The owner of the relationship is document.java.
    The collection table uses 3 fields for defining a Primary Key--Site, Name, and Date. The three fields are Strings.
    I am using a SEQUENCE table for generating the unique Ids for each of the primary keys, except the Collection Table. This table is using a CompositePK Class for the Primary Key for the Collection Table.
    Document.java:
    @ManyToMany(cascade={CascadeType.ALL})
    @JoinTable(name="DOCUMENT_COLLECTION",
                      joinColumns=@JoinColumn(name="DC_DOCUMENT_ID",           referencedColumnName="DOCUMENT_ID"),
           inverseJoinColumns={@JoinColumn(name="DC_COLLECTION_ID", referencedColumnName="SITE_ID"),
                                        @JoinColumn(name="DC_COLLECTION_ID", referencedColumnName="NAME"),
                  @JoinColumn(name="DC_COLLECTION_ID", referencedColumnName="GROUP_DATE")}
    public Set<Collection> getCollectionSet() {
              return collectionSet;
    }Collection.java
    @ManyToMany(mappedBy="collectionSet")
    public Set<Document> getDocumentSet() {
         return documentSet;
    }In the Collection Class it holds a reference to a Collection type.
    CollectionType.java
    @Id
    @TableGenerator(name="COLLECTION_TYPE_TBL_GEN",
                   table="SEQUENCE",
                   pkColumnName="SEQ_NAME",
                   valueColumnName="SEQ_COUNT",
                   pkColumnValue="COLLECTION_TYPE_SEQ")
    @GeneratedValue(strategy=GenerationType.TABLE,     generator="COLLECTION_TYPE_TBL_GEN")
    @Column(name="COLLECTION_TYPE_ID", nullable=false)
    public Long getCollectionTypeId() {
         return collectionTypeId;
    }My test application builds the relationship for all the tables, and then attempts to persist the information to the database. When I look at at the log files, I see no errors, but the data is not being populated in the database. When I look at the SEQUENCE Table, I see all entries in the table are being incremented correctly except the Collection_Type sequence--still set to 1. I surmised the Collection Set for the Document_Collection table is not being populated correctly.
    My intent is to let TopLink generate the PK, Ids for the objects. This appears to be happening for the one-to-one relationships but not for the ManyToMany relationships. When I build the relationships, I create the collection and CollectionType and add it to a set. This set is added to the Document class. Lastly, I call the persist method on the Entity Manager. The log file shows the sequence number is being generated except for the Collection_Type Sequence. This may not be the correct way, but I did not see the correct steps for accomplishing this operation.
    [#|2007-08-27T16:52:03.899-0500|FINE|sun-appserver-pe9.0|oracle.toplink.essentials.file:/C:/glassfish/domains/domain1/applications/j2ee-apps/MyProject/MyEJB_jar/-MYEJBPU.sql|_ThreadID=12;_ThreadName=httpWorkerThread-8080-0;ClassName=null;MethodName=null;_RequestID=22dc7e71-9cef-4824-920f-5b3a2464c1d9;|SELECT SEQ_COUNT FROM SEQUENCE WHERE SEQ_NAME = ?
         bind => [URGENCY_SEQ]|#]This is how I build the Document Entity.
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public Document addDocument(Document docVO) {
              entityManager.joinTransaction();
              Document doc = new Document();
              DataType dataType = getDataType(docVO.getDataType().getDescription());
              UrgencyIndicator urgency  = getUrgencyIndicator(docVO.getUrgencyIndicator().getCode());
              DocMetaData metadata = getDocMetadata(docVO.getDocMetadata().getStoragePath());
              WeaponsSystem weaponsSys = getWeaponsSystem(docVO.getWeaponsSystem().getCode());
              FileType fileType = getFileType(docVO.getFileType().getExtension());
              Date sqlDate = new Date(new java.util.Date().getTime());
              Set<Collection> collectSet = getDocumentCollection("Site", "Name", sqlDate.toString());
              doc.setUrgencyIndicator(urgency);
              doc.setDocMetadata(metadata);
              doc.setFileType(fileType);
              doc.setWeaponsSystem(weaponsSys);
              doc.setDataType(dataType);
              doc.setCollectionSet(collectSet);
              entityManager.persist(doc);
              return doc;
    }Any suggestions would be greatly appreciated.
    Russ

    Okay I figured out one of my problems. When you search using the EntityManager's find method, a null is returned should JPA not be able to find an entity. This led to not populating the Collection Type and Collection incorrectly....... Now all Sequence generators are working correctly....... However, I am still not storing information in the database. Grrrrrr

  • 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

  • HowTo: construct Composite key using other composite key?

    Hello. I don' undestand how is it possible to do.
    Please, see my code:
    @Entity
    @Table(name = "Person", schema = SCHEMA)
    public class Person {
         @Id
         @GeneratedValue
         @Column(name = "id")
         private int id;
         private String medialogyUid;
         private String firstName;
         private String lastName;
         private String patronymic;
         private String biography;
    @Entity
    @IdClass(Convocation.PK.class)
    @Table(name = "Convocation", schema = SCHEMA)
    public class Convocation {
         @Id
         private int number;
         @Id
         @ManyToOne(fetch=FetchType.EAGER, cascade={CascadeType.MERGE, CascadeType.REFRESH, CascadeType.PERSIST})
         private Institution institution;
         private Date beginDate;
         private Date endDate;
         public Convocation(){
         public Convocation(Institution inst, int number, Date beginDate, Date endDate){
              this.institution = inst;
              this.number = number;
              this.beginDate = beginDate;
              this.endDate = endDate;
         public static final class PK implements Serializable {
              public int number;
              public int institution;
              public PK(){
              /**@param number is convocation,number
               * @param institution is convocation.institution.id
              public PK(int number, int institution){
                   this.number = number;
                   this.institution = institution;
              @Override
              public boolean equals(Object o) {
                   if (!(o instanceof PK))
                        return false;
                   PK oPK = (PK)o;
                   return this.number == oPK.number && this.institution  == oPK.institution;
              @Override
              public int hashCode() {
                   return ((number == 0) ? 0 : new Integer(number).hashCode()) ^ ((institution == 0) ? 0 : new Integer(institution).hashCode());
    //And finally the last class:
    @Entity
    @IdClass(DeputyMandate.PK.class)
    @Table(name = "DeputyMandate", schema = SCHEMA)
    public class DeputyMandate {
         @Id
        @ManyToOne(fetch=FetchType.EAGER, cascade={CascadeType.MERGE, CascadeType.REFRESH, CascadeType.PERSIST})
         private Person person;
         @Id
         @ManyToOne(fetch=FetchType.EAGER, cascade={CascadeType.MERGE, CascadeType.REFRESH, CascadeType.PERSIST})
         private Convocation convocation;
         private Date dateIn;
         private Date dateOut;
         public static final class PK implements Serializable {
                   //don't know what to use @Embeddable or what?
        }I want DeputyMandate to use composite key. This composite key is based on Person with simple key +(int id)+ and Convocation PK.
    Please, tell me how can I make composite key DeputyMandate.PK using simple key from Person and composite key from Convocation.
    Edited by: Holod on 27.08.2008 15:52

    And
    CONSTRAINT FK_CONFIG_OPTION_ID FOREIGN KEY (CONFIG_ITEM_ID,CONFIG_OPTION_ID) REFERENCES PRODUCT_CONFIG_OPTION(CONFIG_ITEM_ID,CONFIG_OPTION_ID)
    ?

Maybe you are looking for

  • Mac Pro network freezes on wake from sleep

    This problem has been growing over the past few weeks. It involves symptoms similar to other postings, but as of yet I have not found a common answer. If my machine is running well and I reboot, boot times are slower than previous but not unreasonabl

  • WebDynpro : 500 Internal Server Error

    Hi All,         We are devloping WebDynpro Project with RFC Model, in that project we created two application's we are deploying that applicaton's into devlopment server, it was excuted successfully, now that same webdynpro project we are deploying t

  • .pdf in preview won't print

    For the past 2 days, I am having issues printing documents I am viewing in Preview.  When I press (command P) the File button highlights briefly, but then the print screen does not come up.  However, on occasion, it has worked.  I have all software u

  • What is maccmd and why does it want to make changes?

    Everytime I reboot my macbook pro I get this message. I always just hit cancel but I'm starting to wonder what it is.  I used finder to see what program it was and found nothing.  Then I googled it and searched this board and didn't find anything.  D

  • Image with Title/Description Hover on MouseOver

    Hello All, So currently I am having trouble getting this perfect. I have an image that populates dynamically, as well as Title, Description and Link to the details page. The problem is the hover is not centered to the image, and in IE it doesn't alwa