Updating an object to the database using Apache Ca

2019-08-11 06:55发布

问题:

I am using Cayenne in a project for the first time. Till now, i was using the SelectQuery and was loving it. I now need to update an object e.g. my User object contains an emailId attribute. When the user needs to update his/her email, i take the existing User object and update the emailId attribute with the new value provided by the user.

The problem starts now, where i don't understand the way to persist the update to the database. The options i have seem to be limited to SQLTemplate or using EJB QL. Am I right? Is there a more elegant way of supplying the updated object to the DataContext and persisting the update to the DB?

I am using Cayenne in a web application and obtain the context via the WebApplicationContextFilter.

回答1:

yes, there is certainly a more elegant way. You make one or more changes to your objects, you then commit them via the ObjectContext that was used to get the objects in the first place:

ObjectContext context = ...
List<MyEntity> objects = context.performQuery(...); 
MyEntity o = objects.get(0);  
o.setXyz("new value"); // I assume you got to this point
...
context.commitChanges();

The last line sends all your changes to the DB.