Generating value of column using sequence in Toplink

Hi
I have a toplink pojo table, say SamplePojo. I need to automatically generate a value for the primary key field, say id. Is it possible to insert only the name field into the table and let toplink generate a value for id field using sequence?
I try the following code from my client class
Project project = XMLProjectReader.read("META-INF/tlMap.xml", Thread.currentThread().getContextClassLoader());
DatabaseSession session = project.createDatabaseSession();
session.shouldLogMessages();
session.login();
String query = "insert into SAMPLE_POJO(NAME) values('SAMPLE NAME')";               
session.executeSQL(query);
session.logout();If i execute the above code i get a error like "Internal Exception: java.sql.SQLException: ORA-01400: cannot insert NULL into ("MYSCHEMA"."SAMPLE_POJO"."ID")"
This is how my SamplePojo class looks like
@Entity
public class SamplePojo iimplements Serializablel {
    @Id
    @GeneratedValue(generator = "sampleSequence")
    @SequenceGenerator(name = "sampleSequence", sequenceName = "SAMP_SEQ", allocationSize = 1)
    private BigDecimal id;
    private String name;
    public SamplePojo(BigDecimal id, String name) {
        this.name = name;
        this.id = id;
//getters and setters for class variables
}

Are you trying to use JPA, or the native TopLink API?
Your annotations are JPA, but your code is the native API, using the XMLProjectReader.read("META-INF/tlMap.xml"), either use one or the other.
With JPA, you will just have a persistence.xml, and optionally an orm.xml (you will not use the Mapping Workbench).
To insert an object you just create an instance of the class and call persist(), no SQL.
i.e.
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
SamplePojo pojo = new SamplePojo();
pojo.setName("SAMPLE NAME");
em.persist(pojo);
em.getTransaction().commit();
James : http://www.eclipselink.org

Similar Messages

  • Finding max value in column using java..

    Hello there!!
    I have a problem that i tried finding in google but did not get what i wanted.. that's why i hope you guys could help me out.
    How do i find the maximum value in a column using resultset..
    for example..
    Connection con = DriverManager.getConnection("jdbc:mysql:///eproc","root", "");//eproc is dbase name in MySQL
    Statement stmt=con.createStatement();
    ResultSet rs;
    rs = stmt.executeQuery("SELECT MAX(id) FROM cat_work_sor_category");now, how do i use resultset to make sure i get the max value and assign to integer variable...
    Please do help me out.
    Thankyou.

    Connection con =
    DriverManager.getConnection("jdbc:mysql:///eproc","roo
    t", "");//eproc is dbase name in MySQL
    Statement stmt=con.createStatement();
    ResultSet rs;
    rs = stmt.executeQuery("SELECT MAX(id) FROM
    cat_work_sor_category");
    Integer MaxValue = new Integer(-1);
    if(rs.next()){
    MaxValue = rs.getInt(1);
    int MAX_VALUE = MaxValue.intValue();

  • How we generate Surrogate Keys without using identify column

    Hi All,
    How we generate Surrogate Keys without using identify column.
    Regards,
    Manish

    There are various options
    1.IDENTITY columns - simplest to implement
    2. Using NEWID(), NEWSEQUENTIALID() functions (if you want to use GUID values as surrogate keys)
    3. SEQUENCE object (if SQL 2012 and above)
    4. Using custom functions to generate keys yourself
    This is an good article which compares use of GUIDs against integers as surrogate keys
    http://blog.jonathanoliver.com/integers-vs-guids-and-natural-vs-surrogate-keys/
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • How to set null value for a date column using database adapter

    Hello,
    I have a table wih 3 columns
    (id NUMBER,
    modified_on DATE
    contentText VARCHAR2)
    I have a row wih theses values (1, 20/03/2010 16:30, 'coucou')
    I want use a DB adapter in a BPEL process to change the value of column modified_on to (null). I'm using the out-of-he box "update" method (no custom sql, nieher "insert or update (merge)" method)
    - If I only set values of "Id" and "contentText" -> insert is done but I missed the modification of "modified_on" to (null)
    - If I set all values and use expression '' (2 single quote without any space) for modified_on I got an error on update
    BWriteInteractionSpec Execute Failed Exception.
    update failed. Descriptor name: [DBUTFORM.TForm]. [Caused by: String index out of range: 10]
    Caused by Exception [TOPLINK-3001] (Oracle TopLink - 10g Release 3 (10.1.3.3.0) (Build 070608)): oracle.toplink.exceptions.ConversionException
    Exception Description: The object [xs:datetime], of class [class java.lang.String], could not be converted to [class java.sql.Timestamp].
    Internal Exception: java.lang.StringIndexOutOfBoundsException: String index out of range: 10.
    Thanks for help

    1008318 wrote:
    its my personal need..then it is a very bad personal need. DATE is not an appropriate type to be using for a primary key, as it cannot be guaranteed to be unique, especially when inserting multiple rows at once.
    You would be better working to business needs and implementing correct technical solutions to those needs, than to just do things based on your personal needs.

  • Insert into date column using EJB3.0 and toplink not working

    Hi All,
    I'm getting the following error whenever I attempt to insert a date value into my Oracle database.
    [TopLink Fine]: 2006.08.08 05:53:21.973--UnitOfWork(14806807)--Connection(14714759)--Thread(Thread[RMICallHand
    ler-0,5,RequestThreadGroup])--
    INSERT INTO EMP (EMPNO, ENAME, SAL, HIRE_DATE) VALUES (156, 'John', 2.0, {ts '2006-08-08 17:53:21.973'})
    [TopLink Warning]: 2006.08.08 05:53:22.036--UnitOfWork(14806807)--Thread(Thread[RMICallHandler-0,5,RequestThreadGroup])--
    Exception [TOPLINK-4002] (Oracle TopLink - 10g Release 3 (10.1.3.0.0) (Build 060118)):
    oracle.toplink.exceptions.DatabaseException
    Internal Exception: java.sql.SQLException: ORA-00904: invalid column name
    The cause seems to be clear enough; from the sql above it seems that the timestamp syntax isn't being interpreted properly by either toplink or the JDBC driver , (I'm using whatever driver that comes with OC4J 10.1.3).
    I've seen somewhere that you can call setUseNativeSQL() in toplink but how do I get hold of the toplink session from an entity bean?
    That sounds like an awkward workaround anyway, what other workarounds are open to us?
    Thanks,
    C

    C,
    I don't use TopLink, but I suggest you set the "processEscapes" [Oracle database connection] property to "true", as described in the JDBC User's Guide and Reference.
    Oracle documentation can be accessed from here:
    http://www.oracle.com/technology/documentation/index.html
    Good Luck,
    Avi.

  • MAX(SummaryNum) +1 bad idea, but how to use sequence part composite column

    Hi,
    My relational mode is as follows
    Policy (policynum PK) has 1:M with Summary (policynum FK, SummaryNum part of PK, other columns part of PK)
    Basically for each policy users can enter notes with SummaryNum 1, 2, 3, 4.... These numbers are shown to the user for tracking purpose. I need to make sure summary notes for EACH policy start with 1 (cannot really use sequence in the table in the strictest sense) and are incremented by 1. The current Oracle form basically creates the next highest possible value of SummaryNum by adding one to the currently available highest value. In brief, it is like a sequence number for summaries of a particular policy in the summary table.
    PRE-INSERT
    SELECT MAX(SummaryNum ) + 1
    FROM Summary
    I am trying to replicate this in ADF BC (using 11g) and know that not using sequencing and adding one to get the next number is a very bad idea due to concurrency challenges (transactional ACID properties). The reasons are as follows.
    •     Using MAX(policy_memo_seq_num) + 1 is not scalable,
    •     It will lead to duplicates in a multi-user environment, whether ADF BC, Oracle Forms, or any other technology
    I also know how to use create a sequence in db, a related trigger, and then set the attribute in EO properties as DBSequence. My challenge is that since SummaryNum is not a primary key, and instead is part of a composite key in my case, how do I make sure that summary notes for EACH policy start with 1 in the Summary Table.
    I appears that i cannot really use sequence in the table in the strictest sense as this will mean that for policies the summaryNum will start from the next available sequence number, but what i really want is to have it start by one for all policies.*
    I would appreciate any help.
    Thanks,

    Not sure if there is a better way, but here is one way. Let's say your table was like this:
        SQL> desc versioned_item
         Name         Null?    Type
         ID           NOT NULL NUMBER
         VERSION      NOT NULL NUMBER
         DESCRIPTION           VARCHAR2(20)and lets say your data looked like this:
        SQL> select * from versioned_item order by id, version
                ID    VERSION DESCRIPTION
              1001          1 Item 1001
              1001          2 Item 1001
              1001          3 Item 1001
              1002          1 Item 1002
              1002          2 Item 1002
              1003          1 Item 1003To select only the rows for the max-version-id, you could do this:
        select id, version,description
        from versioned_item
        where (id,version) in (select id,max(version) from versioned_item group by id)
        order by id
                ID    VERSION DESCRIPTION
              1001          3 Item 1001
              1002          2 Item 1002
              1003          1 Item 1003To capture this as a view object, you'd only just need to paste in the WHERE clause above into the Where clause box of the view object. No need to use expert-mode since you're not changing the select list or from clause.

  • From two given tables, how do you fetch the values from two columns using values from one column(get values from col.A if col.A is not null and get values from col.B if col.A is null)?

    From two given tables, how do you fetch the values from two columns using values from one column(get values from col.A if col.A is not null and get values from col.B if col.A is null)?

    Hi,
    Use NVL or COALESCE:
    NVL (col_a, col_b)
    Returns col_a if col_a is not NULL; otherwise, it returns col_b.
    Col_a and col_b must have similar (if not identical) datatypes; for example, if col_a is a DATE, then col_b can be another DATE or it can be a TIMESTAMP, but it can't be a VARCHAR2.
    For more about NVL and COALESCE, see the SQL Language manual: http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions119.htm#sthref1310
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables involved, and also post the results you want from that data.
    Explain, using specific examples, how you get those results from that data.
    Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
    See the forum FAQ: https://forums.oracle.com/message/9362002

  • How to insert a blank value in not nul column using transform activity

    can anyone help me on how to insert blank values in a not null column using transform activity or however possible..This is a requirement in my project ..

    vidya
    In DB adapter or-mappings.xml , did you made any changes. If not the open that file in any notepad editor and change the following
    <attribute-mapping xsi:type="direct-mapping">
    <attribute-name>director</attribute-name>
    <field table="MYTABLE" name="MAKE_IT_BLANK_NOT_NULL" xsi:type="column"/>
    <attribute-classification>java.lang.String</attribute-classification>
    </attribute-mapping>You can try to add this:
    <attribute-mapping xsi:type="direct-mapping">
    <attribute-name>director</attribute-name>
    <field table="MYTABLE" name="MAKE_IT_BLANK_NOT_NULL" xsi:type="column"/>
    <null-value></null-value>
    <attribute-classification>java.lang.String</attribute-classification>
    </attribute-mapping>Refer below link for details
    Re: Insertion of Blank value to a Not Null varchar column in SQL server table
    Thanks
    AJ

  • SP Online - Managed Metadata column Default Value for folders (using CSOM)

    Hello,
    I am working on setting default values (metadata columns)  for different folders on my document library. As so far, I've found solution about how to set default values on whole library and many solutions which works for folders, but not for sharepoint
    online (using metadataDefaults object).
    The only working solution for folders in SPO I've found is editing file library/Forms/client_LocationBasedDefaults and add some data here.
    My question is: is there any easier method to set default values for each folder in document library without manually editing this file? 

    I second that, I have a client looking to do the same thing but I don't see a way to automate this.

  • Re-using expression-generated values to input into other expressions (read-out)

    Hi there everyone. I was wondering if there is a way to 'capture' expression generated values and either buffer these values or re-using them directly in other expressions. I am trying to track rotations of parented layers, which are generated from the DuDuf IK expressions. Getting the rotation through a pick-whip will always return zero, of course; but as After Effects is able to physically show the expression generated value as a number, I guess it should also be able to output this number somewhere as a (buffered) digital value to be re-used somewhere again.
    Anyone ideas?

    Hi Dan, good to hear from you. I know, it sounds that easy. I'll try to explain this thing with a little more detail. If I can find a way to tackle this challenge, it will save me about 60 hours rendering each time this job passes my desk.
    I have a standard (5 sec.) comp with four lines of text in just one font with a fixed size and everything. As explained before, I run a script that generates between 300 and 400 copies of this comp, giving each new comp a logical and unique name, ánd... replacing the contents of all text lines in every copy of the comp. Now the first line of text is easy: just a number. It's left justified and the layout is always correct. The second, third and fourth line are actually a few people's names (the whole comp is actually a crew title for participants in the Dakar rally), where every name is followed by a three-character nationality abbreviation, like USA, or GER or FRA and so on. You must understand that the comp is built up in seven independant text fields, of which each one gets its content automatically through the mentioned script from an Excel sheet. Now here is the problem:
    The designer who created the layout for the titles wants to have the three-character nationality abbreviation exactly one character space BEHIND the name in every title. Ofcourse, the name (set in its own text field and AE layer) is pretty variable in length, so the position of the nationality field that comes right next to the name field, needs to be automatically adjusted in accordance with the name field length. To determine this position, the designer wrote (or adapted) an expression that samples the 'image' of the preceding name title, thus finding the rightmost white pixel (the titles are all simply white on black) and thus, with a certain offset, generating the right basic position for the following title.
    Now I thought I checked thoroughly for a possibility to extract the rightmost 'bounding box line' of a title in another video layer in AE somehow, and I couldn't find it; whereas you mention this can be done. If that is really possible, it would save my day...
    All I ran into was that text layers are always comp size (thisLayer.height and thisLayer.width always give 1920x1080 in an HD comp, no matter how small the text in the text layer) and therefore it seemed impossible to me (and the man who wrote the expression probably) to get any useful info concerning the characters positions and bounding boxes etc.
    So: how can this be done? How can I measure directly what the position value of the rightmost pixel of a line of text is and pass that on to another layer's position? In that case I can work around the time consuming sampleImage expression.
    I'm sure someone is going to send you a big bottle of wine on this one .... :-)

  • System generated value for a field and incrementing (using module pool pro)

    Hi,
    I'm getting system generated value for a field and incrementing (i.e done by coding) when i'm saving the screen or transaction (which is created using module pool programming) while modifying, saving its working fine, but when i'm going out of the screen or exit n again i start the screen (with some ztransco) the value for the field again starting from 0 so i want to start from the same value for a field where we exit or got out from the screen n incremented respectively while saving the screen,
    Thanks & Regards,
    MS
    Edited by: Rob Burbank on May 4, 2010 10:40 AM

    Search the forum for number range objects.
    Rob

  • Interpretation of values in log generated for auth checks(using RSECADMIN)

    Hi experts
    Could you please help me in reading the error log which is created using transaction RSECADMIN.My question is in particular about the interpretation of the values which occurs in front of the authorization relevant characteristics in the section "main checks" of the error log.
    For example if I run a query , assumption(user is configured for auth. logs using rsecadmin and then finally when the query gets completed we see the authorization logs using rsecadmin only). Then in the log it shows what values were checked for the authorizations against authorized values/sets. Lets say there are 2 characteristics char1 and char2 which have hierarchies below them and I run a query with some values(any random nodes from hierarchy below char 1) for Char 1 and some values(any random nodes from hierarchy below char 2) for char2 in the query selection screen and after I run the query and see the log then below values are shown for log:
    Authorization Check  
    Detail Check for InfoProvider <INFOPROV > 
    and then comes the section related to value checks ( MAIN CHECK)
    Main Check
    Subselection (Technical SUBNR) 1  
    Following Set Is Checked                           Comparison with Following Authorized Set 
    Characteristic | Contents                           Characteristics |  Contents                                                                               result
    Char 1           | Node 0 4 0                           Char 1           | All values of nodes for Char1 for which user is authorized.          Ok/NOK
                         | 121339 1
    Char 2          | Node 3 1 98
                       | 121333 1                             Char 2                | All values of nodes for char 2 which user is authorized             Ok/NOK
    Could you please help in getting how shall I interperate the values which are being checked.I mean how exactly should i get the characteristic values from the below shown values
    Char 1           | Node 0 4 0      
                         | 121339 1
    Char 2          | Node 3 1 98
                       | 121333 1   
    I know that this might have some sids related to those values which are passed as nodes in the query selections but I am not sure how shall I get the values which are being passed for checks to the authorized set of values using above notification from sap.
    Could you please help me so that I can find out what values are passed for checks .
    I actually want to know how shall I use the values 0 4 0 121339 1 after the node for char 1 and 3 1 98 121333 after the node for char2.
    The values for the authorized set can be knows as they are shown at the end of the log but nothing is said about the node values which are passed for being checked.
    Please give me light on above so that i can use above informtion to find out what actually the user is not authorized for.
    I hope I explained the requirement to best of levels but still if this is not clear , please let me know.It might be possible that while posting the question some lines get merged (apology for the same but i could not fine the best way to put the same here).
    Thanks
    Vishal

    Hi Chandu
    Thanks for reply. But using the transaction RSECPROT and seeing the log from the rsecadmin both are same as the main program related to both of them is RSEC_PROTOCOL_MAIN.
    My question was related to this generated log only. I know that is in readable format but in log when you see what values are being checked against the authorized set then the part which is not clear to me is that what does the values in front of characteristic (for the node is selected as input value ( selection filter ) to see the data ) signifies.
    Please see example above (as given by me) and please help in interpreation of those generated values in front of charactertistics char1 and char2 (if possible) .
    Regards
    Vishal

  • How to set default value of a table using sequence number

    Dear all,
    Does any body know that how to set default value of a table
    using sequence number.
    But I don't want to use trigger to do that.
    Please help!!!!
    Eldon

    Andrew is essentially correct. You can get around the trigger,
    but not the sequence, if (and this may be a very big if) you can
    guarantee that every time an insert is done into the table, from
    whatever source, the statement looks something like
    INSERT INTO tbl VALUES (sequence.nextval,other_columns_values)

  • Generating values using Regular Expression

    Can values be generated using Regular Expreession?
    I want to generate unique string values on the fly using secified Regular Expression.
    Thanx in advance.
    Message was edited by:
    Kaustubh

    i do not know if there is something that can do it automatically but let's say you have the following regex:
    "a number of 5 digits" then "2 letters" then "a hyphen" and then "a digit"
    what you can do is something like that:
    define the vars that will allows you to pick a value for each part of the generated value
    this means you will have:
    final int[] DIGITS = new int[]{0;1;2;3;4;5;6;7;8;9};
    final char[] LETTERS = new char[]{'a', 'b', ... 'z'};
    final char HYPHEN = '-';
    once you have those vars, all you have to do is to use "Random" class to retrieve a random value from DIGITS and LETTERS
    append them all in the correct order , without forgetting to append the HYPHEN and you have your value

  • How to generate a dynamic column with unique value in AMDP

    Hi Collegue,
    For AMDP I have a table with material plant,i have to assign a unique number to each unique combination of material,plants into a dynamic column say sequence.
    Please suggest me how to proceed.
    Regards,
    Saurabh

    hi
    Firstly, have a look at the following code to see how this can be implemented -
    REPORT ZTEST.
    perform test.
    class test definition.
      public section.
        methods: create_screen.
    endclass.
    class test implementation.
      method create_screen.
        data:  report_line(72),
               report_source like table of report_line.
        data: err_message(240),
              err_line type i,
              err_word(100).
        report_line = 'REPORT TEST.'.
        append report_line to report_source.
        report_line = 'PARAMETERS: P_TEST TYPE I.'.
        append report_line to report_source.
        report_line = 'START-OF-SELECTION.'.
        append report_line to report_source.
        report_line = 'WRITE : P_TEST.'.
        append report_line to report_source.
        syntax-check for report_source message err_message
                                       line    err_line
                                       word    err_word.
        if err_message is initial.
          INSERT REPORT 'ZZZTESTZZZ' FROM REPORT_SOURCE.
          SUBMIT ZZZTESTZZZ VIA SELECTION-SCREEN AND RETURN.
        endif.
      endmethod.
    endclass.
    form test.
      data test type ref to test.
      CREATE OBJECT TEST.
      call method test->create_screen.
    endform.
    As you can see, the report is being written dynamically. Once the INSERT REPORT statement is executed, the program is available. you can you external subroutine calls to pass the data between the programs now.
    Regards,
    ravish
    <b>plz dont forget to reward points if helpful</b>

Maybe you are looking for

  • G5 1.6 still freezing after all these years

    Hi, I have this G5 1.6 for a long time and this is the issue: After all diagnostics and two times recovered in the official Mac repair service (who suggested new motherboard and/or processor) my computer: Freezes when I least expect and all I can say

  • Porblem loading Microsoft JDBC Driver for SQL Server

    Hi all !! Well, it seems there is a naming problem for the MS Driver, when Netbeans creates server resources for the Connection Pool and the DataSource, the default name for the connection pool's datasource classname is com.microsoft.jdbc.sqlserver.S

  • Error during off-cycle payroll

    Hello gurues,    The user got an error while executing an off-cycle payroll, and I cant figure out whats the meaning of it and why is it happening.    The message is very general, "Function has an incorrect value for parameter" 5P 411.    If someone

  • Overcharged.

    Hello. First of all, my bill came to £69.63. I prepaid £35 using my credit card. I have been charged £69.63. Please ensure that £34.63 reaches my account today to remedy the situation. Secondly, this is a poor system for providing feedback and compla

  • Monthly system upgrade email

    I just received an email asking me to click on a link which is supposed to finish my "monthly system upgrade".   Is this phishing?