Problem persisting collection of interfaces in JDO/Datanucleus. "unable to assign an object of type.." - jdo

I am getting below error whilst trying to persist an object that has a collection of interfaces which I want to hold a couple of different types of objects. Seems to be happening almost randomly. Sometimes after restarting it works ok ( I might be doing something wrong though).
class CommentList {
#Persistent
#Join
ArrayList<IComment> = new ArrayList<IComment>();
}
somewhere else...
CommentList cl = new CommentList();
cl.addComment( new SimpleComment() );
cl.addComment( new SpecialComment() );
repo.persist( cl );
I can see the join table has been created in my DB along with ID fields for each of the Implementation classes of IComment.
SimpleComment and SpecialComment implement IComment. If I just add a SimpleComment it works fine. As soon as I start trying to add other types of objects I start to get the errors.
error im getting
java.lang.ClassCastException: Field "com.myapp.model.CommentList.comments" is a reference field (interface/Object) of type com.myapp.behaviours.IComment but DataNucleus is unable to assign an object of type "com.myapp.model.ShortComment" to this field. You can only assign this field to a type specified by the "implementation-classes" extension attribute.
at org.datanucleus.store.mapped.mapping.MultiMapping.setObject(MultiMapping.java:220)
at org.datanucleus.store.mapped.mapping.ReferenceMapping.setObject(ReferenceMapping.java:526)
at org.datanucleus.store.mapped.mapping.MultiMapping.setObject(MultiMapping.java:200)
at org.datanucleus.store.rdbms.scostore.BackingStoreHelper.populateElementInStatement(BackingStoreHelpe
r.java:135)
at org.datanucleus.store.rdbms.scostore.RDBMSJoinListStoreSpecialization.internalAdd(RDBMSJoinListStore
Specialization.java:443)
at org.datanucleus.store.mapped.scostore.JoinListStore.internalAdd(JoinListStore.java:233)
When it does save, if I restart the server and try to query for a list of the comments, I get null values returned.
I'm using mysql backend - if I switch to db4o it works fine.
Please let me know if any info would be useful.
If you have any idea where I might be going wrong or can provide some sample code for persisting collection of different objects implementing the same interface that would be appreciated.
Thanks for any help.
Tom

When I used interfaces I just enabled dynamicSchemaUpdates (some persistence property with a name like that) and FK's are added when needed. The log gives all SQL I think

I fixed this by specifying
<extension implemention-classes="SimpleComment SpecialComment"/>
for the field cl in my pacakge.jdo.

Related

Woocommerce Subscriptions - Set owner programmatically

I'm using WooCommerce Subscriptions on a site to provide team-based memberships. I'd like to ensure that the owner of the Subscription matches the owner of the team (one user to rule them all...!)
It's possible to do this via admin by using the customer dropdown fields.
So, I have been trying to set this programmatically. As I understand it, there are getter and setter methods for all the Subscription data (and as a Subscription is extended from WC_Order, those methods should work too). However, I can't figure out what method to use to make this change.
I've tried creating both a subscription and an order instance from a subscription ID, but neither of the methods I've tried below work:
set_user_id(456)
set_customer_id(456)
When I print_r() the Subscription instance, the original customer_id is still there under the data array:
WC_Subscription Object
(
[data:protected] => Array
(
...
[customer_id] => 123
)
...
)
Given that the array is protected, I'm guessing there's a setter method I haven't tried yet. Can someone please help me with what type of instance and setter method I need for this please?
Cheers!
I'm pleased to say I've solved this one myself - posting here to hopefully help someone else from banging their heads against the walls!
Turns out I was doing everything correctly, I just wasn't calling the save() method after I made my changes......! D'oh!
I'm quite used to functions in WordPress having immediate effect - a valid call to update_post_meta, for example, will take effect straight away.
Instead, WooCommerce stores changes via getters/setters within the local instance created through WC_Order (or other abstractions). These are only saved to the database* when you call the save() method. I believe this is to help prevent unnecessary database calls.
*or data store if you're doing something very fancy.
Code example for those who need it, for an order ID '123' and a new user ID '456':
// Create order instance
$order_instance = wc_get_order(123);
// Set new customer id
$order_instance->set_customer_id(456);
// Save changes
$order_instance->save();
// To echo data back, use the get_data() method to create an array of data, which you can assign however needed. For example:
$order_data = $order_instance->get_data();
$customer_id = $order_data['customer_id'];
echo 'customer number = ' . $customer_id;
I found the information about why the data requires manually saving (it's only stored in the local instance) from the very helpful doc at Advanced Woo:
"Setter methods update information in the WC_Data object held in working memory. However, one of the Database Operations Methods must be called to make the change in the database."
https://advancedwoo.com/topic/wc_data-and-data-storage-manipulate/#/setters

Why is doctrine updating every single object of my form?

I've got a big Symfony 2 form on a huge collection (over 10k objects). For simple reasons, I cannot display a form of thousands of objects. I am displaying a form of about 300 objects.
I have found no way to filter a collection into a form and thus do the following :
$bigSetOfObjects = array(
'myObject' => $this
->getDoctrine()
->getRepository('MyObject')
->findBy(... )
);
$form = $this->createForm(new MyObjectForm(), $bigSetOfObjects);
// And a little further
if ($this->getRequest()->getMethod() == 'POST') {
$form->bindRequest($this->getRequest());
$this->getDoctrine()->getEntityManager()->flush();
}
Everything works great. Form is displayed with the correct values and the update works fine also. Data is correctly saved to the database. The problem is that Doctrine is executing a single update statement per object meaning the whole page is about 300 SQL statements big causing performance issues.
What I do not understand is that I'm updating only a couple of values of the form, not all of them. So why is Doctrine not able to detect the updated objects and thus update only those objects in the database?
Is there anything I'm doing wrong? I might have forgotten?
By default Doctrine will detect changes to your managed objects on a property-by-property basis. If no properties have changed then it should not be executing an update query for it. You may want to check that the form isn't inadvertently changing anything.
You can, however, change how doctrine determines that an object has changed by modifying the tracking policy. Since you are working with a lot of objects you may want to change to the DEFERRED_EXPLICIT tracking policy. With this method you would specifically call:
$em->persist($object);
on the entities that you want to be updated. You would have to implement your own logic for determining if an object needs to be persisted.

How do I get an ID after saving an ExtBase Model?

After creating a model and adding it to a repository I want to have the new ID for different purposes (creating a mail, updating other fields outside the Extbase world)
$page = t3lib_div::makeInstance('Tx_MyExt_Domain_Model_Page');
$page->setTitle('Hello World');
$this->pageRepository->add($page);
At this point $page hasn't got an ID yet, uid is null.
$page->getUid(); // returns null
When does it get it? And how can I retrieve in on runtime?
In ExtBase, objects are "managed". This means every persistence transaction (add/remove/update) is simply noted in the underlying logic, but not yet executed until the appropriate time (like the end of processing a request). So, just because you add an object to a repository doesn't mean that it's actually added yet. That actually happens once $persistenceManager->persistAll() is called, which isn't something you need to do manually, ever. The point is, your $page object won't have a UID until it's saved and that's why $page->getUid() returns null. Look here for a great explanation.
I suspect that you are trying to do something outside of the ExtBase object/MVC lifecycle. At least, last time I got null when I tried to get the UID of an object, it was because I wasn't operating within the framework appropriately.
However, if you post some more code and give us a bigger picture of what you're trying to achieve, maybe we can help you get to a point where that object actually has a UID. For instance, if you're in a Controller object, tell us which Action method you're in, or if you're in a Repository object, tell us what you're trying to get from the repository and where/how you plan on using the query results.
EDIT
Just guessing here, but I'm assuming you're executing this code in some action of a controller. Since after the controller is executed a view is rendered, you can just pass the page object to the view:
$this->view->assign('page', $page);
And then in your view you can use the page object in a link:
<f:link.action action="show" arguments="{page:page}">
See this page object
</f:link.action>
And then in the show action of your controller you can show the page:
public function showAction(Tx_MyExt_Domain_Model_Page $page) {
// Do whatever you need to show the page in the `Show.html` template
}
I really am just guessing here. If you can give us a larger picture of what you're trying to do, what your action methods are supposed to do and things like that, we can answer your question a little more confidently.
(I'm also assuming that your page object isn't a replacement for the regular TYPO3 pages and that they are something totally different. It's much easier to deal with those TYPO3 pages through the backend interface than at the php level.)
You can call persistence manager explicitly in Your controller like this
#TYPO3 4.x
$persistenceManager = $this->objectManager->create('Tx_Extbase_Persistence_Manager');
$persistenceManager->persistAll();
#TYPO3 6.x
$persistenceManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager');
$persistenceManager->persistAll();

Writing changes from editable datagrid back to local data store - Adobe Air/Flex

I am using Adobe Air to get data from SalesForce, and present it in a datagrid.
I am using a query to get the data, and then put it into an arraycollection that is bound to the datagrid, this works correctly and the data is displayed.
I have made the datagrid editable, and I am able to change the values in the datagrid, but I cannot find how to save the changes to the local database.
I am using the following code:-
protected function VisitReportGrid_changeHandler(event:ListEvent):void{
app.wrapper.save(VisitReportGridProvider)
}
But this has the following error when I try and compile it:-
1067: Implicit coercion of a value of type mx.collections:ArrayCollection to an unrelated type mx.data:IManaged.
Obviously I am doing this wrong, but I cannot find the correct syntax.
Thanks in advance for your help
Roy
This code is not enough to understand where actually is the problem
Need to know what is VisitReportGridProvider, what is wrapper.save() method.
**after comment:
F3DesktopWrapper.save():
public function save(item:IManaged):void
Saves the specified Managed object to the local database. You must make an explicit call to syncWithServer() to update the data on the salesforce server. However, do not call syncWithServer() too often (batch your save calls) as this may use up your alloted API usage. If the item is in conflict, the conflict will be resolved.
Parameters:
item:IManaged — The managed object to create or update.
you're passing parameter with type ArrayCollection which doesn't implement IManaged interface.
You need to pass the item in the ArrayCollection that was changed to the save function. Like:
acc.fieldCollection.updateObject(new AsyncResponder(function(o:Object, t:Object):void {
app.wrapper.save(o as Account);
}, function(e:Object):void {
}));

ADO.NET Data Service doesn't Update

I've a problem updating objects with the ADO.NET Data Services.
First I've create a service, which can load and store the data. Its a basic data context which implements the IUpdatable-interface.
After that, I've created a simple service-client. I just created it with the 'Add Service'-reference in Visual Studio. Basically this service seams to work. I can query for the objects and store new objects. However I cannot update objects.
This is my update-code on the client:
var ctx =
new TeamDataContext(new Uri("http://localhost:8637/TeamInfoService.svc"));
var team = ctx.Teams.First();
team.TeamName = "New Team Name";
ctx.UpdateObject(team);
ctx.SaveChanges();
What my main issue is, that IUpdatable.SetValue() isn't called for the object which I want to update. Only the IUpdatable.SaveChanges() is called without updating the objects on the server.
When I create a new object, the IUpdatable.SetValue is called on the server to set the property.
So what I am doing wrong? Are my expectations wrong? Is IUpdatable.SetValue supposed to be called when updating a object? Or do I need to do additional things to do updates?
Edit: I just watched the HTTP-requests between the client and the server. The client send a HTTP-Merge request with the changes. However I still don't know why the changes aren't stored.
I've just found out whats the issue and feel like an idiot right now. The TeamName-property was the Key of the object. Of course, when you change the key, it actually cannot find the object to update anymore. And therefore it cannot update the property.
So, never try to update the key of the object =)

Resources