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;
}

Similar Messages

  • 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

  • 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

  • JPA: Issue with loading One To Many relation

    Hi All,
    I have a One to Many relation mapped as below
    @Entity
    @Table(name="ACCOUNT_TABLE")
    public class UserAccount {
         // Attributes
         @Id
         @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="USER_SEQ")
         @SequenceGenerator(name="USER_SEQ", sequenceName="USERS_SEQ",allocationSize=1)
         @Column(name="CLIENT_ID")
         private Long clientId;
         @Column(name="USER_ID")
         private String userId;
         @OneToMany(fetch=FetchType.LAZY, mappedBy="userAccount")
         @JoinColumn(name="USER_ID", referencedColumnName="USER_ID", insertable=false, updatable=false)
         private List<UserRole> assignedRoles;
    @Entity
    @Table(name = "ROLE_TABLE")
    public class UserRole extends BaseEntity implements Serializable {
         private static final long serialVersionUID = -1651953276532642312L;
         @Id
         @Column(name = "USER_ID", length = 30, nullable=false, insertable=false, updatable=false)
         private String userId;
         @Column(name = "BUSINESS_CODE", length = 10, nullable=false, insertable=false, updatable=false)
         private String businessCode;
         @Column(name = "ROLE_NAME", length = 30, nullable=false, insertable=false, updatable=false)
         private String roleName;
         @ManyToOne()
         @JoinColumn(name="USER_ID", referencedColumnName="USER_ID", insertable=false, updatable=false)
         private UserAccount userAccount;
    As you may have noticed, the tables are not joined on the Primary key of parent. This is legacy schema and I have to work with it.
    Account and Role are joined by the USER_ID column. This I specified by providing JoinColumn.
    Then I have a DAO to retrieve the relation based on user id.
    public class UserAccountDAOJPAImpl UserAccountDAO{
         private static final String USER_ACCOUNT_BY_USERID = "select distinct ua " +
         "from UserAccount ua " +
         "left outer join fetch ua.assignedRoles ar " +
         "where ua.userId = ?1 ";
         public UserAccount findByUserName(String userName){          
              UserAccount userAccount=null;
              List<UserAccount> userAccounts =null;
         Query query = this.entityManager.createQuery(USER_ACCOUNT_BY_USERID);
         query.setParameter(1, userName.toUpperCase());
         userAccounts = query.getResultList();
         if(!userAccounts.isEmpty()) {
              userAccount=userAccounts.get(0);
              return userAccount;
    When I test this code ( for the user Id I used in test there are 11 roles )
    The SQL generated is correct, when I run the SQL in PL/SQL Developer, it returns the results as expected.
    But the DAO method above returns one UserAccount object with List of 11 UserRole objects as expected. But all of these 11 UserRole objects are same, where as the query returns 11 different roles.
    I couldn't figure out what I was doing wrong.
    Any help is appreciated.
    thanks,
    Raghavan

    @OneToMany(fetch=FetchType.LAZY, mappedBy="userAccount")
    @JoinColumn(name="USER_ID", referencedColumnName="USER_ID", insertable=false, updatable=false)
    private List<UserRole> assignedRoles;
    }What do you get when you remove this @JoinColumn annotation? It shouldn't be necessary. (user_id seems a little suspect as the join column name by the way, I would have expected role_id here...)

  • Is it possible to Deploy a SSIS package to catalog with a Sql Server Identity in SQL Server 2012 programmly ?

    Hi,
    how can I deploy a SSIS package with a SQL SERVER identity to the catalog in SQL Server 2012 programmly?
    I tried to use the [SSISDB].[catalog].[deploy_project], but the error said that it could only be used with a WINDOWS identity.
    This question has worried me for days.
    Is there any way to make the catalog.deploy_project available for a SQL SERVER identity ?
    Or just an new solution instead of using the catalog.deploy_project?
    best wishes from Qingyuan Lee.

    Sorry, my description may be confusable.
    I use EXECUTE AS , not EXECUTE WITH, to solve the problem.
    In fact,  I don't care about the authority.
    I want to execute the stored procedure using a SQL SERVER Authentication Account , since my codes run on a linux OS and it is hard to connect to SSIS using a Windows Authentication Account.
    so, using EXECUTE AS to change the execution context is accaptable.
    The requirement for a Windows Authentication Account makes sense.
    I consider that the SSIS executes outside the context of SQL Server and as part of an OS process, which means that a Windows account is necessary in order to deploy a package.
    Thanks very much for your help.

  • Not Working-central web-authentication with a switch and Identity Service Engine

    on the followup the document "Configuration example : central web-authentication with a switch and Identity Service Engine" by Nicolas Darchis, since the redirection on the switch is not working, i'm asking for your help...
    I'm using ISE Version : 1.0.4.573 and WS-C2960-24PC-L w/software 12.2(55)SE1 and image C2960-LANBASEK9-M for the access.
    The interface configuration looks like this:
    interface FastEthernet0/24
    switchport access vlan 6
    switchport mode access
    switchport voice vlan 20
    ip access-group webauth in
    authentication event fail action next-method
    authentication event server dead action authorize
    authentication event server alive action reinitialize
    authentication order mab
    authentication priority mab
    authentication port-control auto
    authentication periodic
    authentication timer reauthenticate server
    authentication violation restrict
    mab
    spanning-tree portfast
    end
    The ACL's
    Extended IP access list webauth
        10 permit ip any any
    Extended IP access list redirect
        10 deny ip any host 172.22.2.38
        20 permit tcp any any eq www
        30 permit tcp any any eq 443
    The ISE side configuration I follow it step by step...
    When I conect the XP client, e see the following Autenthication session...
    swlx0x0x#show authentication sessions interface fastEthernet 0/24
               Interface:  FastEthernet0/24
              MAC Address:  0015.c549.5c99
               IP Address:  172.22.3.184
                User-Name:  00-15-C5-49-5C-99
                   Status:  Authz Success
                   Domain:  DATA
           Oper host mode:  single-host
         Oper control dir:  both
            Authorized By:  Authentication Server
               Vlan Group:  N/A
         URL Redirect ACL:  redirect
             URL Redirect: https://ISE-ip:8443/guestportal/gateway?sessionId=AC16011F000000510B44FBD2&action=cwa
          Session timeout:  N/A
             Idle timeout:  N/A
        Common Session ID:  AC16011F000000490AC1A9E2
          Acct Session ID:  0x00000077
                   Handle:  0xB7000049
    Runnable methods list:
           Method   State
           mab      Authc Success
    But there is no redirection, and I get the the following message on switch console:
    756005: Mar 28 11:40:30: epm-redirect:IP=172.22.3.184: No redirection policy for this host
    756006: Mar 28 11:40:30: epm-redirect:IDB=FastEthernet0/24: In epm_host_ingress_traffic_qualify ...
    I have to mention I'm using an http proxy on port 8080...
    Any Ideas on what is going wrong?
    Regards
    Nuno

    OK, so I upgraded the IOS to version
    SW Version: 12.2(55)SE5, SW Image: C2960-LANBASEK9-M
    I tweak with ACL's to the following:
    Extended IP access list redirect
        10 permit ip any any (13 matches)
    and created a DACL that is downloaded along with the authentication
    Extended IP access list xACSACLx-IP-redirect-4f743d58 (per-user)
        10 permit ip any any
    I can see the epm session
    swlx0x0x#show epm session ip 172.22.3.74
         Admission feature:  DOT1X
         ACS ACL:  xACSACLx-IP-redirect-4f743d58
         URL Redirect ACL:  redirect
         URL Redirect:  https://ISE-ip:8443/guestportal/gateway?sessionId=AC16011F000000510B44FBD2&action=cwa
    And authentication
    swlx0x0x#show authentication sessions interface fastEthernet 0/24
         Interface:  FastEthernet0/24
         MAC Address:  0015.c549.5c99
         IP Address:  172.22.3.74
         User-Name:  00-15-C5-49-5C-99
         Status:  Authz Success
         Domain:  DATA
         Oper host mode:  multi-auth
         Oper control dir:  both
         Authorized By:  Authentication Server
         Vlan Group:  N/A
         ACS ACL:  xACSACLx-IP-redirect-4f743d58
         URL Redirect ACL:  redirect
         URL Redirect:  https://ISE-ip:8443/guestportal/gateway?sessionId=AC16011F000000510B44FBD2&action=cwa
         Session timeout:  N/A
         Idle timeout:  N/A
         Common Session ID:  AC16011F000000160042BD98
         Acct Session ID:  0x0000001B
         Handle:  0x90000016
         Runnable methods list:
         Method   State
         mab      Authc Success
    on the logging, I get the following messages...
    017857: Mar 29 11:27:04: epm-redirect:IDB=FastEthernet0/24: In epm_host_ingress_traffic_qualify ...
    017858: Mar 29 11:27:04: epm-redirect:epm_redirect_cache_gen_hash: IP=172.22.3.74 Hash=271
    017859: Mar 29 11:27:04: epm-redirect:IP=172.22.3.74: CacheEntryGet Success
    017860: Mar 29 11:27:04: epm-redirect:IP=172.22.3.74: Ingress packet on [idb= FastEthernet0/24] matched with [acl=redirect]
    017861: Mar 29 11:27:04: epm-redirect:IDB=FastEthernet0/24: Enqueue the packet with if_input=FastEthernet0/24
    017862: Mar 29 11:27:04: epm-redirect:IDB=FastEthernet0/24: In epm_host_ingress_traffic_process ...
    017863: Mar 29 11:27:04: epm-redirect:IDB=FastEthernet0/24: Not an HTTP(s) packet
    What I'm I missing?

  • SAP WM: Mixed pallet with putaway strategy "P"

    Dear Experts,
    I am using putaway strategy P for a storage type and I have given X for Mixed storage field.
    I am not able to put multiple batches of same material in one bin, is it possible with putaway strategy P
    I am not using SU management.
    Thanks in advance,
    Amit Kumar

    This is from a WM colleague:
    First it will always look at same bin as a material is stored
    with put away strategy “I”. 
    This scenario is completely wrong, if I understand it right.
    He/she needs to look at the bin strategy for the SU types
    defined in the LE qty. / SUT types for bin type.
    Strategy “I” is for addition to stock like they said.
    Capacity check 2 only works if it is SUT active, which they say it is
    not.  Not the check flag, but the SUT.
    The strategy for SUT type allowed to bin type only works if it
    is SUT managed, which they say it is not.
    The strategy just doesn’t seem right.  If they do not use
    SU’s, the only capacity check that works is max from the material master (WM-1
    view) weight “1”.
    The bin type / SUT strategy will not work unless they are using
    SUT’s for storage.  Not just the LE qty. in the SUT defined.
    If they aren’t using SUTs for storage, it is only a quant.
    Noting is configurable for strategy of quant to storage bin type.

  • Send purchase order e-mail with release strategy

    Hi!!
    I have a problem with sending e-mails in purchase order that are blocked with release strategy.
    I create a purchase order that is block for the release strategy, then I release it. This is working OK, but I can't send an e-mail with this released puchase order, to do it, I have to modify something in the purchase order.
    Somebody knows what is happening?
    I would like to send e-mails without previous modification of the purchase order.
    Thanks for your help.

    Hi,
    Purchase order via e-mail in SAP sys,the configurations and pre-requisites are follow:
    1. You must maintain an e-mail address in the address in the vendor master.
    2. The same applies to your own user master. You also have to specify an e-mail address there in order to identify the sender.
    Note that it is not possible to change the e-mail address of the vendor via the SAP purchase order transaction (ME21N, ME22N, and so on). The system only uses the e-mail address of the vendor that is maintained in the vendor master!
    3. For the output type for default values, a communication strategy needs to be maintained in the Customizing that supports the e-mail. You can find the definition of the communication strategy in the Customizing via the following path: (SPRO -> IMG -> SAP Web Application Server -> Basic Services -> Message Control -> Define Communication Strategy). As a default, communication strategy CS01 is delivered. This already contains the necessary entry for the external communication. Bear in mind that without a suitable communication strategy it is not possible to communicate with a partner via Medium 5 (external sending).
    4. Use the standard SAP environment (program 'SAPFM06P', FORM routine 'ENTRY_NEU' and form 'MEDRUCK') as the processing routines.
    5. In the condition records for the output type (for example, Transaction MN04), use medium '5' (External send).
    6. You can use Transaction SCOT to trigger the output manually. The prerequisite for a correct sending is that the node is set correctly. This is not described here, but it must have already been carried out.
    7. To be able to display, for example, the e-mail in Outlook, enter PDF as the format in the node.
    For more details, check SAP note:191470
    Regards,
    Biju K

  • Howto initialize JPA attribute with database sysdate?

    Hi,
    we have the problem that we are required to initialize a "created" attribute of our TopLink JPA POJOs with the current SYSDATE of the Database (as there is a time difference between Application Server and Database Server). For this reason, we cannot simply set the value in the constructor of the Java object.
    Is there any approach to solve this issue?
    regards,
    hans

    In general be careful in doing this if you are concerned with performance, as accessing the database for the current time can be expensive. Normally the Application Server time should be sufficient.
    You have a few options for accessing the database time.
    - You could query the SYSDATE from the database in your application code when you create your object.
    - You could use a TopLink or JPA insert event to query the SYSDATE from the database to populate your object.
    - If you are using TopLink you could use the ReturningPolicy to access the "created" field from the database on insert, and assign the field in the database table using a trigger. The ReturningPolicy is only available in TopLink, not TopLink Essentials.

  • DataCache NPE with generation strategy=IDENTITY

    When I try to persist an entity whose ID is generated with the JPA IDENTITY strategy, everything works fine except a NPE is thrown when trying to cache the newly persisted entity. Disabling the DataCache fixes the problem.
    java.lang.NullPointerException: null keys not allowed
    at com.solarmetric.apache.commons.collections.map.AbstractReferenceMap.put(AbstractReferenceMap.java:248)
    at com.solarmetric.util.EfficientEmptyReferenceMap.put(EfficientEmptyReferenceMap.java:43)
    at com.solarmetric.apache.commons.collections.set.MapBackedSet.add(MapBackedSet.java:110)
    at com.solarmetric.util.ReferenceSet.add(ReferenceSet.java:59)
    at kodo.datacache.ClassRefCacheMap.entryAdded(ClassRefCacheMap.java:136)
    at kodo.util.CacheMap.put(CacheMap.java:402)
    at kodo.datacache.DataCacheImpl.putInternal(DataCacheImpl.java:109)
    at kodo.datacache.AbstractDataCache.putAllInternal(AbstractDataCache.java:420)
    at kodo.datacache.AbstractDataCache.commit(AbstractDataCache.java:98)
    at kodo.datacache.DataCacheStoreManager.updateCaches(DataCacheStoreManager.java:222)
    at kodo.datacache.DataCacheStoreManager.commit(DataCacheStoreManager.java:66)
    at kodo.kernel.DelegatingStoreManager.commit(DelegatingStoreManager.java:98)
    at kodo.kernel.BrokerImpl.endStoreManagerTransaction(BrokerImpl.java:1484)
    at kodo.kernel.BrokerImpl.endTransaction(BrokerImpl.java:2536)
    at kodo.kernel.BrokerImpl.afterCompletion(BrokerImpl.java:2182)
    at kodo.kernel.LocalManagedRuntime.commit(LocalManagedRuntime.java:85)
    at kodo.kernel.BrokerImpl.commit(BrokerImpl.java:1546)
    at kodo.kernel.DelegatingBroker.commit(DelegatingBroker.java:1250)
    at kodo.persistence.EntityManagerImpl.commit(EntityManagerImpl.java:451)
    at figbird.cms.application.DAO.getRootItem(DAO.java:160)
    The stack trace shows that the entity is INSERTed and it's id fetched, but it seems that somehow this identity is not being set property:
    FINEST: <t 2791549, conn 26179329> [2 ms] executing prepstmnt 10891966 INSERT INTO FB_PRIVILEGES (comment, inheritable, level, role, type, username, item_uuid) VALUES (?, ?, ?, ?, ?, ?, ?) [params=(null) null, (boolean) true, (int) 200, (String) *, (String) *, (String) *, (long) 1] [reused=2]
    Jun 30, 2006 11:38:48 AM com.solarmetric.log.CommonsLogFactory$LogAdapter trace
    FINEST: <t 2791549, conn 26179329> [47 ms] executing prepstmnt 21849501 SELECT CURRVAL('FB_PRIVILEGES_id_SEQ') [reused=2]
    Ninth Avenue Software
    http://www.ninthavenue.com.au

    I can reproduce this behaviour with application-identity and autoassign value-strategy. Disabling the DataCache fixes the problem here, too.
    however, calling the getter of a newly persisted Objekt's id, or doing a query, both BEFORE i commit the transaction, fixes the problem also.
    This happens both for kodo 4.0.0 and 4.0.1

  • JPA GenerationType.IDENTITY

    Hello,
    is there any way how to persuade Toplink Essentials to use SCOPE_IDENTITY() instead of @@IDENTITY for returning identity vaues of newly inserted (persisted) objects?
    My problem is that the target table on MS SQL server has insert trigger which inserts records to another table. Thus @@IDENTITY returns wrong value.
    Thanks for any advice.
    Pavel Zelenka

    Thanks. I presume it requires EclpseLink. However I switched JPA provider to EclipseLink
    made new classs
    public class MySQLServerPlatform extends SQLServerPlatform {
    @Override
    public ValueReadQuery buildSelectQueryForIdentity() {
    ValueReadQuery valueReadQuery = new ValueReadQuery("select scope_identity()");
    return valueReadQuery;
    added <property name="eclipselink.target-database" value="cz.mediaservis.metro.entity.MySQLServerPlatform"/> to persistence.xml
    and after persisting I got exception
    Exception [EclipseLink-4011] (Eclipse Persistence Services - 1.1.0.r3634): org.eclipse.persistence.exceptions.DatabaseException
    Exception Description: Error preallocating sequence numbers. The sequence table information is not complete.
    Probably I did something wrong. Could you plese help?
    Thx

  • How do I delete cascade with a PL/SQL procedure?

    This script will create a PL/SQL procedure that deletes cascade. This is a post to contribute to the Oracle community. Take the code as is and test it before you use it in production. Make sure this is what you want.
    Procedure Delete Cascade (prc_delete_cascade)
    Description
    =============
    The principle is very simple. The procedure uses a table called TO_BE_DELETED to keep a list of records to be deleted. This
    table keeps the table name and the rowid of those records that need to be deleted. The procedure also uses a function called
    DELETE_BOTT_ROW which takes one record of the table and tries to delete it. If the deletion fails with a foreign key constraint
    violation, the function parses the SQL error message (SQLERRM) to get the name of the constraint. With the name of the constraint,
    the function finds the name of the child table, all the child records that have references to the parent table primary or unique key,
    and the parent key primary or unique key column name. Once the child records of the failed delete are identified, the function takes their table name and rowids
    and records them into the TO_BE_DELETED table by inserting records of their table name and their rowids. Al the records inserted also contain the level (which
    is 1 for the original records, 2 for child records, 3 for granchild records, etc.) and the sequence number of the order in wich they
    are recorded. This way, when the function picks up a record to be deleted, it takes the one with the highest level and the highest
    inserted sequence, or the "bottom" record. Once all the child records of the failed delete are appended to the TO_BE_DELETED table, it calls itself
    recursevely, and the function takes the record at the "bottom" of the table and tries to delete it. If it succeeds, it calls
    itself recursevely to delete the next record. If it fails, it goes and finds the child records as described before and once they are
    inserted into the TO_BE_DELETED table, it calls itself again recursevely to try to delete again the "bottom" record. All records
    that are successfully deleted are flagged as deleted usig the flag_del column so they are not pickt up again. Once all the (parent,
    child, grandchild, etc.) records are deleted, the procedure ends without commiting, giving the option to the user to commit or
    rollback deletions. The table TO_BE_DELETED is, at the end of the procedure, a list of all the records that were deleted, including their table names
    and the order in with they were deleted. The user then can review its content and decide to commit or rollback.
    Restrictions
    ============
    1. Single tables only. The procedure only takes one table name and a WHERE clause to identified the records to be deleted.
    2. Single columns only. Ther procedure only works with single-column primary, unique and foreign key constraints.
    3. Single schema only.
    4. Unpredictable results with circular references.
    drop table to_be_deleted purge;
    create table to_be_deleted
    (tname varchar2(30)       -- table name
    ,rid rowid                -- rowid
    ,lvl number               -- level: 1=parent, 2=child, 3=grandchild, etc.
    ,seq_ins number           -- sequence order of record inserted
    ,flg_del char             -- flag deleted: Y=record deleted
    ,seq_del number           -- global order of record deletion
    set serveroutput on size 1000000
    create or replace procedure prc_delete_cascade
    (p_tname varchar2  -- table name
    ,p_where varchar2  -- where clause identifying records to be cascade deleted
    is
      dummy         char;
      v_sqlcode     number;
      v_sqlerrm     varchar2(32767);
      v_param_val   integer := 0;
      v_sql         varchar2(4000);
      v_ret_cde     number;
      e_bad_params  exception;
      v_iter        number;
      v_plvl        number;
      v_seq_del     number;
      v_max_iter    number := 1000000000;
      function delete_bott_row
      return number
      is
        v_sql        varchar2(4000);
        v_ptname     varchar2(30);  -- parent table name
        v_ppkname    varchar2(30);  -- parent primary key constraint name
        v_ppkcname   varchar2(30);  -- parnet primary key column name
        v_prowid      rowid;
        v_crowid      rowid;
        v_ctname     varchar2(30);  -- child table name
        v_cfkname    varchar2(30);  -- child foreign key constraint name
        v_cfkcname   varchar2(30);  -- child foreign key column name
        v_ins        number;
        v_seq_ins    number;
        v_sqlerrm    varchar2(4000);
        v_sqlcode    number;
        e_const_viol exception;
        pragma exception_init(e_const_viol, -2292);
        e_max_iter_reached exception;
      begin
        v_iter := v_iter + 1;
        if v_iter >= v_max_iter then
          raise e_max_iter_reached;
        end if;
        dbms_output.put_line('- Iter '||to_char(v_iter));
        dbms_output.put_line('----------');
        dbms_output.put_line('- Starting function delete_bott_row');
        v_sql := 'select tname, rid, lvl, seq_ins from (select * from to_be_deleted where flg_del = ''N'' order by lvl desc, seq_ins desc) where rownum=1';
        --  dbms_output.put_line('- SQL: '||v_sql);
        execute immediate v_sql into v_ptname, v_prowid, v_plvl, v_seq_ins;
        dbms_output.put_line('- Selected row: table name: '||v_ptname||', level: '||v_plvl||', seq: '||v_seq_ins);
        v_sql := 'delete from '||v_ptname||' where rowid='''||v_prowid||'''';
        dbms_output.put_line('- SQL: '||v_sql);
        execute immediate v_sql;
        dbms_output.put_line('- Row deleted !!!');
        v_ret_cde := 1;
        v_seq_del := v_seq_del + 1;
        dbms_output.put_line('- Mark the row deleted');
        v_sql := 'update to_be_deleted set flg_del = ''Y'', seq_del = '||to_char(v_seq_del)||' where tname='''||v_ptname||''' and rid='''||v_prowid||'''';
        -- dbms_output.put_line('- SQL: '||v_sql);
        execute immediate v_sql;
        -- dbms_output.put_line('- Updated table to_be_deleted, row marked deleted');
        -- dbms_output.put_line('- End of iter '||to_char(v_iter));
        dbms_output.put_line('----------');
        -- call function delete_bott_row recursively
        v_ret_cde := delete_bott_row;
        return 0;
      exception
        when no_data_found then
          dbms_output.put_line('- Table to_be_deleted is empty, delete cascade has completed successfully.');
          v_ret_cde := 0;
          return 0;
        when e_const_viol then
          v_sqlcode := SQLCODE;
          v_sqlerrm := SQLERRM;
          v_ret_cde := v_sqlcode;
          dbms_output.put_line('>Constraint Violation. Record has children');
          -- dbms_output.put_line('Error code: '||to_char(v_sqlcode));
          v_cfkname := substr(v_sqlerrm,instr(v_sqlerrm,'.')+1,instr(v_sqlerrm,')') - instr(v_sqlerrm,'.')-1);
          dbms_output.put_line('>Child FK name: '||v_cfkname);
          select table_name, column_name
            into v_ctname, v_cfkcname
            from user_cons_columns
           where constraint_name=v_cfkname;
          dbms_output.put_line('>Child table name: '||v_ctname||'. FK column name: '|| v_cfkcname);
          select constraint_name, column_name
            into v_ppkname, v_ppkcname
            from user_cons_columns
           where constraint_name = (select r_constraint_name
                                      from user_constraints
                                      where constraint_name=v_cfkname);
          dbms_output.put_line('>Parent PK/UK name: '||v_ppkname||'. Parent PK/UK column: '||v_ppkcname);
          v_sql := 'insert into to_be_deleted(tname, rid, lvl, seq_ins, flg_del) '||
                   'select '''||v_ctname||''', rowid, '||to_char(v_plvl+1)||', rownum, ''N'' '||
                   'from '||v_ctname||' '||
                   'where '||v_cfkcname||' =any (select '||v_ppkcname||' from '||v_ptname||' where rowid =any (select rid from to_be_deleted where tname = '''||v_ptname||'''))';
          -- dbms_output.put_line('- SQL: '||v_sql);
          execute immediate v_sql;
          select count(*)
            into v_ins
            from to_be_deleted
           where lvl = v_plvl+1
             and tname = v_ctname
             and flg_del = 'N';
          dbms_output.put_line('>Found '||to_char(v_ins)||' child records which were added to table to_be_deleted');  
          v_ret_cde := delete_bott_row;
          return  v_ret_cde;
        when e_max_iter_reached then
          dbms_output.put_line('Maximum iterations reached.  Terminating procedure.');
          raise;
        when others then
          raise;
      end delete_bott_row;
    begin
      dbms_output.put_line('Beginning');
      dbms_output.put_line('================================');
      -- validate p_table
      begin
        select 'Y'
          into dummy
          from user_tables
         where table_name=upper(p_tname);
      exception
        when no_data_found then
        v_param_val := 1;
        dbms_output.put_line('Table '||p_tname||' does not exist.');
        raise e_bad_params;
      end;
      dbms_output.put_line('- Parameter p_tname validated');
      -- validate p_where
      begin
        execute immediate 'select ''Y'' from '||p_tname||' where '||p_where INTO dummy;
      exception
        when no_data_found then  -- where clause returns no records
          dbms_output.put_line('Record(s) not found.  Check your where clause parameter');
          v_param_val := 2;
          raise e_bad_params;
        when too_many_rows then  -- found multiple records means it is ok
          null; 
        when others then  --  any other records means where clause has something wrong.
          dbms_output.put_line('Where clause is malformed');     
          v_param_val := 2;
          raise e_bad_params;
      end;   
      dbms_output.put_line('- Parameter p_where validated');
      if v_param_val > 0 then raise e_bad_params; end if;
      v_iter := 0;
      v_plvl := 1;
      v_seq_del := 0;
      v_sql := 'insert into to_be_deleted(tname, rid, lvl, seq_ins, flg_del) select '''||upper(p_tname)||''', rowid, '||to_char(v_plvl)||', rownum, ''N'' from '||p_tname||' where '||p_where;
      dbms_output.put_line('- Inserting initial record');
      dbms_output.put_line('- SQL: '||v_sql);
      execute immediate v_sql;
      dbms_output.put_line('- Record(s) inserted');
      dbms_output.put_line('- Calling function delete_bott_row to delete last row of table to_be_deleted');              
      dbms_output.put_line('-----------------------------------');              
      v_ret_cde :=  delete_bott_row;
      -- dbms_output.put_line('- Back from function delete_bott_row');              
      -- dbms_output.put_line('Return code: '||to_char(v_ret_cde));              
      dbms_output.put_line('- End of procedure');              
    exception
      when e_bad_params then
        dbms_output.put_line('Bad parameters, exiting.');
    end;
    show errors
    spool prc_delete_cascade.log
    --  Call to the procedure
    exec prc_delete_cascade('xent','xent_id between 1669 and 1670')
    select tname "Table Name", count(*) "Rows deleted"
      from to_be_deleted
    group by tname;
    spool off
    set lines 120
    select *
      from to_be_deleted
    order by seq_del;
    prompt  Now commit or rollaback deletions.
    -- commit;
    -- rollback;Edited by: Rodolfo4 on Mar 23, 2011 10:45 AM

    Interesting.
    I see a few areas where this could be useful. Elimiating specific test records from a Test DB for example.
    Some comments:
    <li>Since this is a recursive logic you must add a stop criteria. In this case I would add a max iteration variable. If that one is reached, raise an error message and let the procedure stop with that error.</li>
    <li>The when others exception at the end should be removed completely</li>
    <li>The when others exception in the middle should be replaced by a specific exception that handles the -2292 error</li>
    <li>A list of tables where no record should be deleted could be usefull. If the logic would encounter such a table, it should also stop. This would be to prevent that data from some system critical tables could be deleted per accident.</li>
    <li>The reference from the FK constraint to the PK constraint should include the table name and if possible the owner (as long as you use user_* views the owner is always the same. But we could extend this to the ALL_* views). I never met a system where different tables have the identical FK constraint names, however just make this fool proof.</li>

  • JPA and SQL Server 2005's  Identity Don't Play Nice

    I am hoping someone with a little more senior knowledge of JPASQL Server 2005 can point me in the right direction involving SQL Server 2005.
    What I am discovering is JPA and SQL Server 2005 do not playing nice together when you use the IDENTITY capability for
    a primary key. Let me explain. "...when using the IDENTITY as the generator type, the value for the identity field MAY NOT be
    available BEFORE the entity data is saved in the database because typically it is generated when a record is committed."
    My problem is this.
    I have two separate entities using another entity, for example a car has a wheel and a truck has a wheel. I can go through the steps
    of persisting the car and the wheel with no problem. My problem begins when I try to
    find the wheel (by wheel description) for the truck. The query finds the wheel, but does not return the primary key for wheel.
    Therefore, using the PK inside a query generates this error:
    java.lang.IllegalArgumentException: An instance of a null PK has been incorrectly provided for this find operation. What has been my appraoch to get the entity to commit to the database is to use the following sequence for the Entity Manager.
    entityManager.persist(wheel);
    entityManager.flush(); I have assumed to this point this action would persist my data because I have been able to retrieve the PK immidately after these steps.
    However, multiple actions taking place within the same transaction, appears to render the persist and flush steps useless. My initial thought
    is to wrap the wheel creation within a new transaction so when the method/transaction completes, the data would be in the database. This
    has not worked.
    I hope I have explained this clear for others to follow. I apologize in advance if I have not. Any suggestions are greatly appreciated.

    I am hoping someone with a little more senior knowledge of JPASQL Server 2005 can point me in the right direction involving SQL Server 2005.
    What I am discovering is JPA and SQL Server 2005 do not playing nice together when you use the IDENTITY capability for
    a primary key. Let me explain. "...when using the IDENTITY as the generator type, the value for the identity field MAY NOT be
    available BEFORE the entity data is saved in the database because typically it is generated when a record is committed."
    My problem is this.
    I have two separate entities using another entity, for example a car has a wheel and a truck has a wheel. I can go through the steps
    of persisting the car and the wheel with no problem. My problem begins when I try to
    find the wheel (by wheel description) for the truck. The query finds the wheel, but does not return the primary key for wheel.
    Therefore, using the PK inside a query generates this error:
    java.lang.IllegalArgumentException: An instance of a null PK has been incorrectly provided for this find operation. What has been my appraoch to get the entity to commit to the database is to use the following sequence for the Entity Manager.
    entityManager.persist(wheel);
    entityManager.flush(); I have assumed to this point this action would persist my data because I have been able to retrieve the PK immidately after these steps.
    However, multiple actions taking place within the same transaction, appears to render the persist and flush steps useless. My initial thought
    is to wrap the wheel creation within a new transaction so when the method/transaction completes, the data would be in the database. This
    has not worked.
    I hope I have explained this clear for others to follow. I apologize in advance if I have not. Any suggestions are greatly appreciated.

  • JPA cascading using TopLink

    Hi, I am writing DAOs for one of my workflow applications. I need to write to 2 tables A and B. Table A should have only the current operational data and Table B should have the history (for reporting/metrics info) of Table A. And to build the history, whenever there is an UPDATE event on Table A, I need to capture that as an INSERT in Table B, so that at any point of time I will have a list of events happened in Table B. I am planning to use JPA annotations and cascading features using TopLink for this. I know I can cascade INSERT and DELETE from Table A to Table B. My quiestion is - Is there a way I can cascade the updates in Table A as INSERTs in Table B? Any magic that annotations or JPA or even TopLink can provide? Any help/suggestions/thoughts are highly appreciated. Thanks!

    Hi Doug, I tried implementing this with my own object and data model and also registered the handler in the persistence.xml. I am getting the following error. I am wondering if I need any additional setup to start the listener and make it work, any idea? do you have any sample test case that you had run your application with the handler? Thanks for all your help on this.
    javax.persistence.RollbackException: java.lang.NullPointerException
         at oracle.toplink.essentials.internal.ejb.cmp3.transaction.base.EntityTransactionImpl.commit(EntityTransactionImpl.java:105)
         at oracle.toplink.essentials.internal.ejb.cmp3.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:45)
         at A.B.C.dao.jpa.BaseDao.save(BaseDao.java:215)
         at A.B.C.dao.jpa.BaseDao.save(BaseDao.java:1)
         at A.B.C.dao.jpa.JpaWorkflowTests.testGetTaskReturningSingleTask(JpaWorkflowTests.java:64)
         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 org.springframework.test.ConditionalTestCase.runBare(ConditionalTestCase.java:69)
         at org.springframework.test.annotation.AbstractAnnotationAwareTransactionalTests.access$001(AbstractAnnotationAwareTransactionalTests.java:47)
         at org.springframework.test.annotation.AbstractAnnotationAwareTransactionalTests$1.run(AbstractAnnotationAwareTransactionalTests.java:115)
         at org.springframework.test.annotation.AbstractAnnotationAwareTransactionalTests.runTest(AbstractAnnotationAwareTransactionalTests.java:180)
         at org.springframework.test.annotation.AbstractAnnotationAwareTransactionalTests.runTestTimed(AbstractAnnotationAwareTransactionalTests.java:153)
         at org.springframework.test.annotation.AbstractAnnotationAwareTransactionalTests.runBare(AbstractAnnotationAwareTransactionalTests.java:111)
         at org.springframework.test.jpa.AbstractJpaTests.runBare(AbstractJpaTests.java:159)
         at org.springframework.test.jpa.AbstractJpaTests.runBare(AbstractJpaTests.java:239)
         at junit.framework.TestResult$1.protect(TestResult.java:106)
         at junit.framework.TestResult.runProtected(TestResult.java:124)
         at junit.framework.TestResult.run(TestResult.java:109)
         at junit.framework.TestCase.run(TestCase.java:118)
         at junit.framework.TestSuite.runTest(TestSuite.java:208)
         at junit.framework.TestSuite.run(TestSuite.java:203)
         at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:130)
         at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
    Caused by: java.lang.NullPointerException
         at A.B.C.model.TaskHistory.<init>(TaskHistory.java:296)
         at A.B.C.audit.TaskAuditingHandler.insertTaskHistory(TaskAuditingHandler.java:32)
         at A.B.C.audit.TaskAuditingHandler.aboutToInsert(TaskAuditingHandler.java:44)
         at oracle.toplink.essentials.descriptors.DescriptorEventManager.notifyListener(DescriptorEventManager.java:649)
         at oracle.toplink.essentials.descriptors.DescriptorEventManager.notifyListeners(DescriptorEventManager.java:679)
         at oracle.toplink.essentials.descriptors.DescriptorEventManager.executeEvent(DescriptorEventManager.java:198)
         at oracle.toplink.essentials.internal.queryframework.DatabaseQueryMechanism.insertObjectForWrite(DatabaseQueryMechanism.java:452)
         at oracle.toplink.essentials.queryframework.InsertObjectQuery.executeCommit(InsertObjectQuery.java:74)
         at oracle.toplink.essentials.internal.queryframework.DatabaseQueryMechanism.performUserDefinedWrite(DatabaseQueryMechanism.java:635)
         at oracle.toplink.essentials.internal.queryframework.DatabaseQueryMechanism.performUserDefinedInsert(DatabaseQueryMechanism.java:599)
         at oracle.toplink.essentials.internal.queryframework.DatabaseQueryMechanism.insertObjectForWriteWithChangeSet(DatabaseQueryMechanism.java:495)
         at oracle.toplink.essentials.queryframework.WriteObjectQuery.executeCommitWithChangeSet(WriteObjectQuery.java:130)
         at oracle.toplink.essentials.internal.queryframework.DatabaseQueryMechanism.executeWriteWithChangeSet(DatabaseQueryMechanism.java:283)
         at oracle.toplink.essentials.queryframework.WriteObjectQuery.executeDatabaseQuery(WriteObjectQuery.java:67)
         at oracle.toplink.essentials.queryframework.DatabaseQuery.execute(DatabaseQuery.java:609)
         at oracle.toplink.essentials.queryframework.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:536)
         at oracle.toplink.essentials.queryframework.ObjectLevelModifyQuery.executeInUnitOfWorkObjectLevelModifyQuery(ObjectLevelModifyQuery.java:123)
         at oracle.toplink.essentials.queryframework.ObjectLevelModifyQuery.executeInUnitOfWork(ObjectLevelModifyQuery.java:95)
         at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2219)
         at oracle.toplink.essentials.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:937)
         at oracle.toplink.essentials.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:894)
         at oracle.toplink.essentials.internal.sessions.CommitManager.commitNewObjectsForClassWithChangeSet(CommitManager.java:254)
         at oracle.toplink.essentials.internal.sessions.CommitManager.commitAllObjectsWithChangeSet(CommitManager.java:175)
         at oracle.toplink.essentials.internal.sessions.AbstractSession.writeAllObjectsWithChangeSet(AbstractSession.java:2638)
         at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.commitToDatabase(UnitOfWorkImpl.java:1030)
         at oracle.toplink.essentials.internal.ejb.cmp3.base.RepeatableWriteUnitOfWork.commitToDatabase(RepeatableWriteUnitOfWork.java:387)
         at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1112)
         at oracle.toplink.essentials.internal.ejb.cmp3.base.RepeatableWriteUnitOfWork.commitRootUnitOfWork(RepeatableWriteUnitOfWork.java:91)
         at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.commitAndResume(UnitOfWorkImpl.java:842)
         at oracle.toplink.essentials.internal.ejb.cmp3.transaction.base.EntityTransactionImpl.commit(EntityTransactionImpl.java:87)
         ... 30 more

  • How to get JDev 10.1.2/ADF working with MS SQL Server Identity Column

    Hello JDevTeam & JDevelopers,
    I want to use JDev/ADF with a MS SQL Server 2005 database that contains tables employing IDENTITY Columns.
    Using JDev/ADF and DBSequence with an Oracle database employing before triggers/sequences accomplishes what I am trying to do except I want to accomplish the same thing using a MSSQL Server 2005 database. Unfortunately I cannot change the database.
    I have been able to select records but I am unable to insert records (due to my lack of knowledge) when using MS/SQL Server Identity Columns with JDev/ADF.
    The following are the steps taken thus far.
    Step1: Create table named test in the 2005 MSSQL Server (see script below).
    Step2: Register 3rd Party JDBC Driver with JDeveloper; Using use Tools/Manage Libraries. Create a new entry in User Libraries with the following;
         Library Name     = Ms2005Jdbc
         Class Path     = C:\dev\Ms2005Jdbc\sqljdbc_1.0\enu\sqljdbc.jar
         (note: Latest TYPE 4 JDBC driver for Microsoft SQL Server 2005 - free at http://msdn.microsoft.com/data/ref/jdbc/)
    Step3:Create New Database Connection;
         Connection Name = testconn1
         Type = Third Party JDBC Driver
         Authentication Username = sa, Password = password, Check Deploy Password
         Connection
              Driver Class = com.microsoft.sqlserver.jdbc.SQLServerDriver     
              Library = Ms2005Jdbc     
              Classpath = C:\dev\Ms2005Jdbc\sqljdbc_1.0\enu
              URL = jdbc:sqlserver://192.168.1.151:1433;instanceName=sqlexpress;databaseName=test
         Test Connection = Success!
    Step5: Create a new application workspace using Web Application default template
    Step6: In Model project, Create new Business Components Diagram.
    Step7: Create new Entity Object. Goto to connections/testconn1, open tables and drag table test onto the diagram.
    Step8: Generate Default Data Model Components by right-clicking on Entity Object. Except all the defaults.
    When I test the Appmodule I select the view object and can scroll through all the records without error. If I try to insert a record, I get JBO-27014: Attribute testid in test is required.
    Going back to the EntityObject I deselect the Mandatory attribute and re-run the test. Now when I try to insert it accepts the value for testname but it does not update the PK testid like it would using an "JDev/ADF/DBSequence/Oracle database/before trigger/sequence" solution.
    Going back to the EntityObject and selecting refresh on insert does not solve this problem either. Changing the URL connection string and adding "SelectMethod=cursor" did not help and changing the SQl Flavor to SQLServer produced errors in the Business Components Browser. I've tried overriding isAttributeChanged() and other things as well.
    I am totally stuck! Can anyone provide a solution?
    Thanks for you help,
    BG...
    Create table named test
    use [testdb]
    go
    set ansi_nulls on
    go
    set quoted_identifier on
    go
    create table [test](
         [testid] [int] identity(0,1) not null,
         [testname] [nvarchar](50) collate sql_latin1_general_cp1_ci_as not null,
    constraint [pk_test] primary key nonclustered
         [testid] asc
    )with (pad_index = off, ignore_dup_key = off) on [primary]
    ) on [primary]

    Figured it out!
    When using the MS SQL Server 2000 Database with the MS JDBC 2000 Driver you specify the SQL Flavor to SQLServer. However setting the SQL Flavor to SQLServer with MS SQL Server 2005 Database and the MS JDBC 2005 Driver will *** fail ***.
    When working with the MS SQL Server 2005 Database and the MS JDBC 2005 Driver you set the SQL Flavor to SQL92 and the Type Map to Java.
    If using a named instance like I am you would specify the URL = jdbc:sqlserver://<db host ip address>:<listening port>;instanceName=<your instance name>;selectMethod=cursor;databaseName=<your database name> (note: leave out the < >)
    The 2005 Driver Class is different then the 2000 and is specified as com.microsoft.sqlserver.jdbc.SQLServerDriver
    Note: In a default MS SQL Server 2005 installation the listening port will change *** everytime *** the host is restarted! You can override this though.
    For the primary key you need to deselect the Mandatory attribute in the EntityObject editor.
    Set Refresh on insert/update = no.
    Set Updateable = never.
    Now my Primary Keys which get their values from the Identity Column are working with ADF in a predictable way.
    Simple enough but I have been away from this stuff for awhile.
    BG...

Maybe you are looking for

  • Linking Tables to Oracle Views

    I am not able to see the PKs in MS-ACCESS after creating a linked table to a view within Oracle. The views were created using Select * from the base table which is a materialized view. No WHERE clause in the view. Also, why do I get an error when cre

  • IPod Touch stops syncing and disappears from iTunes

    I have a problem with an iPod Touch 8GB: when connecting it to a MacBook, it starts syncing and transferring songs, but after a while it just stops syncing and disappears from iTunes. The iPod will still show "sync in progress", and it will still sho

  • Windows 7 has **bleep** terrible internet connectivy issues due to linksys router!!!

    Well, its a really long story that lasts for a total of 6 months, and I solved some of the problems, but more just kept coming.I will tell you the problems I am having now, to shorten up the story. So In late Nov of 2009 I upgraded my toshiba windows

  • Open file in internet expolorer

    I have created a jbutton, and from this i want to open a file in internet exploror. ie, c:\test.html how would i go about doing this

  • Very slow print performance after installing Photoshop CC

    Hello- A colleague of mine has been using Photoshop CS2 forever. I finally convinced her to upgrade to a newer version, and we installed Photoshop CC on her Win 7 Pro desktop. She is trying to print today, and jobs that would take no time at all in C