JPA: Availability of generated keys

Hi
If I create an entity which has an auto-generated key and call the persist method of the entity manager, can I then assume that the key is immediately available in the entity or only after a subsequent call of the flush method?
In general, the synchronization with the datasource may be delayed by the application server until commit time of the associated transaction. But the immediate availability of auto-generated keys can be crucial in session beans with container-managed transactions if the corresponding creation methods want to make use of the keys.
Unfortunately, I couldn't find any definitive answer in the JPA specification.
Thanks for any help, Stephan

I must be missing something. I'm calling persist on my entity but i'm not getting a value for my primary key. Then when I go to put it in a relationship the whole thing dies. I even tried using flush and that didn't help either.
I'm essentially doing
beginTransaction();
EntityA a = new EntityA();
persist(a);
EntityB b = new EntityB();
b.setA(a);
persist(b);
commit();Is there some annotation I need so that the primary key is set on persist ?

Similar Messages

  • SSL Server: No available certificate or key.... exception

    Hi,
    I want to create a very simple SSL Server for testing purposes.
    I have searched google and these forums for an answer, but anything that I found did not help (will say below what I tried).
    Here is my code:
    import java.io.IOException;
    import javax.net.ssl.SSLServerSocket;
    import javax.net.ssl.SSLServerSocketFactory;
    public class Server {
         private int port = 25000;
         private SSLServerSocketFactory factory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
         public Server() {          
              try {
                   SSLServerSocket socket = (SSLServerSocket) factory.createServerSocket(port);
                   Echo echo = new Echo(socket);
                   Thread t = new Thread(echo);
                   t.start();
              } catch (IOException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              new Server();
    }and
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    import javax.net.ssl.SSLServerSocket;
    import javax.net.ssl.SSLSocket;
    public class Echo implements Runnable {
         SSLServerSocket socket;
         public Echo(SSLServerSocket socket) {
              this.socket = socket;
         @Override
         public void run() {
              try {
                   SSLSocket connectedSocket = (SSLSocket) socket.accept();
                   // creating the streams
                   InputStream inputstream = connectedSocket.getInputStream();
                InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
                BufferedReader in = new BufferedReader(inputstreamreader);
                OutputStream outputstream = connectedSocket.getOutputStream();
                OutputStreamWriter outputstreamwriter = new OutputStreamWriter(outputstream);
                BufferedWriter out = new BufferedWriter(outputstreamwriter);
                // echoing...
                String input = "";
                while (input.compareTo("abort") != 0) {
                     input = in.readLine();
                     System.out.println("Server received message: " + input);
                     out.write(input + " " + input);
                     out.flush();
              } catch (IOException e) {
                   e.printStackTrace();
    }When I run the code, I get
    javax.net.ssl.SSLException: No available certificate or key corresponds to the SSL cipher suites which are enabled.
         at com.sun.net.ssl.internal.ssl.SSLServerSocketImpl.checkEnabledSuites(Unknown Source)
         at com.sun.net.ssl.internal.ssl.SSLServerSocketImpl.accept(Unknown Source)
         at Echo.run(Echo.java:24)
    Line 24 in Echo.java is SSLSocket connectedSocket = (SSLSocket) socket.accept();
    I have created a keystore according to the JSSE documentation: http://java.sun.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#CreateKeystore
    I have tried relative and full pathnames for javax.net.ssl.keyStore, as well as copying the keystore right into the directory with the class-files
    I have tried to set javax.net.ssl.keyStore (and javax.net.ssl.keyStorePassword) via the command line's -D switch and via System.setProperty
    After all that failed, I even tried to import the generated public key into the server's keystore as well
    No matter what I did, I always get above exception upon calling accept().
    I am using Java 6 (Java(TM) SE Runtime Environment (build 1.6.0_17-b04)) on Windows 7 64 Bit
    Any help is appreciated.

    I have created a keystore according to the JSSE documentation: http://java.sun.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#CreateKeystore
    Are you sure you created a keystore with an RSA keypair, and not a DSA keypair?

  • JPA: Oracle Sequence Generator not up to date

    Hi,
    I'm using the JPA Oracle Sequence Generator in one of my JPA classes:
    @Entity
    @Table(name = "DACC_COST_TYPE")
    public class JPACostType implements Serializable {
    @SequenceGenerator(name = "CostTypeGenerator", sequenceName = "DACC_COST_TYPE_SEQ")
        @Column(name = "ID_COST_TYPE")
        @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CostTypeGenerator")
        private Integer idCostType;
    In order to persist a new object I perform the following code:
    @PersistenceContext
    private EntityManager em;
    JPACostType myJPA = new JPACostType();
    myJPA.setIdCostType = null;
    em.merge(myJPA);
    em.flush();
    Normally this works fine. But after deploying the app there sometimes happens an error:
    Caused by: javax.persistence.PersistenceException: SQLException while inserting entity {com.karmann.dacc.ejb.busilog.jpa.JPACostType(idCostType=4)}.
    at com.sap.engine.services.orpersistence.core.PersistenceContextImpl.flush(PersistenceContextImpl.java:278)
    at com.sap.engine.services.orpersistence.core.PersistenceContextImpl.beforeCompletion(PersistenceContextImpl.java:565)
    at com.sap.engine.services.orpersistence.entitymanager.EntityManagerImpl.beforeCompletion(EntityManagerImpl.java:410)
    at com.sap.engine.services.orpersistence.environment.AppJTAEnvironmentManager.beforeCompletion(AppJTAEnvironmentManager.java:197)
    at com.sap.engine.services.ts.jta.impl.TransactionImpl.commit(TransactionImpl.java:232)
    ... 52 more
    Caused by: java.sql.SQLException: ORA-00001: unique constraint (AEMA.DACC_COST_TYPE_PK) violated
    Obviously JPA does not fetch the new key by accessing the Oracle sequence. This documents "next value = 5". Does JPA fetch the new key from its cache? Is there any possibility to avoid this?
    Thanks for each hint,
    Christoph

    Hello Christoph Schäfer  ,
    I am stuck with a similar issue. I was able to save mutiple entries and there has not been much change to my JPA. I added new entities and new sequences.
    Now, I get the error Caused by: javax.persistence.PersistenceException: java.sql.SQLException: ORA-02289: Sequence ist nicht vorhanden.
    I have checked the name of sequence and sequence next val on the DB. It works on DB but when i execute it from ejb, it gives me thsi error. Now, it gives the error for all previously working JPA entities.
    I have also provided allocationSize = 1 for all entities.
    Please let me know, possible cause/solution to this issue.
    thank you.
    Regards,
    Sharath

  • Getting generated keys inside Java

    Is there any way to get generated keys in Java running on CF
    server?
    I have some java code accessed from CF, I get a connection to
    the data source by name via
    "coldfusion.server.DataSourceService.getDatasource(datasourceName).getConnection()"
    call within java, which works. However if I try to do a
    connection.prepareStatement(sql,
    PreparedStatement.RETURN_GENERATED_KEYS) call or
    preparedStatement.getGeneratedKeyts() call I get a
    "java.lang.AbstractMethodError" exception like:
    java.lang.AbstractMethodError:
    coldfusion.server.j2ee.sql.JRunConnectionHandle.prepareStatement(Ljava/lang/String;I)Ljav a/sql/PreparedStatement;
    Which seems to indicate to me that CF does not implement
    getting generated keys via JDBC - is there another way or do I have
    to just give up and do a "select" after "insert"?
    Hope this made sense.
    Thanks,
    -HH
    P.S. In case this is usefull, CF MX7 with MSSQL2005 , JDK
    1.4

    Hichhiker wrote:
    > Is there any way to get generated keys in Java running
    on CF server?
    CF6/7 uses JDBC 2 so I don't think you can get it to work
    there. In CF 8
    it should work (if your database supports it).
    Jochem
    Jochem van Dieten
    Adobe Community Expert for ColdFusion

  • Generating key pair on PKCS#11token and save it there

    Hello,
    again i'm completely lost in this PKCS11 jungle.
    What i want to do:
    Generating key pair on crypto pkcs11 token and store it there.
    In the moment i've tried eg:
    sun.security.pkcs11.SunPKCS11 p = new sun.security.pkcs11.SunPKCS11(configName);
    Security.addProvider(p);
    Builder builder = KeyStore.Builder.newInstance("PKCS11", p, new KeyStore.CallbackHandlerProtection(new UserInputDialog(new JDialog(),"test","test")));
    KeyStore ks = builder.getKeyStore();
    ks.load(null,null);
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA", p);
    gen.initialize(1024);
    KeyPair kp = gen.generateKeyPair();
               Here access to token works. The callback PIN dialog comes up and i can login.
    But i'm not sure whether the key are generated on this PKCS11. And they are not stored there.
    How i can generate keys are stored there.
    (like with keytool -genkeys ). In keytool case a certificate is stored.
    ... every little hint, also to some documentation i've not seen, is very welcome ...
    Thank You !
    Regards
    Thomas
    .

    First, you need to get a KeyStore representation of the PKCS#11 token with code similar to this, I'm using NSS as the PKCS#11 token in this example:
    Provider nss = new sun.security.pkcs11.SunPKCS11(configFile);
    Security.insertProviderAt(nss, 1);  //you may not want it at highest priority
    KeyStore ks = KeyStore.getInstance("PKCS11", nss);
    ks.load(null, password);From the testing I've done in the past with various tokens, when you generate an asymmetric keypair (e.g. RSA like you are) specifying the PKCS11 provider, it creates it right on the token automatically and code like below is not needed.
    To store the key in the keystore, use code similar to this, I'm using NSS again and storing a symmetric key:
    KeyGenerator kg = KeyGenerator.getInstance("DESede",nss);
    SecretKey tripleDesKey = kg.generateKey();
    KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(tripleDesKey);
    ks.setEntry(randAlias, skEntry, new KeyStore.PasswordProtection(password));

  • Keychain not generating keys for email certificates

    In trying to set up email signing for two different machines I ran into a problem when adding email authentication certificates from Comodo.  After downloading the .p7s files each of the users double clicked the files, adding them to their key chains.  However, when they opened Mail there were no options for adding the lock(encrypt) and star(digitally sign) icons to their 'compose new message' windows.
    After a lot of screwing around, I discovered that the new certificates had been added, but just as regular certificates and never made it to the 'My certificates' section.  After some more comparisons I discovered that the private keys had not been generated automatically when the keys were added.  The solution was to send the origional files to a machine that was generating keys, add them to that machine's keychain and then export the certificates (this time with a .p12 extention) and re-import the keys back to the owners machines.
    That's a pain.  Anyone seen this before?  Have a better fix?
    Configs as follows
    Working configuration (generates keys)
    iMac 27" 3.4ghz Intel core i7
    Mac os 10.7.2
    keychain 5.0
    Broken configurations (not generating keys)
    Mac Mini 2.66 intell core duo
    Mac os 10.7.2
    keychain 5.0

    Hi Jack,
    Open Keychain Access in Utilities, use Keychain First Aid under the Keychain Menu item, then either check the Password under that item, change it, or delete it and start over.
    Resetting your keychain in Mac OS X...
    If Keychain First Aid finds an issue that it cannot repair, or if you do not know your keychain password, you may need to reset your keychain.
    http://support.apple.com/kb/TS1544

  • Support for Generated Keys in oracke jdbc drivers?

    Hi All,
    Anyone know when the Oracle Thin JDBC drivers are going to support generated keys?
    Regards,
    Lee

    Sure Justin,
    I should have made myself more clear. Sorry about that.
    I have a sequence for generating primary keys in a particular table, and a trigger to replace a null in my insert query with the nextval. That all works fine. I would like to use the DB-neutral means of getting a generated primary key...
    prepStmt = connection.prepareStatement(insertSQL, Statement.RETURN_GENERATED_KEYS);
    prepStmt.executeUpdate();
    ... and later ...
    ResultSet generatedKeyRS = prepStmt.getGeneratedKeys();
    ... etc.
    I am aware that I can get this information several other Oracle9i-specific ways, including using the sequence's .currval and creating a callable statement that returns the primary key column. However I would still like to use the nice, neat, vendor-neutral JDBCv3 way. Call me pedantic.
    Regards,
    Lee

  • Question about generate key press event to system. help plz.

    I am wondering if it is possible to write a java program to generate key press event(not receiving)to the local system so all the other program in the system receive those key press event also. Thanks.

    Hi,
    :. I don't know what exactly you intend to accomplish. But, I have used the following code in order to simulate keys pressing inside a Java application.
          /* - - - Simulates TAB (java.awt.Event)
          EventQueue evtq = Toolkit.getDefaultToolkit().getSystemEventQueue();
          evtq.postEvent( new KeyEvent(this, KeyEvent.KEY_PRESSED,
                          0, 0, KeyEvent.VK_TAB, KeyEvent.CHAR_UNDEFINED) );
          evtq.postEvent( new KeyEvent(this, KeyEvent.KEY_RELEASED,
                          0, 0, KeyEvent.VK_TAB, KeyEvent.CHAR_UNDEFINED) );
          /* - - - Simulates Shift+TAB (java.awt.Event)
          evtq.postEvent( new KeyEvent(this, KeyEvent.KEY_PRESSED, 0,
                          InputEvent.SHIFT_DOWN_MASK, KeyEvent.VK_TAB,
                          KeyEvent.CHAR_UNDEFINED) );
          evtq.postEvent( new KeyEvent(this, KeyEvent.KEY_RELEASED, 0,
                          InputEvent.SHIFT_DOWN_MASK, KeyEvent.VK_TAB,
                          KeyEvent.CHAR_UNDEFINED) );:. However, as far as I know to send keys to the whole OS you have to create a 'Hook' as described inside Win32API documentation. That's for Microsoft Windows naturaly.
    Cheers.
    Roque

  • Prioryly generated key problem.

    public String encrypt(String password){
    String algo = "DESede";
    Cipher cipher = Cipher.getInstance(algo);
    String s = null;
    Key key = (Key)com.sun.crypto.provider.DESedeKey@4f9655f1;
    cipher.init(Cipher.ENCRYPT_MODE, key);
         byte[] inputBytes = password.getBytes();
         s = cipher.doFinal(inputBytes);
    return s;
    public String decrypt(String password){
    String algo = "DESede";
    Cipher cipher = Cipher.getInstance(algo);
    String s = null;
    Key key = (Key)com.sun.crypto.provider.DESedeKey@4f9655f1;
    cipher.init(Cipher.DECRYPT_MODE, key);
         byte[] vas = cipher.doFinal(password);
         String s = new String(vas);
         return s;
    I got a problem with the above code the character @ in the object com.sun.crypto.provider.DESedeKey@4f9655f1 does not compile in java, but I need to use it because its my pre generated key that i wish to use in encryption and decryption function.
    Thanks for the help in advance.

    Wow. This one is...surreal. Let's see:
    As silk.m noted, what you're trying to do doesn't make any sense. You need to have the bytes of the Key in order to recreate it. Use generatedKey.getEncoded() to get the byte[] that describes the Key, and then look at how to use DESedeKeySpec and SecretKeyFactory to recreate the Key object.
    On top of that, you have other problems.
    You can't just use byte[] plaintext = s.getBytes(). The default String encoding is different on different platforms. You need to tell getBytes() which encoding you really want.
    You're attempting to return the output of doFinal() as a String. You can't - it's a byte[]. You can't just return "new String(doFinalBytes)", either - ciphertext IS NOT "String-able". You'll need to Base64 it first.
    It's also possible you'll be bitten by having a plaintext that isn't an integral number of blocks. I don't recall if the default DESede uses padding, or assumes NoPadding.
    You've got some fixing to do...
    Good luck,
    Grant

  • Generating Key for new installation

    Hi,
    I installing IDES , I am trying to generate key. the FYI steps i have involved
    goto SMSY>select other object>generate key==yes got the key
    When i entered the generated key from solution manager
    The system does not accepts.
    The error message read as<b>"HOST directory to central instance and system ID incorrect"
    Please help tell me basic requiremnts or procedures to follow.
    REGARDS,
    PAUL

    Hello Paul,
    Kindly follow the steps mentioned in the below link to generate the key...
    http://help.sap.com/saphelp_sm40/helpdata/en/45/51fbdbd4941803e10000000a1553f7/frameset.htm
    regards,
    Anand

  • Generate Key Events without pressing key???

    Hi,
    Is it possible to generate key events without pressing a key in swing???
    i dont know if the question is logical or not, but just i want to generate some display as if the key is pressed by the user
    Ashish

    assuming c represents a text field.
    This will type the character 'a' in the text field:
    c.dispatchEvent( new KeyEvent (c, KeyEvent.KEY_TYPED, 0, 0, KeyEvent.VK_UNDEFINED, 'a') );
    This will invoke Ctrl+F1, which will show the tool tip for the text field:
    c.dispatchEvent( new KeyEvent (c, KeyEvent.KEY_PRESSED, 0, KeyEvent.CTRL_MASK, KeyEvent.VK_F1) );

  • CF 9.0.2 and Oracle - On update returns error "Auto-generated keys were not requested..."

    We have a simple update statement to Oracle 11g Database. When running the statement the data is not getting updated and we are getting an error "Auto-generated keys were not requested, or the SQL was not a simple INSERT statement. ErrorCode=0 SQLState=HY000". We found this error by dumping the SQL to a file.
    But most other Update statements are working fine.
    Also, the same statment works for Oracle 10g and Coldfusion 9.0.0.
    Any idea if this is a problem with Coldfusion or Oracle? Is there any resolution.
    I found the CF 8 had a similar issue and was fixed in a hotfix (http://helpx.adobe.com/coldfusion/kb/error-auto-generated-keys-requested.html).

    Hi,
    Thanks. I compiled my code using JDeveloper 10.1.2, didn't dare to use the latest. It works in 10g apps server. When I deployed to 9ias apps server, those weird errors showed up. Unfornately, our dev environment is at a newer version than the production one.
    So, you think the error is generated because I referenced some newer technologies that was not provided by 9ias?
    Jia

  • Finding generated keys with batch updates

    Is it possible to combine reading generated keys with batch updates?
    In trying to improve performance of inserts into a database, I am using the addBatch functionality of the JDBC driver to insert several rows at once. Unfortunately some of my tables have auto numbered fields and I need to know what values they are taking so I can update my in-memory representation of the object in the database.
    The getGeneratedKeys functionality works fine when I insert one row at a time, but when I try to insert a batch of rows, the method returns null.
    I am using DB2 with the com.ibm.db2.jcc driver, though I have a hunch that this is a limitation of the JDBC spec. Can anyone confirm this? Does anyone have any ideas about a workaround?

    What is "several"?
    And have you actually measured the speed difference?
    Since returning generated keys is a rather recent addition to JDBC I doubt that it exists for batch updates.

  • What to use in jpa from self generated primary key ?

    Is it described somewhere what strategy to use with JPA when primary key are self generated by a trigger into the table ?
    Thank You

    Please see this link http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Primary_Keys_through_Triggers

  • Available characteristics and key figures in drilldown reports

    Hi,
    I'm wondering which table /structure defines what characteristics and key figures are available for drilldown reports (eg. G/L), and if it is possible to add new chars/key figs.
    I reckon there must be a structure resembling Report Painter libraries, where you can select fields from a reporting table. I just can't find that structure anywhere.
    Any help is appreciated.
    Best regards,
    Jarkko Kuusisto

    For GL the menu path is Financial accounting-general ledger accounting-G/L accounts-Line items-line item display.
    Here you select the way the line item display is set up. Also you can select the fields you want and additional fields as well. Some tcodes range from O7F1 and O7FE.
    This varies by module but is generally in the line item or information systems section in configuration.
    Go to GR21 and drop down the tables and you can see all the tables availble for report painter.
    You can add tables to report painter in sm30 in table T804A. That makes it availble for report painter.
    please assign points. It is appreciated.

Maybe you are looking for

  • Problem with window focus in xmonad

    Hi! I have the following problem with xmonad: Suppose I do the following: 1) go to fullscreen view 2) Start an application app1 e.g. evince 3) start another application on the same workspace app2 e.g. okular 4) open in app2 a dialogue (e.g. a "file o

  • How to insert a delay in cbs file in between two commands?

    Hi, This is an example/sample of cbs file I am using for Essbase Cube Refresh. LOGIN 10.128.129.200 SETSOURCE "DSN=AAA";CODEPAGE=English_UnitedStates.Latin1@Binary;UID=aaaaa;PWD=bbb;" SETTARGET "DSN=cccc;UID=nnnn;PWD=hbvhhv;" SETCATALOG "DSN=EIS_Cata

  • IO issues on Red Hat Linux SAN storage and veritas volume manager

    Oracle 11.0.1.7: We recently moved from Solaris Sparc box to linux box and since then we are seeing IO issues. And it's quite obvious in iostat that the io goes as high as 100ms. So I am wondering if someone can advice if there are any mount options

  • ColdFusion Archives option is missing

    Hi, I have a CF7 Standard installed on Windows 2003 Server with IIS 5.1. I noticed that under Packaging and Deployment menu in Coldfusion Administrator, the only option listed is J2EE archives. ColdFusion Archives option is missing. Any idea as why C

  • Find table with wbs element list

    Hi experts, i have the wbs element id number (i found it from a function) but i dont know how can i find the wbs element description table. any help will be appreciated. Michal.