JPA annotation @GeneratedValue(strategy = GenerationType.???)

What is the recommended strategy for handling identity fields? Suppose I have a table named Employee with a primary key column emp_id. With oracle 10g, we created a sequence emp_id_seq and a trigger to automatically insert emp_id_seq.nextval into emp_id when a row is inserted into Employee table. Therefore, user does not need to provide a value for emp_id for insertion. Given a table like this, how should we choose the GenerationType?
If this is not the right place for this type of questions, please let me where I should post this question. Thanks

In general I would not recommend this, and instead let EclipseLink insert the id value and use an increment on the sequence to allow preallocation and much better performance. Maybe have the trigger only assign the value if not set.
However, you can do this either by:
- Using a ReturnPolicy for the id (@ReturnInsert instead of @GeneratedValue)
- In the OraclePlatform call setSupportsIdentity(true) (such as using a SessionCustomizer), this will then allow identity like sequencing
James : http://www.eclipselink.org

Similar Messages

  • JPA cascade with  @GeneratedValue(strategy=GenerationType.IDENTITY)

    If anyone has got cascading persistance working in JPA with database generated primary keys I'd be much obliged if you could let me know how.
    Am attempting to use tables with database auto generated primary keys (MySQL AUTO_INCREMENT), and using the JPA cascade features. But I can't see how to make it work.
    The problem is that if you cascade persist a series of entities, you need to know the database primary keys before you persist to the database.
    If I remove all the cascades in my @entity's, and explicitly persist entities in the correct order so the primary keys are set before them being needed, then all is ok.
    When I put the cascades in, my JPA implementation (Toplink) attempts to create the entities with foreign keys to tables with the yet to be generated primary keys all null. I was hoping JPA/Toplink would be clever enough to persist the entities in order, setting the database generated primary keys as it went.
    Has anyone tried this in Hibernate?
    Sampe code exerts that does not work:
    @Entity
    public class Address implements Serializable {
       private long id;
       private Collection<Contact> contacts = new ArrayList<Contact>();
       @OneToMany(cascade = { CascadeType.ALL })
       public Collection<Contact> getContacts() {
          return contacts;
    @Entity
    public class Contact implements Serializable {
       private long id;
       @Id
       @Column(updatable = false)
       @GeneratedValue(strategy = GenerationType.IDENTITY)
       public long getId() {
          return this.id;
    CREATE TABLE address (
           id BIGINT NOT NULL AUTO_INCREMENT
         , address_line_1 VARCHAR(64)
         , address_line_2 VARCHAR(64)
         , address_line_3 VARCHAR(64)
         , suburb VARCHAR(64)
         , postcode VARCHAR(16)
         , state VARCHAR(64)
         , country_code CHAR(2)
         , PRIMARY KEY (id)
    CREATE TABLE contact (
           id BIGINT NOT NULL AUTO_INCREMENT
         , address_id BIGINT
         , contact_type CHAR(10)
         , value VARCHAR(255)
         , PRIMARY KEY (id)
         , INDEX (address_id)
         , CONSTRAINT FK_contact_address FOREIGN KEY (address_id)
                      REFERENCES address (id)
    );

    The way I have it, the contact does need annotations as it is a bidirectional link. The contact defines the link and the address has a mappedBy="address".
    If you remove the annotations on contact, I think you will need to set up a unidirectional one-to-many link and my 'text book' says you need to have a join table to implement this. I tried all kinds of ways to have a unidirectional one-to-many link without a join table, but never succeeded.
    I found if a persist failed it would still use up sequence numbers (Hibernate and MySQL), but I did not come accross your problem. I found it useful to look on the SQL Database logs to see exactly what SQL was getting to the server.
    My code - so far working fine, am in mid development though.
    Address.java:
    @Entity
    @Table(name = "address", schema = "z")
    public class Address implements Serializable {
       private static final long serialVersionUID = 1L;
       private long id;
       private String addressLine1;
       private Collection<Contact> contacts = new ArrayList<Contact>();
       public Address() {
          super();
       @Id
       @Column(updatable = false)
       @GeneratedValue(strategy = GenerationType.IDENTITY)
       public long getId() {
          return this.id;
       public void setId(long id) {
          this.id = id;
       @Column(name = "address_line_1")
       public String getAddressLine1() {
          return this.addressLine1;
       public void setAddressLine1(String addressLine1) {
          this.addressLine1 = addressLine1;
       @OneToMany(mappedBy="address", cascade={CascadeType.ALL})
       public Collection<Contact> getContacts() {
          return contacts;
       public void setContacts(Collection<Contact> contacts) {
          this.contacts = contacts;
    Contact.java:
    @Entity
    @Table(name = "contact", schema = "z")
    public class Contact implements Serializable {
       private static final long serialVersionUID = 1L;
       private long id;
       private Address address;
       private String value;
       private String contactType;
       public Contact() {
          super();
       @Id
       @Column(updatable = false)
       @GeneratedValue(strategy = GenerationType.IDENTITY)
       public long getId() {
          return this.id;
       public void setId(long id) {
          this.id = id;
       @ManyToOne (cascade={CascadeType.ALL})
       @JoinColumn(name="address_id", referencedColumnName="id", nullable=false, updatable=false)
       public Address getAddress() {
          return this.address;
       public void setAddress(Address address) {
          this.address = address;
       public String getValue() {
          return this.value;
       public void setValue(String value) {
          this.value = value;
       @Column(name = "contact_type")
       public String getContactType() {
          return this.contactType;
       public void setContactType(String contactType) {
          this.contactType = contactType;
    }

  • Toplink Essentials JPA doesn't use GenerationType.IDENTITY

    Based on EJB 3 and JPA I want to store some entities (@Entity) in a database. For some of those entites the database auto increments the primary key. In these cases I defined a @TableGenerator and a @GeneratedValue using GenerationType.IDENTITY as strategy in order to get the primary key (@Id) updated after the entity has been persisted.
    Short example:
    @Entity
    @Table(name = "orders")
    public class POrder implements PEntity {
         @TableGenerator(name = "orderIdGenerator", initialValue = 0, allocationSize = 1)
         @Id
         @GeneratedValue(strategy = GenerationType.IDENTITY, generator = "orderIdGenerator")
         @Column(name = "orderNumber", nullable = false)
         private Integer orderNumber;
    ...I am running the application on GlassFish. I added a corresponding JDBC resource to the server configuration, using the specific MySql driver interfaces.
    Persisting entities which doesn't use a TableGenerator works, but as soon as I try to persist an entity which should use a TableGenerator I am running in the following exception:
    beergame.server.exception.BeergameServerException: nested exception is: Exception [TOPLINK-4002] (Oracle TopLink Essentials - 2.1 (Build b55-fcs (10/10/2008))): oracle.toplink.essentials.exceptions.DatabaseException
    Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'beergame3.sequence' doesn't exist
    Error Code: 1146
    Call: UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?
         bind => [1, roleIdGenerator]
    Query: DataModifyQuery()
    Local Exception Stack:
    Exception [TOPLINK-4002] (Oracle TopLink Essentials - 2.1 (Build b55-fcs (10/10/2008))): oracle.toplink.essentials.exceptions.DatabaseException
    Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'beergame3.sequence' doesn't exist
    Error Code: 1146
    Call: UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?
         bind => [1, roleIdGenerator]
    Query: DataModifyQuery()
         at oracle.toplink.essentials.exceptions.DatabaseException.sqlException(DatabaseException.java:311)
         at oracle.toplink.essentials.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:654)
         at oracle.toplink.essentials.internal.databaseaccess.DatabaseAccessor.executeNoSelect(DatabaseAccessor.java:703)
         at oracle.toplink.essentials.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:492)
         at oracle.toplink.essentials.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:452)
         at oracle.toplink.essentials.internal.sessions.AbstractSession.executeCall(AbstractSession.java:690)
         at oracle.toplink.essentials.internal.queryframework.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:228)
         at oracle.toplink.essentials.internal.queryframework.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:214)
         at oracle.toplink.essentials.internal.queryframework.DatasourceCallQueryMechanism.executeNoSelectCall(DatasourceCallQueryMechanism.java:257)
         at oracle.toplink.essentials.internal.queryframework.DatasourceCallQueryMechanism.executeNoSelect(DatasourceCallQueryMechanism.java:237)
         at oracle.toplink.essentials.queryframework.DataModifyQuery.executeDatabaseQuery(DataModifyQuery.java:86)
         at oracle.toplink.essentials.queryframework.DatabaseQuery.execute(DatabaseQuery.java:628)
         at oracle.toplink.essentials.internal.sessions.AbstractSession.internalExecuteQuery(AbstractSession.java:1845)
         at oracle.toplink.essentials.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:952)
         at oracle.toplink.essentials.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:924)
         at oracle.toplink.essentials.sequencing.QuerySequence.update(QuerySequence.java:344)
         at oracle.toplink.essentials.sequencing.QuerySequence.updateAndSelectSequence(QuerySequence.java:283)
         at oracle.toplink.essentials.sequencing.StandardSequence.getGeneratedVector(StandardSequence.java:96)
         at oracle.toplink.essentials.sequencing.Sequence.getGeneratedVector(Sequence.java:281)
         at oracle.toplink.essentials.internal.sequencing.SequencingManager$Preallocation_Transaction_NoAccessor_State.getNextValue(SequencingManager.java:420)
         at oracle.toplink.essentials.internal.sequencing.SequencingManager.getNextValue(SequencingManager.java:846)
         at oracle.toplink.essentials.internal.sequencing.ClientSessionSequencing.getNextValue(ClientSessionSequencing.java:110)
         at oracle.toplink.essentials.internal.descriptors.ObjectBuilder.assignSequenceNumber(ObjectBuilder.java:240)
         at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.assignSequenceNumber(UnitOfWorkImpl.java:355)
         at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.registerNotRegisteredNewObjectForPersist(UnitOfWorkImpl.java:3266)
         at oracle.toplink.essentials.internal.ejb.cmp3.base.RepeatableWriteUnitOfWork.registerNotRegisteredNewObjectForPersist(RepeatableWriteUnitOfWork.java:432)
         at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:3226)
         at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerImpl.persist(EntityManagerImpl.java:221)
         at com.sun.enterprise.util.EntityManagerWrapper.persist(EntityManagerWrapper.java:440)
         at beergame.server.model.trans.impl.TExtensionOfPEntityImpl.persist(TExtensionOfPEntityImpl.java:130)
         at beergame.server.model.trans.impl.TRoleImpl.<init>(TRoleImpl.java:61)
         at beergame.server.logic.trans.impl.GameLogicImpl.assignUserToValueChainLevel(GameLogicImpl.java:81)
         at beergame.server.logic.remote.impl.UserSessionBean.createGame(UserSessionBean.java:65)
    I wonder why a sequence table has to be update whereas IDENTITY is defined as strategy. I tried also AUTO as strategy but it doesn' matter, the result is the same.
    I read several posts in forums, but couldn't find a solution. So I still have no idea how to get IDENTITY used as strategy. Any one of you does?
    My configuration:
    IDE: Eclipse 3.4.0
    Server: GlassFish V2 Java EE 5
    JPA Implementation: Toplink Essentials v2.1-b55
    JPA driver: oracle.toplink.essentials.PersistenceProvider
    Database: MySQL 5.0.51a
    JDBC driver: mysql-connector-java-5.1.5

    I did it. I must admit, I was a little bit confused by the annotation TableGenerator. It is not responsible for generating ids of a table at all but only in conjunction with a table which should provide ids.
    After I removed @TableGenerator and also the corresponding reference within @GeneratedValue the persistence works as expected. Now the code looks like this:
    @Entity
    @Table(name = "orders")
    public class POrder implements PEntity {
         @Id
         @GeneratedValue(strategy = GenerationType.IDENTITY)
         @Column(name = "orderNumber", nullable = false)
         private Integer orderNumber;
    ...Edited by: TomCat78 on Oct 12, 2008 3:38 PM

  • Automatically Add JPA Annotations

    Hi,
    I am not sure if my question is annotation specific, maybe it is more generally about generating source code.... here is what I want to do:
    I want to use JPA annotations to declare the O/R mapping of my domain classes, but actually I don't want to write these annotations manually. I want to generate them automatically based on name patterns.
    e.g. I have the following class:
    public class Permission  {
        private Integer permissionID;
        private Set <AccountGroup> accountGroups = new HashSet<AccountGroup>();
    }... now I want to write a java program that adds annotations based on name patterns and get something like:
        @Id
        @Column( name = "permissionID", updatable = false, nullable = false )
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Integer permissionID;
        @ManyToMany (
            targetEntity = AccountGroup.class
        @JoinTable (
            name = "Permission_AccountGroup",
            joinColumns = @JoinColumn (name="permissionID"),
            inverseJoinColumns = @JoinColumn (name="accountGroupID")
        private Set <AccountGroup> accountGroups = new HashSet<AccountGroup>();What is the easiest way to insert the annotations into the source code? ... I am thinking about methods like "addAnnotationToClass / Field" ... any idea?

    Hi there...
    I just made a similar question.
    i have tested and i have the same problem.
    the solution i found at the moment for me was to move back to 10.2.1. As this are minor versions, i just uninstalled 10.2.2, got a copy of itunes 10.2.1 from oldapps website and installed that one, and seems are back to normal.
    Fred

  • JPA - Mysql - GeneratedValue

    I am using Mysql with Eclipselink 2.0.1 and have the following situation:
    My Entity is using a field declared like this:
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long referenceNumber;
    The DDL is generated and in my database all tables are created. If I insert a new record within my EJB I am getting as the "referenceNumber" not "1" - I am getting sometimes "50" sometimes "1232". It is a completely random id. Is it possible to get an ID which is starting by 1 and incrementing automatically ?
    I have tried to use GenerationType.IDENTY but this has some problems with cascading operations, so I do not want to use it.

    Hello,
    I just started playing with JPA and mysql. My tables's primary keys use auto-increment option in database. To tell application how to work with these fields I use following statements and everything works perfect after some troubles in the beggining of course :-)) :
    @Entity
    @Table(name = "C_ADRESA_TYP") //, schema = "KMPV"
    public class CiselnikAdresaTyp implements Serializable{
         private static final long serialVersionUID = 1L;
         @Id
         //@Required - cannot be used when using auto-increment and IDENTITY gerenator
         @Hidden
         @Column(name = "PK_ADRESA_TYP", insertable = false, nullable = false, updatable = true)
         @GeneratedValue(strategy=GenerationType.IDENTITY)
         private int pkAdresaTyp;
         @Required
         @Column(name = "KOD", length = 30, nullable = false, updatable = true)
         private String kod;
    .....etc
    In case of you are experiencing still some troubles witch some cascade actions, this could be regarding your foreing keys, exactly on on update on delete actions.
    Hope it'll help.
    archenroot
    Edited by: user8916162 on Nov 9, 2010 11:18 AM

  • JPA - generate orm.xml from existing JPA annotations

    Hi,
    Is there any tool which can be used to generate the orm.xml file from existing JPA java annotated source files?
    Thank you,
    Virgil

    Yes. Map some of the classes with JPA annotations or orm.xml, for the other leave them unmapped, and don't list them in your persistence.xml. Then in a SessionCustomizer you can load your native EclipseLink project.xml file using the XMLProjectReader, and then manually add the descriptors from the Project to the JPA EclipseLink Session using DatabaseSession.addDescriptors(Project).

  • JPA Annotation Processing

    Is this the correct forum to discuss JPA object relational mapping using annotations?

    rbroersma wrote:
    kajbj wrote:
    rbroersma wrote:
    Is this the correct forum to discuss JPA object relational mapping using annotations?
    No, probably not. The [JDBC forum|http://forums.sun.com/forum.jspa?forumID=48] might be better. But note that there probably are better forums if you want to discuss annotations that are related to a certain product/application (e.g. Hibernate)
    That's too bad. While JPA annotations might be discussed on the JDBC forum it isn't exactly related either. Since javax.persistence is part of both Java SE and EE it would be nice if a form could be opened for this rather large topic.
    Is there a way to make a request like this?You can create a thread in the News and Updates forum: [http://forums.sun.com/forum.jspa?forumID=515]

  • JPA mixed inheritance strategy issue

    Table : A, b
    Class : A, B, C
    @Entity
    @Table(name="A")
    @Inheritance(strategy=InheritanceType.JOINED)
    @DiscriminatorColumn(name="type")
    abstract Class A
    @Entity
    @Table(name="B")
    @DiscriminatorValue("B")
    @PrimaryKeyJoinColumn()
    Class B extends A
    @Entity
    @DiscriminatorValue("C")
    Class C extends A
    From A - B its *@Inheritance(strategy=InheritanceType.JOINED)* and from A - C its *@Inheritance(strategy=InheritanceType.SINGLE_TABLE)* by default. When I try to run some test Toplink doesn't identifies class C as mixed strategy but expects C to have its own table as the super class A is specified with Joined strategy. Not sure how else would mixed strategy work !
    Any help would be greatly appreciated.
    Tx
    K

    Hello,
    My understanding is that all classes should use the inheritance strategy defined in its parent class - there is no way to have two strategies used on a single parent class.
    If you are aiming to get 3 classes (A, B and C) to use two tables (A, B) you might instead try specifying the root (A) to use SINGLE_TABLE. B will then automatically have an entry in Table A, and Class B can then be defined to use the B table as well by adding the @SecondaryTable(name="B") annotation to it, specifying the joincolumn if the primary key field names are different. A and C will then only use Table A, B will use Table A for inherited attributes and join to Table B - be sure to explicietly define the table to be used in any mappings on B that you wish to use Table B, otherwise I believe Table A will be assumed as it is the primary table.
    Best Regards,
    Chris

  • Embedding with JPA annot: column "is not compatible with expected type"

    I have the following embed case (things I guess to be inessential omitted):
    @Entity
    public class Container {
    @Id
    @GeneratedValue
    @Column(name="ID")
    private long id;
    @Embedded
    @AttributeOverride(name="value", column=@Column(name="UID"))
    private Uid uid;
    @Embeddable
    public class Uid {
    private String value;
    When I run this through the mapping tool to build the schema, it correctly builds the UID column in the MySQL Agreement table as a VARCHAR.
    However, when I try to access the table, I get the following error (I've edited class names to match my simplified example):
    RROR_SYSTEM_FAILED:
    <4|true|4.0.0> kodo.persistence.ArgumentException: "Uid.value" declares a column that is not compatible with the expected type "varchar". Column details:
    Full Name: Agreement.UID
    Type: blob
    Size: 0
    Default: null
    Not Null: false
         at kodo.jdbc.meta.MappingInfo.mergeColumn(MappingInfo.java:720)
         at kodo.jdbc.meta.MappingInfo.createColumns(MappingInfo.java:567)
         at kodo.jdbc.meta.ValueMappingInfo.getColumns(ValueMappingInfo.java:143)
         at kodo.jdbc.meta.strats.StringFieldStrategy.map(StringFieldStrategy.java:52)
         at kodo.jdbc.meta.FieldMapping.setStrategy(FieldMapping.java:101)
         at kodo.jdbc.meta.RuntimeStrategyInstaller.installStrategy(RuntimeStrategyInstaller.java:75)
         at kodo.jdbc.meta.FieldMapping.resolveMapping(FieldMapping.java:497)
         at kodo.jdbc.meta.FieldMapping.resolve(FieldMapping.java:456)
         at kodo.jdbc.meta.ClassMapping.resolveNonRelationMappings(ClassMapping.java:930)
         at kodo.jdbc.meta.ClassMapping.resolveMapping(ClassMapping.java:886)
         at kodo.meta.ClassMetaData.resolve(ClassMetaData.java:1761)
         at kodo.jdbc.meta.ValueMappingImpl.resolve(ValueMappingImpl.java:541)
         at kodo.jdbc.meta.strats.EmbedFieldStrategy.map(EmbedFieldStrategy.java:62)
         at kodo.jdbc.meta.FieldMapping.setStrategy(FieldMapping.java:101)
         at kodo.jdbc.meta.RuntimeStrategyInstaller.installStrategy(RuntimeStrategyInstaller.java:75)
         at kodo.jdbc.meta.FieldMapping.resolveMapping(FieldMapping.java:497)
         at kodo.jdbc.meta.FieldMapping.resolve(FieldMapping.java:456)
         at kodo.jdbc.meta.ClassMapping.resolveMapping(ClassMapping.java:890)
         at kodo.meta.ClassMetaData.resolve(ClassMetaData.java:1761)
         at kodo.meta.MetaDataRepository.processBuffer(MetaDataRepository.java:683)
         at kodo.meta.MetaDataRepository.resolveMapping(MetaDataRepository.java:635)
         at kodo.meta.MetaDataRepository.resolve(MetaDataRepository.java:518)
         at kodo.meta.MetaDataRepository.getMetaData(MetaDataRepository.java:288)
         at kodo.meta.MetaDataRepository.getMetaData(MetaDataRepository.java:352)
         at kodo.kernel.QueryImpl.classForName(QueryImpl.java:1879)
         at kodo.kernel.ExpressionStoreQuery$1.classForName(ExpressionStoreQuery.java:74)
         at kodo.kernel.jpql.JPQLExpressionBuilder.getClassMetaData(JPQLExpressionBuilder.java:151)
         at kodo.kernel.jpql.JPQLExpressionBuilder.resolveClassMetaData(JPQLExpressionBuilder.java:119)
         at kodo.kernel.jpql.JPQLExpressionBuilder.getCandidateMetaData(JPQLExpressionBuilder.java:203)
         at kodo.kernel.jpql.JPQLExpressionBuilder.getCandidateMetaData(JPQLExpressionBuilder.java:176)
         at kodo.kernel.jpql.JPQLExpressionBuilder.getCandidateType(JPQLExpressionBuilder.java:167)
         at kodo.kernel.jpql.JPQLExpressionBuilder.access$500(JPQLExpressionBuilder.java:30)
    ===
    I can't figure out why it thinks something should be a blob. Any thoughts?
    Thanks,
    -- Bryan Loofbourrow

    Ok, I found the problem. I hadn't added the Uid.java to the persistence.xml file, so although the mapping tool correctly recognized this as a varchar situation, the execution environment did not, taking Uid to be a nonpersistent class that it must treat as a blob.
    -- Bryan

  • Error from the jpa annotation

    when I wrote some sample code according to the mastering EJB 4th Ed and deployed my project in jboss I got lots of exception. I should move annotation location (Ex move the annotation from the getter method to the property declaartion).
    Is there any standard for the annotation location?
    Any differece among the different places?

    Entity annotation can be either at field or property level (Getters only)
    Cannot put the annotation on setters.
    Also, if the annotations are applied to both field and properties then the behavior is undefined according to specifications. (Container dependent)

  • How to execute a query uses hibernate @Formula or other JPA annotation

    Solved ! ^^

    This is the code.
    1. we can declare types dynamically
    2. Internal table dynamically
    3. Select querry dynamically
    just copy paste this code
    Here is the code for your question
    DATA:v_fieldname
    TYPE fieldname,
    l_PROG TYPE string,
    v_mess TYPE string,
    l_sid TYPE string,
    wa_ddfields TYPE dntab.
    DATA i_tab TYPE STANDARD TABLE OF string.
    DATA:l_str TYPE string,
    l_str1 TYPE string.
    PARAMETERS matnr type marc-matnr.
    end-of-SELECTION.
    *build the subroutine pool
    APPEND 'PROGRAM subpool.' TO i_tab.
    APPEND `LOAD-OF-PROGRAM.` TO i_tab.
    APPEND `DATA i_tab1 TYPE TABLE OF vbak.`      TO i_tab.
    APPEND `DATA l_rows TYPE i.`      TO i_tab.
    APPEND `select * into table i_tab1 from vbak.` To i_tab.
    append 'DESCRIBE TABLE i_tab1 LINES l_rows.' to i_tab.
    append 'Write :  l_rows .' to i_tab.
    GENERATE SUBROUTINE POOL i_tab NAME l_PROG
    MESSAGE v_mess
    SHORTDUMP-ID l_sid.
    IF sy-subrc = 0.
    PERFORM ('LOOP_AT_TAB') IN PROGRAM (l_PROG) IF FOUND.
    ELSEIF sy-subrc = 4.
    MESSAGE v_mess TYPE 'I'.
    ELSEIF sy-subrc = 8.
    MESSAGE l_sid TYPE 'I'.
    ENDIF.
    Edited by: vijay wankhade on Jan 1, 2009 5:34 PM
    Edited by: vijay wankhade on Jan 1, 2009 5:34 PM

  • JPA problem need help on JoinColumn, OneToMany, and ManyToOne annotations

    I made a mistake in placing a foreign key.
    but I don't really get what wrong with it
    I have followed what shown on the book
    Could somebody help me out? thanks!
    package com.h2o;
    import javax.persistence.*;
    import java.util.*;
    @Entity
    @IdClass(h2oUserId.class)
    @NamedQuery(name="findAllUsers", query="SELECT h FROM h2oUser h")
    public class h2oUser {
         @Id @GeneratedValue(strategy=GenerationType.SEQUENCE) @Column(name="H2O_ID")
         private Long id;
         @Id
         @Column ( nullable = false)
         private String email;
         @Column ( nullable = false)
         private String nickName;
         @Column ( nullable = false)
         private String password;
         private String basePath;
         private String avatorPath;
         private boolean activated;
         @Temporal(TemporalType.DATE)
         private Date createDate;
         @Transient
         private static final String LARGE = "original";
         @Transient
         private static final String SMALL = "thumbernail";
         @OneToMany(mappedBy="h2oUser")
         private Collection<ImageBase> images;
            //getters and setters
    package com.h2o;
    import javax.persistence.*;
    @Entity
    public class ImageBase {
         @Id @GeneratedValue(strategy=GenerationType.SEQUENCE)
         private Long id;
         @Column(unique=true)
         private String imgFile;
         @Column(nullable=true)
         private String imgOriginalFile;
         @ManyToOne
         @JoinColumn
         private h2oUser user;
            //getters and setters
    Caused by: org.hibernate.MappingException: Could not determine type for: com.h2o.h2oUser, at table: ImageBase, for columns: [org.hibernate.mapping.Column(user)]
         at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:304)
         at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:288)
         at org.hibernate.mapping.Property.isValid(Property.java:216)
         at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:467)
         at org.hibernate.mapping.RootClass.validate(RootClass.java:268)
         at org.hibernate.cfg.Configuration.validate(Configuration.java:1287)
         at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1729)
         at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:84)
         at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:904)
         ... 9 more

    Your solution may be there:
    http://www.insideria.com/2010/02/using-coldfusion-9-orm-in-flex.html
    Check out what Pedro did in the Flex class:
    Note the tag:
    [Entity]
    [Id]
    [ManyToOne
    ...etc...
    package com.pcsilva.insideria.one.mxml.entity
    [Bindable]
    // pointing to an entity in ColdFusion
    [RemoteClass(alias='com.pcsilva.insideria.one.cfml.entity.User')]
    // declare entity
    [Entity]
    public class User
    [Id] //statement identifier
    public var id:Number = 0; // NaN is not going to ColdFusion
    public var name:String;
    public var lastname:String;
    public var email:String;
    // statement of relationship
    [ManyToOne(targetEntity="com.pcsilva.insideria.one.cfml.entity.Group", fetchType="EAGER", cascadeType='ALL')]
    [JoinColumn(name="group_id", referencedColumnName="id")]
    // start property for use in getter groupname
    public var group:Group = new Group();
    [Transient] //add property read-only, which is not reflected in ColdFusion
    public function get fullname():String
    return name+' '+lastname;
    [Transient] //add property read-only,  simplifies access the property
    public function get groupname():String
    return group.name;

  • Problem with JPA Implementations and SQL BIGINT in primary keys

    I have a general Question about the mapping of the SQL datatype BIGINT. I discovered, that there are some different behaviour depending on the JPA implementation. I tested with TopLink Essentials (working) and with Hibernate (not working).
    Here is the case:
    Table definition:
    /*==============================================================*/
    /* Table: CmdQueueIn */
    /*==============================================================*/
    create table MTRACKER.CmdQueueIn
    CmdQueueInId bigint not null global autoincrement,
    Type int,
    Cmd varchar(2048),
    CmdState int,
    MLUser bigint not null,
    ExecutionTime timestamp,
    FinishTime timestamp,
    ExecutionServer varchar(64),
    ScheduleString varchar(64),
    RetryCount int,
    ResultMessage varchar(256),
    RecordState int not null default 1,
    CDate timestamp not null default current timestamp,
    MDate timestamp not null default current timestamp,
    constraint PK_CMDQUEUEIN primary key (CmdQueueInId)
    The java class for this table has the following annotation for the primary key field:
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name = "CmdQueueInId", nullable = false)
    private BigInteger cmdQueueInId;
    When using hibernate 3.2.1 as JPA provider I get the following exception:
    avax.persistence.PersistenceException: org.hibernate.id.IdentifierGenerationException: this id generator generates long, integer, short or string
    at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:629)
    at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:218)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:585)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:176)
    at $Proxy16.persist(Unknown Source)
    at com.trixpert.dao.CmdQueueInDAO.save(CmdQueueInDAO.java:46)
    at com.trixpert.test.dao.CmdQueueInDAOTest.testCreateNewCmd(CmdQueueInDAOTest.java:50)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:585)
    at junit.framework.TestCase.runTest(TestCase.java:154)
    at junit.framework.TestCase.runBare(TestCase.java:127)
    at
    Caused by: org.hibernate.id.IdentifierGenerationException: this id generator generates long, integer, short or string
    at org.hibernate.id.IdentifierGeneratorFactory.get(IdentifierGeneratorFactory.java:59)
    at org.hibernate.id.IdentifierGeneratorFactory.getGeneratedIdentity(IdentifierGeneratorFactory.java:35)
    at org.hibernate.id.IdentityGenerator$BasicDelegate.getResult(IdentityGenerator.java:157)
    at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:57)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2108)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2588)
    at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:48)
    at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:248)
    at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:290)
    at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:180)
    at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:108)
    at org.hibernate.event.def.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:131)
    at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:87)
    at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:38)
    at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:618)
    at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:592)
    at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:596)
    at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:212)
    ... 34 more
    This means, that their ID generator does not support java.math.BigInteger as datatype.
    But the code works if I take TopLink essentials as JPA Provider.
    Looking at the spec shows the following:
    In chapter 2.1.4 "If generated primary keys are used, only integral types will be portable." Integral datatypes are byte, short, int, long and char. This would mean, that the Hibernate implementation fits the spec but there seem to be a problem in general with BIGINT datatypes.
    I use a SYBASE database. There it is possible to declare a UNSIGNED BIGINT. The range of numbers is therefore 0 - 2^64 - 1. Since in Java a long is always signed it would mean its range is from -2^63 -1 to 2^63 -1. So a mapping of BIGINT to java.lang.long could result in an overflow.
    The interesting thing is, that I used NetBeans to reverse engineer an existing database schema. It generated for all Primary Keys of Type BIGINT automatically a java.math.BigInteger. But for other fields (not being keys) it mapped BIGINTs to java.lang.long.
    It looks like there are some problems with either the spec itself or the implementation of it. While TopLink seems to handle the problem correctly, Hibernate doesn't. But Hibernate seems to fulfill the spec.
    Is anybody familiar with the Spec reading this and can elaborate a little about this situation?
    Many thanks for your input and feedback.
    Tom

    Not sure if I clearly understand your issue, would be good if you can explain it a bit more clearly.
    "I select a value from LOV and this value don't refresh in the view"
    If you mean ViewObject, check if autoSubmit property is set to true.
    Amit

  • Using JPA Entity-Objects defined in other EJB-Development Component

    Hello Community,
    I'm working on a Java-Application on NW CE 7.1, using JEE5 Beans in the Business-Logic-Layer and WebDynpro/Java in the UI-Layer.
    I designed a Bean for working with data, stored in a database-table of the system-database.
    For that addtionally i created a class, representing the Entity-Object, in the same Development-Component of Type EJB 3.0.
    It looks like this:
    @NamedQueries ({
         @NamedQuery (name="findAllSdCust", query="SELECT c from SdCust c ORDER BY c.kdnr"),
         @NamedQuery (name="findSdCustByKdnr", query="SELECT c from SdCust c WHERE c.kdnr = :kdnr"),
         @NamedQuery (name="findSdCustByIlnnr", query="SELECT c from SdCust c WHERE c.ilnnr = :ilnnr")
    @Entity
    @Table(name="ZKALL_SD_CUST")
    public class SdCust implements Serializable {
         @Id
         @TableGenerator (name="idGenerator", table="ZKALL_ID_GEN", pkColumnName="GEN_KEY", valueColumnName="GEN_VALUE", initialValue=100)
         @GeneratedValue (strategy=GenerationType.TABLE, generator="idGenerator")
         private long id;
         private String name;
         private String lname;
         private String kdnr;
         private String ilnnr;
         private long connid;
         private long cnt;
         @Version
         private long version;
          Constructor, Getter and Setter methods follow here
    The corresponding bean looks like this
    @Stateless(name="SdCustBean")
    public class SdCustBean implements SdCustLocal {
         @PersistenceContext (unitName="xyz")
         private EntityManager em;
         public SdCust getSdCustByKdnr (String kdnr)
              SdCust result = new SdCust();
              // List<Manufacturer> resultList = new ArrayList<Manufacturer>();
              Query  myQuery = em.createNamedQuery("findSdCustByKdnr");
              myQuery.setParameter("kdnr", kdnr);
              result = (SdCust) myQuery.getSingleResult();
              return result;
         public void setEM (EntityManager iem)
              em = iem;
           // other methods .....
    After that i created a new Development-Component of Enterprise Application-Type and added above DC to this EAR-DC. I also supplied the nessecary descriptor-files/Enries in EJB-DC and EAR-DC.
    When now using this bean from WebDynpro with the Web-Dypro EJB-Model-Import everything works fine.
    The bean returns the desired object(s).
    But now i created a new DC of type EBJ 3.0
    This DC contains a Message Driven Bean. That MDB is a Job-Bean which i want to schedule. That  Bean uses JRA to connect to an SAP-Abap-System to read some Data and should use JPA to insert/upate/delete the read data in the Database. This should work as a simple replication for my application.
    I assigned that EJB-DC containing the MDB to a new EAR-DC together with job-definition-xml and the neccessary entries in deployment-descriptors.
    After deploying i see the corresponding job-defition in the NW scheduler using the administrator-views.
    I'm also able to schedule the job and it executes fine. Connecting to SAP-Abap System also works fine using JRA.
    But JPA does not work!!!!!
    I created an dependency from my EAR-DC containing the Job EJB-DC and to the EJB-DC containing the Entity-Class.
    I tried three diferent things to get i running, but all of them failed.
    1.)
    The part  looks like:
    public class MasterDataReplicateJobBean extends MDBJobImplementation implements MessageListener
      @EJB SdCustBean mybean;
       public void onJob(JobContext ctx) throws Exception {
            SdCust sdCust = mybean.getSdCustByKdnr (mykdnr);
    Compiles fine. But this fails because the Data is stored in the system-database. The exception says, that i have to use a datasource which supports 2-Phase commit. I know, that i could possibly solve this problem by annotation the Method getSdCustByKdnr with the Annotation for the Transaction-Manager to use REQUIRES_NEW Transaction. But i dont want to generally annotate my methods this way.
    2.)
    This part looks like this
    public class MasterDataReplicateJobBean extends MDBJobImplementation implements MessageListener
    @PersistenceContext (unitName="xyz")
    private EntityManager em;
       public void onJob(JobContext ctx) throws Exception {
         SdCust cust = new SdCust();
         Query  myQuery = em.createQuery("SELECT c from SdCust c WHERE c.kdnr = :kdnr");
         myQuery.setParameter("kdnr", dbkdnr);
         cust = (SdCust) myQuery.getSingleResult();
    This also results in a runtime-exception because the entity-Manager cant resolve SdCust from the Query as an Object. The Exception is:
    java.lang.IllegalArgumentException: line 1: Abstract Schema Type 'SdCust' doesn't exist
    SELECT c from SdCust c WHERE c.kdnr = :kdnr
    3.) and last try so far:
    public class MasterDataReplicateJobBean extends MDBJobImplementation implements MessageListener
    @PersistenceContext (unitName="xyz")
    private EntityManager em;
       public void onJob(JobContext ctx) throws Exception {
         SdCustBean custBean = new SdCustBean();
         custBean.setEM(em);
         SdCust cust = custBean.getSdCustByKdnr(kdnr);
    In this example i use the Bean from the beginning not as a bean itself but as a normal class. that class has an addtional Method setEM to set the Entity-Manager (which is injected when using the class as a bean)
    In that way i got the exception, that the named Query "findSdCustByKdnr" cannot be found by the entity-manager.
    It seems to me, that i can access the class, but that all annotations belonging to JPA for that class are not recognized.
    Does anybody can give me a hint to solve this problem? Did i forgot something important?
    best regards
    matthias hayk
    Edited by: Matthias Hayk on Feb 5, 2009 9:38 AM

    I was already on wright trace.
    My class "SdCust" was not recognized by the Entity-Manager as an Entity-Class.
    This relies on the storage of the entity-class and where the Entity-Manager looks for entity-classes.
    By default it seems to look for all classes in the same jar file. thats the reason why everything works fine when the using bean and the entity-class are in the same project.
    In my last case, the using bean is in another  development-component and so also in anohter jar file. in this case the entity-manager must be told where to find entity-classes.
    this is done in the persistence.xml file.
    i added the line
    <jar-file>xxx.yyy.com~mdata_beans.jar</jar-file>
    underneath the <persistence-unit>-tag.
    This works.
    regards
    Matthias Hayk

  • GenerationType.AUTO doesn't work correctly with Kodo and MySQL

    Greetings,
    I'm migrating applications from JBoss/Hibernate to WebLogic/Kodo. The following column annotation:
    @Id
    @Column(name="CUSTOMER_ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    public long getCustomerId()
    is supposed to generate auto-increment primary key in mysql. This is what happens with Hibernate. With Kodo, this seems to be equivalent with GenerationType.TABLE as a table named openjpa_sequence_table is created, containing sequence values. So what should one do in order to be able to use true auto-increment strategy with MySQL and Kodo ?
    Many thanks in advance,
    Nicolas

    Hi Nicolas,
    By setting the generation strategy to AUTO, you're essentially letting the JPA provider choose which strategy to use. It looks like Kodo is using the TABLE strategy by default and Hibernate is using the IDENTITY strategy here. You can set the strategy to IDENTITY if you want Kodo to behave similarly to Hibernate. However, it's worth pointing out that there may be a reason for Kodo not using the IDENTITY strategy by default.
    The docs at: http://edocs.bea.com/wls/docs103/kodo/full/html/ref_guide_pc_oid.html#ref_guide_pc_oid_pkgen_autoinc
    point out the following:
    "Statements inserting into tables with auto-increment / identity columns cannot be batched. After each insert, Kodo must go back to the database to retrieve the last inserted auto-increment value to set back in the persistent object. This can have a negative impact on performance. "
    - Matt

Maybe you are looking for

  • Authentication issue with 4.1

    We are using a custom authentication scheme. It calls the authenticatin api to authenticate agains active directory. It is working in multiple apex aplications in apex version 3.2. We created a new install of 4.1 and imported the apps from 3.2 I can'

  • Do i need a codec for avi files to play in flv

    i have no mpeg moves files on my computer so when it says browse for your flv file it shows me nothing right. i have to have flv files already encoded for them to view on my computer right.

  • Pipeline Performance Management Data

    Hi, Does anyone know if there is any way we could enhance the data that is displayed in the Pipeline Report. Currently it works by displaying either your own opportunities or your teams opportunities if you are a manager. We have a requirement where

  • Admin Server start failure-Error running init function load-modules

    Hi, run start-admin, I get: SunONE-WebServer-Enterprise/6.0SP3 B05/14/2003 18:31 failure: server exit: status 1 (Interrupted system call) in log file, it said: [07/Nov/2005:12:34:12] info (215932): successful server startup [07/Nov/2005:12:34:12] inf

  • I cant remember my icould user id

    i tried several times to key in an incorrect password it was disabled for a couple of times. and then when i entered the right password its now asking me to enter backup and i just remembered that im not the type of person who keeps on backing up my