Hi Corina,
If you are trying to fill in the Invoices Entity from the MySql Credit Memo data, if the object found with same Invoice Number in your check Credit exists:
True > You already retrieved Credit Memo and do another retrieve of Invoices via association and make changes as needed
False > Create a New Credit Memo and also create Invoices add association between them.
For both Credit Memos and Invoices, you need to create a list before loop (Like you did for credit memo) and commit outside the loop.