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

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

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

  • How to retrieve information from entity beans?

    Hi all!
    I have a problem while trying to get information from entity beans. Here it goes:
    There are two entity beans with 1:N relationship between them.
    A FacadeSB is used to find a single record in one entity bean, using the findbyPrimaryKey method.
    What is required now is to get information from the other entity bean matching the record found from the first entity bean.
    to become more clear, the db schema is like that:
    vehicle_table
    vehicleid (vehicle_pkey)
    name (type of vehicle i.e. car, bike, atv, etc)
    brand_table
    brandid (brand_pkey)
    name (brand name e.g. ferrari)
    vehicleid (foreign key to vehicle_table)
    a FacadeSB gets the vehicle_table info and passes them to a servlet generated dropdown.
    what is the best way to populate a brand dropdown based on the vehicle dropdown selection?
    thanx in advance
    I hope the problem definition is clear enough for you guys...

    thanx for the reply
    i'm ok with the finder methods you suggested. my main concern in whether to create another FacadeSB to access the brand EJB. I don't believe that's the way to go on i.e. creating a session bean for every EJB created. Shall i use the VehicleFacadeSB to access brand EJB as well?
    I can undestand that such an implementation would be a quick fix as well as not such a resources hungry hack but on the other hand, would it make any sense architecturally?
    any suggestions?
    Zac

  • How to impliment a auto increamenting  primary key feature in ADF ??

    How to implement an auto incrementing primary key feature in ADF ( With out using database Triggers)
    Edited by: Dinil Mithra on Apr 24, 2009 2:28 AM
    Edited by: Dinil Mithra on Apr 24, 2009 2:59 AM

    Dinil,
    Create a sequence in the database.
    Read section 4.11.5 of the Fusion Developer's Guide - which has sample code to get the next sequence value from Java without a database trigger.
    John

  • Dynamically fill primary key from a second table

    Hi,
    IDOC-JDBC
    during runtime, the primary_key of the table must be filled dynamically.
    something like,
    it should go to a table dyn_key and get the hightest value of the field there and add one to it and pass it to dyn_key
    any idea how do i do it?
    regards,
    nikhil.

    Hello Nikhil,
    You can use JDBC look up for retrieving the current Primary key value.....
    Regards
    Ashwin M

  • How to return Collection from from entity bean to servlet?

    hi
    is it possible to return Collection from entity bean (Which is returns form CMR field ) to servlet ?
    thanks

    SERVLET
    public class test extends HttpServlet {
       @EJB
       private LocalBean lookupBean;
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
      for(Item i : lookupBean.getMyCollection() )
              out.println(i.getItemName());
            out.close();
    }BEAN INTERFACE
    public interface BeanLocal {
        Collection<Item> getMyCollection();  
    }BEAN IMPLEMENTATION
    @Stateless()
    public class Bean implements BeanLocal {
        @PersistenceContext()  
        private EntityManager em;      
         public Collection<Item> getMyCollection() {
            return em.createQuery("SELECT i from ITEM i").getResultList();
        }    and if you create an instance of your servlet you'll have to reinitialize LocalBean
    @EJB(name="myejbref", beanInterface=BeanLocal.class)
    private BeanLocal lookupBean;
    private BeanLocal getLookupBean() {
    if(lookupBean == null) {
    try {
    InitialContext ic = new InitialContext();
    lookupBean = (BeanLocal) ic.lookup("java:comp/env/myejbref");
    catch(Exception e){
    System.out.println(e.getMessage());
    return lookupBean;
    }

  • Creating entity beans with auto numbered primary key

    I have two entity bean with a CMR between them. I am successfully creating the first one but when I try and create the child entity bean I get a NullPointerException.
    Now I think this is because the gernerated code tries to get the primary key of the created entity bean and this is not set as it is set using a auto number in the database (An oracle sequence and trigger).
    Is there anyway i can get round this problem?
    Thanks in advance,
    Adrian

    This is the auto generated code:
         public dmd.sync.ejbs.entity.AppliancePackInfoLocal create_Local(dmd.sync.dataobjects.dto.AppliancePackInfoDTO appliancePackInfoDTO, dmd.sync.ejbs.entity.AmppLocal amppLocal) throws javax.ejb.CreateException, java.rmi.RemoteException {
              BeanO beanO = null;
              dmd.sync.ejbs.entity.AppliancePackInfoLocal result = null;
              boolean createFailed = false;
              boolean preCreateFlag = false;
              try {
                   beanO = super.createBeanO();
                   dmd.sync.ejbs.entity.AppliancePackInfoBean bean = (dmd.sync.ejbs.entity.AppliancePackInfoBean) beanO.getEnterpriseBean();
                   preCreateFlag = super.preEjbCreate(beanO);
                   bean.ejbCreate(appliancePackInfoDTO, amppLocal);
                   Object ejsKey = keyFromBean(bean);
                   result = (dmd.sync.ejbs.entity.AppliancePackInfoLocal) super.postCreate_Local(beanO, ejsKey, true);
                   bean.ejbPostCreate(appliancePackInfoDTO, amppLocal);
                   super.afterPostCreate(beanO, ejsKey);
    It must be falling over on the last line as it calls the ejbPostCreate fine.

  • Retrieve data  from entity bean to struts and display in JSP

    I am integrating Struts+EJB3.0.
    Now i need to retrieve data stored in mysql database through entity bean to struts framework*(Action Form*).Then i need to display it in JSP page.(display using combo box).
    Please Any one give suggestions!!!!!
    Thanks in advance

    I got the solution.
    --Jagan.+                                                                                                                                                                                                                               

  • CMP with Auto-increment Primary Key problem

    I'm trying to set a column as IDENTITY in PointBase and have the app server utilize this in the CMP beans. I followed the instructions from the tutorial:
    - In the deployment descriptor, the primary key class is defined as a java.lang.Object. The primary key field is not specified.
    - In the home interface, the argument of the findByPrimaryKey method must be java.lang.Object.
    - In the entity bean class, the return type of the ejbCreate method must be a java.lang.Object.
    Below is (a fragment of) my deployment descriptor:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
    <ejb-jar>
    <display-name>CMPModule</display-name>
    <enterprise-beans>
    <entity>
    <display-name>DocState</display-name>
    <ejb-name>DocState</ejb-name>
    <home>com.sun.itstar.j2ee.projectdocmgt.ejb.DocStateHome</home>
    <remote>com.sun.itstar.j2ee.projectdocmgt.ejb.DocState</remote>
    <local-home>com.sun.itstar.j2ee.projectdocmgt.ejb.LocalDocStateHome</local-home>
    <local>com.sun.itstar.j2ee.projectdocmgt.ejb.LocalDocState</local>
    <ejb-class>com.sun.itstar.j2ee.projectdocmgt.ejb.DocStateBean</ejb-class>
    <persistence-type>Container</persistence-type>
    <prim-key-class>java.lang.Object</prim-key-class>
    <reentrant>False</reentrant>
    <abstract-schema-name>DocState</abstract-schema-name>
    <cmp-field>
    <field-name>name</field-name>
    </cmp-field>
    <cmp-field>
    <field-name>description</field-name>
    </cmp-field>
    <cmp-field>
    <field-name>color</field-name>
    </cmp-field>
    </entity>
    In the admin-serv/logs directory I get the follow message (bad place for the logs, took me a while to find where it was putting it!):
    [24/Sep/2002:16:33:57] WARNING ( 4165): Validation error in bean DocumentType: Warning: All primary key columns in primary table DOCUMENT_TYPE of the bean corresponding to the generated class com.sun.itstar.j2ee.projectdocmgt.ejb.DocumentTypeBean_387898907_JDOState must be mapped to key fields.
    Map the following primary key columns to key fields: DOCUMENT_TYPE.ID. If you already have fields mapped to these columns, verify that they are key fields.

    Great! This worked. Here are some clear steps:
    1. delete the field from the CMP
    2. delete any business methods that you might have for the field
    3. go to the properties of the bean, find the primary key property. Set the property to Unkown Primey Key Class (java.lang.Object)
    Now there is a bigger problem. CMR fields. In ejbPostCreate() the bean gets its own pk and looks up other related beans. Now that I have removed the accessor to the pk field (and the pk field from the bean), how do I lookup the relationships?
    I need some method that I can call from within ejbPostCreate() that will return the primary key...
    I tried adding the field back in but not as the primary key. That generated an exception that said you cannot do that. If the field is the pk it must be marked as the pk.
    Any ideas?

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

Maybe you are looking for

  • ASK FOR HELP OF BILL OF EXCHANGE

    Dear all. I require Bill of Exchange Document where it gives a clear view of Configuring the Same i have lot of doubts with regards please send the document my box add:jackleeivo at a rat hotmail.com Points will be given by way of thanks Regards latt

  • I don't know icloud user name&password to login iphone after update ios7

    I don't know icloud user name&password to login iphone after update ios7. I try to recovery apple i.d., but nothing. I called Thailand service support 001800 4412904. He advise me to goto http://expresslane.apple.com/, and send issue form to apple se

  • How to get Runtime for each statement in abap program

    Is there any tool which tells the runtime of each statement in our program..apart from sto5 and se30 Thanks in advance PRASANNA

  • Errors when installing VF0060 - Webcam Live Ultra

    When I am running the installaltion CD, at around 9% completion I get an error that says "Installation is unable to continue because of one or more unresolved issues. Please contact support services and quote "Error I-001". This is followed by the me

  • Can BAM extract data from Excel Sheet?

    Hi, Thanks for seeing my message. We have huge data in the form of Excel sheet with large number of regular updates every day. Can BAM read Excel sheet so I can make a dash board reflecting lot of KPI's to track? regards,