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.

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.

  • 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]..
    >

  • 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 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.

  • Primary key in Entity Objects. How?

    Hi!
    I'm using Jdeveloper 9.0.3.3. I have a table with primary keys: CliId and Id. I make an entity object and choose primary key option for Cliid and Id in the entity. Now i make an viewObject from the entity object. In the viewObject, there are 2 key attribute: Cliid and Id. Now i'm generating with Jdeveloper 9.0.3.3 a standard uix page and i want to update a record, but it doesn't works. I become a bc4j error message: 'begin insert into....'.
    In the UIX code i made the rowDef autocreate="true":
    <bc4j:viewObjectDef name="CnedViewUsage" rangeSize="1">
    <bc4j:rowDef autoCreate="true" "CurrentCnedViewUsage">
    <bc4j:propertyKey name="key">
    </bc4j:propertyKey>
    </bc4j:rowDef>
    </bc4j:viewObjectDef>
    so
    if the propertyKey can't catch bc4j rowkey form url, it makes a new row. There is the problem...why doesn't catch the the propertyKey the bc4j key form the url? If i check out CliId primary key from entity and key attribute from ViewObject, it begins to work.. But in the database they together are primray keys.. Has anyone an idea?
    Thanks: Gabz

    Does your ViewObject use more than one entity? If so, then the Key that you are using in the ViewObject probably contains the key attributes of each Entity. You can go to the attributes section of the ViewObject Wizard and click off any "Key" checkboxes for attributes that aren't a part of your "primary" Entity.
    Mark

  • 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

  • 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();

  • USE ROWID AS PRIMARY KEY OF ENTITY ON EJB3

    When we launch the Create Entities from Tables wizard, and create JPA (Java Persistence API) entities from existing database tables, if the table has no primary key and unique key field, you will get a warning. When you run, you will get the following information:
    Caused by: Exception [TOPLINK-7161] (Oracle TopLink Essentials - 2006.8 (Build 060829)): oracle.toplink.essentials.exceptions.ValidationException
    Exception Description: Entity class [class model.Test] has no primary key specified. It should define either an @Id, @EmbeddedId or an @IdClass.
    Actually, every row of oracle table has a ROWID field , I think it is a good “primary key field”. Add it into Entity Java bean file as following:
    @Id
    private ROWID rowid;
    And generate accessors, ok, run……
    GOOD, No problem.
    But when you insert a new row, got an exception:
    Exception [TOPLINK-4002] (Oracle TopLink Essentials - 2006.8 (Build 060829)): oracle.toplink.essentials.exceptions.DatabaseException
    Internal Exception: java.sql.SQLException: ORA-00928: missing SELECT keyword
    Error Code: 928
    Call:INSERT INTO TEST (ROWID, B, A) VALUES (?, ?, ?)
         bind => [null, 555, 555]
    Query:InsertObjectQuery(model.Test@40979b)
    555~~~, what happened?! Somebody builds a wrong SQL …
    Don’t worry! I know (…) where is the “bug”.
    Find out the class
    oracle.toplink.essentials.internal.expressions. SQLInsertStatement
    which is included in the toplink-essentials.jar,
    decompile… , fix…, compile, and jar it back.
    Fix
    if(field.getTable().equals(getTable()) || !field.hasTableName())
    to
    if((field.getTable().equals(getTable()) || !field.hasTableName()) && !field.getName().equalsIgnoreCase("ROWID"))
    OK, it is running well.
    I suggest ORACLE fix it into his next version. Do you think it is a good idea?

    Do you think it is a good idea? Not really, but that's just my two cents.

  • Define primary key in FormsGraph Bean

    Hi !
    I read that I need to declare a primary key for using MODIFY_ROW_DATA or REMOVE_DATA.
    The problem is that there is 4 columns in the primary key of my table.
    So, how can I declare this primary key in the FormsGraph Bean ?
    Thanks for your help.
    Sev

    Hi,
    because the BI Graph relational API doesn't support a 4th extra field for e.g. holding primary keys, the modify row data does a full object comparison, comparing - in your case the routine in localRelationalData.java compares the values of
    xxx
    v_week
    v_quantity
    with values found in the existing data object, which is held in memory. To be sure of what happens, please enable debugging on the Graph bean before performing the modification. The effect you see can have many reasons e.g. that the refresh of the screen doesn't work or that the implementation itself has a problem. The debug messages that get written to the JInitiator shows if there is a match found for the data you provided (message starts with "ModifyData(): ") . Also the output starting with "parseStringData()" is interesting.
    Note that the Java source code is shipped with the demos - just in case you want to have a look yourself
    Frank

  • Primary Key on Entity Object

    Hello
    I create an entity object based on a view manually (not via the wizard)BC$J. I choose a primary key to complete the operation. I created a UIX page which display 5 records at a time. It turned out that the Primary key a chose was not a primary key and the page displayed with an error indicating that there are duplicate matches. Does this mean that the BC4J is checking the entire table for duplication? In my Page, i was about to invoke the search page as the first page to force the user to enter a criteria which when entered will cause only one record to be retrieved. BC4J seems to be executing the query and checking for the duplication before even allowing the search page to appear. The Search page is the first page that appears in my application (managed to skip forcing the initial table to be rendered with rows)
    Is there a way to stop OC4J from executing and checking before i display the Search Page.
    Thanks
    Ammar

    BC4J do not check the entire table for duplication. We retrieve rows as requested by the client app and if a duplicate PK is found as rows are retrieved, we will throw an exception.
    Thanks.
    Sung

  • 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

  • How to persist an entity with Composite primary key

    Problem Statement:-
    Entity A have many to one relation with Entity C
    Entity B have many to one relation with Entity C
    Entity C have a composite primary key of (Entity A PK & Entity B PK)
    A --< C
    B --< C
    the entites are automatic generated by Dali tool
    @Entity
    public class C implements Serializable
         @EmbeddedId
         private C.PK pk;
         private int attribute;
         //Code
         @Embeddable
         public static class PK implements Serializable
              public int A_Id;
              public int B_Id;
              //Code
    @Entity
    public class A implements Serializable
         @Id
         private int AId;
         @OneToMany
         private Set<C> C_Collection;
         //Code
    @Entity
    public class B implements Serializable
         @Id
         private int BId;
         @OneToMany
         private Set<C> C_Collection;
         //Code
    i made a session Bean which add a new entity C
    Session
         A a = em.find(A.class, AId);
         B b = em.find(B.class, BId);
         C c = new C();
         C.PK pk = new C.PK();
         pk.AId(a.getID());
         pk.BId(b.getID());
         c.setPk(pk);
         c.setA(a);
         c.setB(b);
         c.setAttribute(12);
         em.persist(c);
    when running this code an exception is raised
    Exception [TOPLINK-4002] (Oracle TopLink Essentials - 2006.8 (Build 060830)): oracle.toplink.essentials.exceptions.DatabaseException
    Internal Exception: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Unknown column 'A_ID' in 'field list'Error Code: 1054
    Call:INSERT INTO C (attribute, Aid, A_ID, B_ID, Bid) VALUES (?, ?, ?, ?, ?)
         bind => [2, 6, 6, 1, 1]
    this is logic as Table "C" has only 3 coloumns only "attribute" , "Aid" , "Bid"
    but the mapping is different as it adds the composite PK attributes to the insert statement
    if there is a sample code or how to solve this issue it would be great

    Hello Juwen,
    The problem is you are registering an object, assigning it a null pk, and then commiting the uow/transaction. TopLink uses registered objects to keep track of changes you make inorder to persist those changes on commit. So the simple fix is to not commit the UnitOfWork - call release() on it instead.
    Another solution is to use the session copyObject api. The simple form that only takes an object will work similar to registering the object as it will copy all persistent attributes but it will leave the primary key null. You can also use this method to specify a copyPolicy to customize the process. Using this method will be a bit more efficient, since a UOW makes both a working copy and a back up copy of objects registered, inorder to keep track of changes. Using the copyObject api will only make a single copy.
    Best Regards,
    Chris

  • Ability to auto create a primary key column while creating an entity ?

    Product : oracle data modeler ( 3.0.0.665 32 bit version ) on windows XP Professional , : Target DB Oracle 11GR2
    I am new to Mozilla Rhino. Is it feasible to have a mechanism where in the primary key column name would be auto generated when the entity ( name ) is just created for the first time, and it has no columns defined yet . For e.g. one could create an entity named vendor , and after the table name is typed in, a column vendor identifier,of type numeric , is to be auto created. This mechanism should work even if the entity name changes, and the primary key is in format {tablename}_id , but it should not , if the primary key was manually set in later and is not in the expected format.

    I created this script (1) for adding an ID column (using a specific domain) to all supertype entities that do not already have an ID attribute, and a script (2) for adding primary key constraints to all ID attributes.
    - Marc de Oliveira
    Script 1:
    entities = model.getEntitySet().toArray();
    domain = model.getDesign().getDomainSet().getByName('Integer DIS Domain');
    for (var e = 0; e<entities.length;e++)
    entity = entities[e];
    if (entity.getHierarchicalParent()==null)
    attributes = entity.getAttributes().toArray(); // find existing attributes
    IDattribute = null;
    for (var a = 0; a<attributes.length; a++) // look for an ID attribute
    if (attributes[a].getName()=="ID") { IDattribute = attributes[a]; }
    if (IDattribute==null) // if an ID attribute was not found...
    IDattribute = entity.createAttribute(); // create a new ID attribute
    IDattribute.setName("ID");
    IDattribute.setDomain(domain);
    entity.moveToIndex(IDattribute,0); // move ID attribute to top
    Script 2:
    entities = model.getEntitySet().toArray();
    for (var e = 0; e<entities.length;e++)
    entity = entities[e];
    attributes = entity.getAttributes().toArray(); // find existing attributes
    IDattribute = null;
    for (var a = 0; a<attributes.length; a++) // look for an ID attribute
    if (attributes[a].getName()=="ID") { IDattribute = attributes[a];}
    if (IDattribute!=null) // if an ID attribute was found...
    key = entity.createCandidateKey(); // Create a key
    key.add(IDattribute); // Add the ID attribute to the key
    key.setPK(true); // Define the key as a primary key
    PKName = entity.getName().replace(" ","_")+"_PK";
    key.setName(PKName); // Define the key as a primary key
    entity.setPK(key); // workaround for bug...
    }

  • Primary keys in CMP

    Hello,
    I have 2 CMP having master and detailed relationship.
    1) BookingMasterBean
    2) BookingDetailsBean
    (having one to many relationship).
    This is to do with a new booking to be made for Squash halls in our application.
    The primary key in Master bean , as well as the details bean get generated by a triggers (on insert) in the database(oracle).
    I have a stateful session bean which handles the booking process( creating entities in both master and details). After create a master entity the key should of the master record should be used as one of CMP field value in the details bean.
    i.e., I need to retreive the generated key once ejbCreate has been executed and should be sent back to the Stateful session bean.
    Can anybody tell me how to do this?

    Whatever you have understood is exactly correct. I am passing a value object as a parameter in the ejbCreate method. The code looks as folows.
    CMP header bean:
    public Integer ejbCreate(BookingHeaderValueObject bookingHeader)
    throws CreateException
    setBookingId(new Integer(bookingHeader.getBookingId()));
    setBookingDate(bookingHeader.getBookingDate());
    setBookingSlot(bookingHeader.getBookingSlot());
    setMemberId(bookingHeader.getMemberId());
    setClubId(bookingHeader.getClubId());
    setHallNumber(bookingHeader.getHallNumber());
    setAccompaniedBy(bookingHeader.getAccompaniedBy());
    setAccompaniedType(bookingHeader.getAccompaniedType());
    setTotalCharges(bookingHeader.getTotalCharges());
    setBookingStatus('B');
    setArrivalStatus('N');
    setDateModified(new Date());
    return getBookingId();
    Session Bean code:
    public void bookSquashHall(BookingHeaderValueObject bookingHeader,
    ArrayList bookingDetails )
    throws RemoteException,
    CreateException, NamingException
    int bookingSerialNo = 0;
    BookingHeaderHome bookingHeaderHome = (BookingHeaderHome)
    getEntityHome("BookingHeaderBean");
    BookingDetailsHome bookingDetailsHome = (BookingDetailsHome)
    getEntityHome("BookingDetailsBean");
    BookingHeader bookingHeaderRemote = bookingHeaderHome.create(bookingHeader);
    if( bookingHeaderRemote != null)
    for( int index = 0 ; index < bookingDetails.size(); index++)
    BookingDetailsValueObject bookingDetailsObj = (BookingDetailsValueObject)
    bookingDetails.get(index);
    bookingDetailsObj.setBookingSlNo(bookingSerialNo+1);
    bookingDetailsObj.setBookingId(bookingHeaderRemote.getBookingId().intValue());
    BookingDetails bookingDetailsRemote = bookingDetailsHome.create(
    bookingDetailsObj);
    bookingSerialNo = bookingDetailsRemote.getBookingSlNo().intValue();
    The following are scripts used to create the table structures :
    create table booking_header (
    bh_bookingid number,
    bh_booking_date date not null,
    bh_booking_slot varchar2(11) not null,
    bh__memberid number not null,
    bh__clubid number not null,
    bh_hallno varchar2(7) not null,
    bh_accompanied_by varchar2(60),
    bh_accompanied_type varchar2(10),
    bh_totalcharges number(10,2) not null,
    bh_status char(1) not null,
    bh_arrived char(1) not null,
    bh_date_modified date not null,
    constraint booking_header_pk primary key(bh_bookingid),
    constraint booking_header_fk1 foreign key(bh__clubid) references club_details(cd_clubid),
    constraint booking_header_fk2 foreign key(bh__memberid) references member_details(md_memberid)
    create trigger booking_header_insert
    before insert on BOOKING_HEADER
    for each row
    declare
    newBookingId number;
    begin
    select nvl(max(BH_BOOKINGID)+1, 1) into newBookingId from BOOKING_HEADER;
    :new.BH_BOOKINGID := newBookingId;
    end;
    create table booking_details (
    bd_slno number,
    bd__bookingid number not null,
    bd_booking_date date not null,
    bd_booking_slot varchar2(11) not null,
    bd__memberid number not null,
    bd__clubid number not null,
    bd_hallfacility char(1) not null,
    bd__facilityid number,
    bd_charges number(10,2) not null,
    bd_status char(1) not null,
    bd_arrived char(1) not null,
    bd_date_modified date not null,
    constraint booking_details_pk primary key(bd_slno),
    constraint booking_details_fk1 foreign key(bd__bookingid) references booking_header(bh_bookingid),
    constraint booking_details_fk2 foreign key(bd__clubid) references club_details(cd_clubid),
    constraint booking_details_fk3 foreign key(bd__memberid) references member_details(md_memberid)
    create trigger booking_details_insert
    before insert on BOOKING_DETAILS
    for each row
    declare
    newSlNo number;
    begin
    select nvl(max(BD_SLNO)+1, 1) into newSlNo from BOOKING_DETAILS;
    :new.BD_SLNO := newSlNo;
    end;
    Should I be defining the ejb relationships in this case.?
    Also I saw in a search from google that we can implement ejbPostCreate to retrieve the primary key if generated by the container. Could I do something like that in order to get back the primary key.
    Is there any better approach for this. I am fairly new to the subject .

Maybe you are looking for

  • Is there a save function for online forms?

    Hi, I've created an online form which requests quite a lot of information from those who it is sent to.  Because of its size, I have made use of the skip logic rules to so that users can quickly skip sections that don't apply to them.  Notwithstandin

  • InDesign Trial Extension

    Hi - does anyone know if it is possible to get an extension on the 30 day free trial? I am in the process of purchasing a license but due to company purchase processes this will not be complete before my trial runs out (tomorrow). (I know I have the

  • Tried to make a ringtone, I messed up the song

    I tried to make a ringtone and now the song I as using will only play for 3 seconds. Even if I play it in the store, it will only play for 3 seconds. After I adjusted the start and stop time, it did not give me the short copy of that song. I have mes

  • Can you fix my ipod, even though i never bought it from your shop?

    Can you fix my ipod, even though i never bought it from youe store?

  • Log & Transfer Quits unexpectedly

    I transferred my AVCHD footage from an SD/HC card to a hard drive and, as usual, went to use Log and Transfer to import it into FCP, which then proceeds to "quit unexpectedly."  Haven't had this problem before.  Any help would be appreciated.  Thanks