Persist problem in cascade using @OneToMany

We are trying to persist an object which has a OneToMany relationship to other objects with CascadeType.ALL
When we persist, the log shows that it creates the INSERT statement with the correct bind variables (sequence-generated REPORT_ID, etc.) for the first object.
The problem happens when it tries to cascade and insert the Many part. The log shows the it tries to create the INSERT statement for the second object but the bind variable for the REPORT_ID is null.
Since we defined the relationship of the OneToMany using the REPORT_ID, we assumed that the REPORT_ID that was auto-generated for the first object would be used for the @Many objects.
What are we missing ??????
First Object:
@Id
@SequenceGenerator(name = "REPORT_HEADER_S", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "REPORT_HEADER_S")
@Column(name = "REPORT_ID", nullable = false)
private Long reportId;
@OneToMany(mappedBy = "report", cascade = { CascadeType.ALL})
private List<Summary> summaryList;
Second Object
@ManyToOne
@JoinColumn(name = "REPORT_ID", referencedColumnName = "REPORT_ID")
private Report report;

Hello, Chris.
Thank you for your reply.
The structure of my tables is:
table document (id int not null constraint document_pk primary key,
table document_price (document_id int not null constraint document_price_fk references document (id),
date date not null default current_date,
price decimal(9,2) not null,
primary key (document_id, date)).
The entity classes are:
@Entity @Table(name = "DOCUMENT")
public class Document implements Serializable {
@TableGenerator(name = "document_generator", table = "ID_GENERATION", pkColumnName = "TABLE_NAME", valueColumnName = "ID_VALUE",
pkColumnValue = "DOCUMENT", allocationSize = 1)
@Id
@GeneratedValue(generator = "document_generator")
@Basic(optional = false)
@Column(name = "ID")
private Integer id;
// other fields
@OneToMany(cascade = CascadeType.ALL, mappedBy = "document", fetch = FetchType.LAZY)
private Collection<DocumentPrice> documentPriceCollection;
// constructors, getters, setters ...
@PostPersist
public void initializePrices() {
for (DocumentPrice dp : documentPriceCollection) {
dp.documentPricePK.setDocumentId(id);
@Entity
@Table(name = "DOCUMENT_PRICE")
public class DocumentPrice implements Serializable {
@EmbeddedId
protected DocumentPricePK documentPricePK;
@Basic(optional = false)
@Column(name = "PRICE")
private BigDecimal price;
@JoinColumn(name = "DOCUMENT_ID", referencedColumnName = "ID", insertable = false, updatable = false)
@ManyToOne(optional = false, fetch = FetchType.LAZY)
private Document document;
// constructors, getters, setters ...
@Embeddable
public class DocumentPricePK implements Serializable {
@Basic(optional = false)
@Column(name = "DOCUMENT_ID")
private int documentId;
@Basic(optional = false)
@Column(name = "DATE")
@Temporal(TemporalType.DATE)
private Date date;
// constructors, getters, setters ...
I create first Document entity, create DocumentPrice entity and add DocumentPrice entity to the documentPriceCollection of the first Document entity. I invoke commit method of my entity manager, and corresponding rows are added to the document and document_price tables.
I invoke clear method of my entity manager.
Then I create new entities Document and DocumentPrice and add new DocumentPrice entity to the documentPriceCollection of the new Document entity. I invoke commit method and get the following exception:
oracle.toplink.essentials.exceptions.ValidationException
Exception Description: Cannot persist detached object [entities.DocumentPrice[documentPricePK=.entities.DocumentPricePK[documentId=0;
date=Sat May 29 00:00:00 MSD 2010];
price=11]].
Class> entities.DocumentPrice Primary Key> [2010-05-29, 0]
at oracle.toplink.essentials.exceptions.ValidationException.cannotPersistExistingObject(ValidationException.java:2171)
at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.registerNotRegisteredNewObjectForPersist(UnitOfWorkImpl.java:3251)
at oracle.toplink.essentials.internal.ejb.cmp3.base.RepeatableWriteUnitOfWork.registerNotRegisteredNewObjectForPersist(RepeatableWriteUnitOfWork.java:339)
at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:3220)
at oracle.toplink.essentials.mappings.CollectionMapping.cascadeRegisterNewIfRequired(CollectionMapping.java:265)
at oracle.toplink.essentials.internal.descriptors.ObjectBuilder.cascadeRegisterNewForCreate(ObjectBuilder.java:1294)
at oracle.toplink.essentials.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:3226)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerImpl.persist(EntityManagerImpl.java:205)
And I see through debugging that @PostPersist method of the Document entity isn't invoked during second commit before the exception is generated.
What should I do to avoid exception during second commit?

Similar Messages

  • Problems with cascading delete with entities

    I have a problem with cascading delete. I have two entities, Notebook and Note. One instance of Notebook can have several instances of Note in a Collection< Note >. The two entities are joined with a join table notebook_note that have two columns, the PK from the table of Notebook and Note. Note is not aware of the relation.
    From the user interface some elements of the collection<Note> can be added or deleted. I want to delete an element of that collection and make it persisted on the DB.
    If I add some Note elements to the collection and then I EntityManager.merge(notebook) (see public void persistNotebook() code below), I have all them persisted on the DB.
    However, if I delete some preexisting Note elements, after the merge I found deleted only the corresponding rows from the join table notebook_note BUT the rows in table Note, that was belonging to the deleted instance of Notebook, are NOT removed.
    Till now I found a way to do that (see code UserBean below), but I think that there is a simpler and so better way to do that! I hope to receive some suggestions!!
    @Entity
    public class Notebook implements Serializable {
    private static final long serialVersionUID = 1L;
    private String userName;
    private Collection<Note> notes;
    public Notebook() {
    public Notebook(String userName) {
    this.userName = userName;
    notes = new ArrayList<Note>();
    @Id
    public String getUserName() {
    return userName;
    public void setUserName(String userName) {
    this.userName = userName;
    @OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
    public Collection<Note> getNotes() {
    return notes;
    public void setNotes(Collection<Note> notes) {
    this.notes = notes;
    @Entity
    public class Note implements Serializable {
    String note;
    public void setNote(String note) {
    this.note = note;
    public String getNote() {
    return note;
    @Stateful
    public class UserBean implements UserRemote {
    private static Logger log = Logger.getLogger(UserRemote.class);
    @PersistenceContext(unitName = "etourism-ejbPU")
    private EntityManager em;
    &hellip;&hellip;
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void persistNotebook() {
    NotebookDao notebookDao = new notebookDao(em);
    notebookDao.merge(notebook);
    em.flush();
    public void deleteNotebookNote (&hellip;.) {
    &hellip;..
    //noteFound is the note I want to delete from the Collection<Note>
    notebook.getEvents().remove(noteFound);
    persistNotebook(); //see method above
    *//I have also to explicitally delete the associated note!!!*
    *NoteDao noteDao = new NoteDao(em);*
    *noteDao.remove(noteDao.read(noteFound.getId()));*
    public void addNotebookNote(&hellip;..) {
    //add new note to the collection<Note> of the Notebook
    Note newNote = new Note(&hellip;);
    notebook.getNotes().add(newNote);
    persistNotebook();
    Where:
    public class NotebookDao extends JpaDao<Notebook, String> {
    &hellip;&hellip;
    public abstract class JpaDao<T, PK extends Serializable> implements IDao<T, PK> {
    &hellip;..
    public void remove(T entity) {
    getEntityManager().remove(entity);
    public void merge(T transientObject) {
    getEntityManager().merge(transientObject);
    }

    Thank you gimbal2 for your answer.
    You are right saying that a single Note could be bound to multiple notebooks, when using a join table, so the cascade cannot be done automatically by JPA.
    However, in my case, a single Note is bound only to one Notebook, so I would like to drop the join table (as you rightly suggest): however when I declare in the Notebook, a relation 1:N in this way ...
    @OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
    private Collection<Note> notes;
    ... the join table is automatically created during the deploy.
    Sorry, I am a beginner in EJB3. What kind of relational mapping annotation should I use to have a straight 1:N relationship that doesn't generate a join table?
    I think that it should be better to avoid to modify the relationship (es. cascade option) directly in the created db tables and let the logic be declared in the entity code definition: am I right?
    Waiting for your suggestion ...
    thank you very much
    Enzo
    Edited by: contini on May 22, 2009 5:37 AM

  • Persistant problems with FF 27.0.1 on Windows 7/64

    I seem to have a persistent problem with Firefox 27.0.1 and my MSN homepage. When I open FF, it takes me to both my Outlook Mail page and My MSN pages in two separate tabs. Outlook Mail had a problem taking my correct password, but that issue seems to have resolved itself (I did clear all cookies and caches related to the website). But My MSN is still giving me this message...
    "The page you have requested cannot be found.
    The web page you were attempting to view may not exist or may have moved — try checking the web address for typos."
    I tried the same thing as I did with Outlook (deleted cookies and caches), but the problem persists. I disabled all plugins, and still no luck. The MSN Homepage comes up, and I'm shown as logged into My MSN, but when I click the My MSN link, I get the "The page you have requested..." message.
    Another issue relating to both websites is password remembering. FF will NOT ask to remember the passwords for those sites. I have Remember Passwords box checked in Settings and it does for other sites, but not my Homepage(s). Clearing cookies/caches didn't help, and the password is not listed in the Remembered Passwords page of Settings.
    Finally, Firefox on my home laptop (Windows 7/64 as well) freezes and crashes a lot, as well as displayes a warning there is something with Flash, which I have updated many times over.
    I used to use Internet Explorer as a browser exclusively until I started having problems with certain websites not allowing me to log in. I realized it was not the website, but some incompatibility with IE. I started using Firefox, and fouind no problems, and heard it was more secure and easier to configure than Internet Explorer anyway. But since these problems started occurring (especially with NO way for me to log onto My MSN), I have to go back to using IE (except for select website logons), which is disappointing :-(.

    About your home page; Manually set up Firefox with the window(s) and tab(s)
    the way you want them to be. Then;
    '''''Firefox Options > General > Homepage'''''.
    Press the button labeled ''''Use Current'''.'
    =====================================
    Open a new window or tab. In the address bar, type '''''about:config'''''.
    If a warning screen comes up, press the '''''Be Careful''''' button.
    This is where Firefox finds information it needs to run.
    At the top of the screen is a search bar. Enter '''''browser.newtab.url'''''
    and press enter. '''''browser.newtab.url'''''
    tells Firefox what to show when a new tab is opened.
    If you want, right click and select '''''Modify'''''. You can change the
    setting to;<BR><BR>about:home (Firefox default home page),<BR>
    about:newtab (shows the sites most visited),<BR>
    about:blank (a blank page),<BR>
    or you can enter any web page you want.<BR><BR>
    The same instructions are used for the new window setting, listed as
    '''''browser.startup.homepage'''''.

  • TS3276 Anyone experiencing problems sending mail using TalkTalk - can receive but not send  - was ok up until pm 24/08/12 - have recently loaded Mountain Lion patch could this be the problem?

    Anyone experiencing problems sending mail using Apple Mail viaTalkTalk - can receive but not send  - was ok up until pm 24/08/12 - have recently loaded Mountain Lion patch could this be the problem?

    jag157 wrote:
    "I managed to solve the problem. Under smtp settings (mail preferences/accounts/edit smtp) I set the outgoing port to 25 (as recommended by Talktalk), no authentication (set to none) and unchecked SSL. I found that until I set the port to 25 and authentication to none I was unable to uncheck SSL. One I had done this I was able to send from my main email and other email adddresses set up under my account."
    Superb advice R&W!  My email sending block using TalkTalk started 2 months ago using Snow Leopard, continued when I upgraded to 10.8.2, and has been persistent on my wife's new iPad (IOS 6.1).  Implementing your wise words has fixed all that, and now enables me to call her on FaceTime — previously only she could call me.  Thank you so much; this will save hours of further fruitless searching and phoning.
    Please remember that your email is now insecure, if you wish to have a secure connection SSL must be on and port 25 should be avoided.

  • I am unable to view google ads running alongside and under videos on YouTube. This is only a problem when I use Firefox. If I use another browser, I can see the ads. I do not have adlock as it does not appear in my plug-ins/add ons. Please help..

    I have been using Firefox for about two years. For about a month now I have been unable to view any Google advertisements that run on YouTube pages alongside and under videos. This is important for my business. I would like to stay with Firefox, but this is only a problem when I use Firefox and is not a problem with Internet Explorer or Google Chrome as I checked. I tried uninstalling Firefox and all plugs ins and add ons and then reinstalling it. This did not work. Firefox seems to be blocking the Google codes that enable the ads to run on the pages. I look forward to your help. Thank you.

    CS2 is very old and reached its "end of life" a while back.  So probably won't run on modern operating systems.  If you can still run it, you'll need to uninstall what you have and re-install with the download link below to activate it.
    Error: Activation Server Unavailable | CS2, Acrobat 7, Audition 3
    Nancy O.

  • Hi can anybody help please. I am having terrible problems trying to use my Nikon D7100 to tether. I have downloaded the latest Lightroom updates and also checked my firmware which is also the latest avaiable and still Lightroom wont detect my camera!

    Hi can anybody help please. I am having terrible problems trying to use my Nikon D7100 to tether. I have downloaded the latest Lightroom updates and also checked my firmware which is also the latest avaiable and still Lightroom wont detect my camera!. When I use a friends Canon camera it works every time!

    Hi Keith thanks for your reply I have Lightroom 5.7.1 64 bit and my Nikon's firmware is version 1.02

  • Problem with sendRedirect using relative URL in WebLogic 5.1 with SP7 & 8

    I patched to SP 7 (and also 8), and the request.sendRedirect() with relative
              URL failed. The browser simply displayed "404 - Page not found".
              This problem only happens in a cluster environment attached to a web server.
              SP6 or earlier does not have such problem.
              I noticed that the latest SP always formats the URL and returns it as a full
              absolute URL to the browser. The problem is it uses the Weblogic Server host
              URL where the request is processed (not the Web Server host URL) which is
              not visible to the internet.
              Is it possibly a bug in SP?
              

    I patched to SP 7 (and also 8), and the request.sendRedirect() with relative
              URL failed. The browser simply displayed "404 - Page not found".
              This problem only happens in a cluster environment attached to a web server.
              SP6 or earlier does not have such problem.
              I noticed that the latest SP always formats the URL and returns it as a full
              absolute URL to the browser. The problem is it uses the Weblogic Server host
              URL where the request is processed (not the Web Server host URL) which is
              not visible to the internet.
              Is it possibly a bug in SP?
              

  • When I mirror my late 2012 mac mini to my apple tv. I only see a black screen.  I have no problems if I use my mid 2012 MBPr

    When I try to mirror my late 2012 macmini to my apple tv. I only see a black screen.  I have no problems if I use my mid 2012 MBPr.
    The mac mini is still on mavericks at present any advice welcome please.  (There is no other monitor attached to the macmini would this be an issue?)
    I use share screen to monitor my macmini from my MBPr
    Thank you
    Ken

    I have solve this problem.
    I plug in a usb 3.0 HDMI blackmagic capture device in to the mac mini and connected the HDMI out of the macmini to the HDMI in of the black magic.
    So it thinks it has a primary screen and it now mirror this the apple tv.

  • Problem in struts using JDeveloper10.1.2

    hi
    Iam completly new to jdeveloper
    Iam using jdev 10.1.2 for my simple struts application
    I have
    action class -- LoginAction
    form bean -- login (using DynaActionForm)
    login.jsp to enter username
    success.jsp for welcom msg
    failure.jsp --- in this i use one submit btn when i press this it will go to login.jsp for relogin
    <form action="/login.jsp">....
    the problem is
    In LoginAction
    String password=(String)((DynaActionForm)form).get("password");
    // String pwd =request.getParameter("username");
    if(password.equalsIgnoreCase("oracle"))
    return mapping.findForward("success");
    else
    return mapping.findForward("failure");
    iam import all the class for the respective reff variables.
    But it will indicate err underline(blue) under text which are in bold saying msgs as
    --method get(java.lang.string) not found in org.apache.struts.action.DynaActionform
    the samething for remaining two showing on ActionMapping
    plese tell me where is the problem
    running on Embedded OC4J SERVER
    error message is
    http://hostname:8988/hello_struts1-ViewController-context-root/login.do
    07/07/19 17:12:31 Oracle Application Server Containers for J2EE 10g (10.1.2.0.2) initialized
    Jul 19, 2007 5:12:32 PM org.apache.struts.util.PropertyMessageResources <init>
    INFO: Initializing, config='org.apache.struts.util.LocalStrings', returnNull=true
    Jul 19, 2007 5:12:32 PM org.apache.struts.util.PropertyMessageResources <init>
    INFO: Initializing, config='org.apache.struts.action.ActionResources', returnNull=true
    Jul 19, 2007 5:12:32 PM org.apache.struts.util.PropertyMessageResources <init>
    INFO: Initializing, config='view.ApplicationResources', returnNull=true
    Jul 19, 2007 5:12:32 PM org.apache.struts.action.RequestProcessor processException
    WARNING: Unhandled Exception thrown: class java.lang.NullPointerException
    thanks

    Duplicate post:
    problem on struts using jdeveloper 10.1.2
    user583549,
    I see you got an answer from Shay in the other post.
    Good Luck,
    Avi.

  • Display problems in IE, using Netlace Designs approach

    Display problems in IE, using Netlace Designs approach
    Could someone please look at
    www.tudo.co.uk/testing/magnification/
    I am trying to adjust some css code taken from Netlace
    Design's website
    for my purposes. The purpose is to enlarge an image on
    'hover' and to
    enlarge some text on 'hover'.
    What I have done works all right in Mozilla/Seamonkey.
    However, in IE,
    the 'text enlargement' does not work at all
    and when I am enlarging the image there is ***in IE*** a
    large grey
    surplus area at the bottom, which looks like a background
    area which has
    turned out to have too much height. I want to get rid of that
    superfluous grey area.
    How can I make sure it works in BOTH Mozilla and in IE?
    Thanks for your help.
    Adrian

    Hi ijmari,
    I checked out that page and don't see any Spry menubar in it.
    I'm assuming you've reverted back or removed it.
    If you still need/want help, please post the URL to the page
    that uses the menubar and demonstates the problem.
    --== Kin ==--

  • Problem with BAPI_CUSTOMER_CREATEFROMDATA1 using JCo on IDES

    sorry, wrong board - i opened a new post
    Problem with BAPI_CUSTOMER_CREATEFROMDATA1 using JCo on IDES
    Hello everyone,
    we are working on a student project and would like to create customers (debtors) in an SAP IDES system.
    Using the ref-customer to copy from, and some personal-data below, we get the error message
    'Internal error: External no.assignment for reference customer/customer'
    We also tried with BAPI_CUSTOMER_GETINTNUMBER, and ACCOUNTGROUP ZINT (New Internet Customer, others won't work?). But CREATEFROMDATA1 takes no CustomerNo created this way, nor it wants to create one 'internal'?
    Any suggestions? Thanks a lot for your help,
    Greetings,
    Tobias Schmidbauer
              inParams = function.getImportParameterList().getStructure(
                   "PI_COPYREFERENCE");
              inParams.setValue("0000001000", "REF_CUSTMR");
              inParams.setValue("1000", "SALESORG");
              inParams.setValue("10", "DISTR_CHAN");
              inParams.setValue("00", "DIVISION");
              inParams =function.getImportParameterList().getStructure(
                   "PI_PERSONALDATA");
              inParams.setValue("Simpson", "LASTNAME");
              inParams.setValue("Homer", "FIRSTNAME");
              inParams.setValue("Jay","MIDDLENAME");
              inParams.setValue("Springfield", "CITY");
              inParams.setValue("DE", "LANGU_P");
              inParams.setValue("DE", "LANGUP_ISO");
              inParams.setValue("DE", "COUNTRY");
              inParams.setValue("EUR", "CURRENCY");
              inParams.setValue("12345", "POSTL_COD1");
    Message was edited by: Tobias Schmidbauer

    Hello Brian,
    Thanks for your pointer. Actually The customer's reference number i was providing in the PI_COPYREFERENCE structure was a sold-to party customer and it uses external customer number assignment. When i used "New Internet Customer" (that doesnt use external assignment by default) as customer's account group, the customer was created successfully and assigned customer number was returned.
    I want to ask now how could we give a customer number in the BAPI as i am unable to find any such column in any of the tables. (Customer number is an "out" parameter so it can only return the number of created customer). Secondly, how to chnage the external assignment property of a particular account group (like sold-to party). i.e, how could we change the account group configurations through SAP GUI??
    - Umair

  • TS1292 Hey, im facing a problem while im using the purchesing , its showing me that: contact with apple support itunes???? Please help

    Hey, im facing a problem while im using the purchesing , its showing me that: contact with apple support itunes???? Please help

    Use the link below to contact iTunes support.
    http://www.apple.com/emea/support/itunes/contact.html

  • I am trying to cut and paste from a program, IEP DIRECT, and normally on my PC I have no problems; however, when using my MAC the formatting gets all mixed up

    i am trying to cut and paste from a program, IEP DIRECT, and normally on my PC I have no problems; however, when using my MAC the formatting gets all mixed up

    If you refer to this
    https://www.iepdirect.com/iepdotnet/hub/index.html
    then they have an issue with mac version.
    At a first glance, their website is optimized for Windows only, it displays badly in Safari, perhaps it would be better in Firefox or other browser.

  • HT5132 I can't click on the 'Learn More' or 'Ok' options so cannot use Aperture. How do I overcome this problem? I use OS X Lion 10.7.4

    I can't click on the 'Learn More' or 'Ok' options so cannot use Aperture. How do I overcome this problem?
    I use OS X Lion 10.7.4.
    I also don't seem to be able to disable the Mobileme account via the system preferences option as mobileme doesn't allow access with my password.

    Have you tried to disconnect from the Internet before launching Aperture? Then the MobileMe webpage should not be shown and you should be able to access the Aperture preferences and remove the MobileMe account from the "Preferences > Web" panel.
    If this does not succeed, (Force) quit Aperture, log off and log on again, then remove the Aperture Preferences file (~/Library/Preferences/com.apple.Aperture.plist)
    from the Preferences Folder in your User Library and try again to launch Aperture. See http://support.apple.com/kb/HT3805 on how to remove the Preferences.
    Regards
    Léonie

  • Im using xcode 4.6 and im having problems reading files using the fopen function in c

    Im using xcode 4.6 and im having problems reading files using the fopen function in c

    Yes, but that would not cause the "build  failed" message.
    right I missed that part. Looks like two problems then.
    //  main.m
    //  ASCTestFopen
    //  Created by Frank Caggiano on 3/2/13.
    //  Copyright (c) 2013 Frank Caggiano. All rights reserved.
    #import <Foundation/Foundation.h>
    #include <stdio.h> 
    int main(int argc, const char * argv[])
        @autoreleasepool {
            FILE *fp, *fopen();
            // insert code here...
            if((fp = fopen("~/test.txt","r")) == NULL)
                NSLog(@"open failed");
        return 0;
    This will compile ad run in Xcode with a project type of comand line tool

Maybe you are looking for

  • QT taking so long to bring up a video "WMV or AVI" on new Mac Intel

    Well, that about says it. I've loaded quite a number of the "add ons" but still taking forever to load and sometimes never comes up. Any advice please? Thank you tons. Tom

  • Development Environment Recommendations

    For a developer considering moving fm php and Textpad as my text editor (something about 'cold dead fingers' might apply here) I'm looking for recommendations.  With me as a singleton, and no income for the stuff I do, $ is a factor. I develop under

  • Essbase smartview retrival versus excel add in

    Hi all, I have some performance issues with smartview. I am running a simple querry through smartview having one attribute dimension on the excel sheet, it runs for couple of minutes and throws me a time out error. I tried the same querry using excel

  • Create Development mode selection popup

    Hi All,           I have to implement the popup as like Development mode selection popup. What is the component name of the popup. how to implement it? thanks, dhina

  • Change printer settings using print management

    I have deployed some printers using 'Print Management' in Windows 2012. My users see the printer. By default, 'paper size' is set to 'letter'. I want to change it to 'A4'.  I went to 'print management' tool on the print server. There I changed the fo