In an app on which I'm currently working, I just replaced db4o with RavenDB. I just noticed something that wasn't working, did some research, and now I need a sanity check.
Let's assume this domain model:
Person has Name, Address, and Car properties.
Car has Make, Model, and Mileage properties.
With RavenDB, I can create a Car and save it. Then I can create a Person and assign a Car to the Person's Car property. When I save Person, Car gets saved within Person. All seems fine.
The problem is when I later update Car.Mileage. Car gets updated in RavenDB, but not within Person.Car. Person.Car has the old mileage.
Car exists on its own. Person Joe can own the car, and so can Person Nancy. Both Person objects will have a reference to Car.
In RavenDB, how should this be handled? From everything I've read about aggregate/root objects, it looks like maybe I should add a CarId property to Person. Then, when I load Person, also manually load the Car by the ID. Is that right? Or can I embed the Car property within Person, and somehow have all Person objects show the correct Person.Car.Mileage as Car.Mileage changes over time?
If I understood your model correctly, you are generating 2 documents like this:
{// cars/1
"Make": "Honda",
"Model": "Civic",
"Mileage": 250000
}
And like this:
{// persons/1
"Name": "John Doe",
"Address": "...",
"Car": {
"Id": "cars/1",
"Make": "Honda",
"Model": "Civic",
"Mileage": 250000
}
}
It's important that in this document model. All of the car properties have been denormalized in the Person.Car property. So in your code, when you make an update to Car.Mileage and save it. You end up with the 2 document looking like this:
{// cars/1
"Make": "Honda",
"Model": "Civic",
"Mileage": 999999
}
And like this:
{// persons/1
"Name": "John Doe",
"Address": "...",
"Car": {
"Id": "cars/1",
"Make": "Honda",
"Model": "Civic",
"Mileage": 250000
}
}
Which is exactly what you told Raven to do. With this document model, to make sure both documents are consistent you would need to update both the Car object like you did and the Person.Car.Mileage property for all the persons using that car.
Depending on the data access needs you can modify your model in a few different ways. One option is to make your model look like this:
{// cars/1
"Make": "Honda",
"Model": "Civic",
"Mileage": 250000
}
And like this:
{// persons/1
"Name": "John Doe",
"Address": "...",
"Car": "cars/1"
}
With this document model you will only need to update the Car.Mileage property. If you select this option you can also get the referenced document back from Raven in a single network request. By doing something like this:
var person = session.Include<Person>(x => x.Car).Load("persons/1");
var car = session.Load<Car>(person.Car);
But this is only one option in how you can change your document model to address your application's needs.
Related
I have an event entity.
What is the correct way to implement update of this entity? Our frontend-developer wants everything to be done with a single PUT request to the backend: changing the values of the title, description fields, as well as adding, deleting, and editing prices, event_dates, and event_dates.
I made separate endpoints put /event/{id}, put /price/{id}, put event_date/{id}
What can you recommend?
{
"id": 504,
"title": "First Event",
"description": "Description of First Event",
"created_at": "2022-08-16T08:42:11+00:00",
"prices": [
{
"id": 4,
"value": "12.99",
"type": "regular",
"is_entrance_free": false,
"info": "some extra infos",
"sorting": 7
}
],
"event_dates": [
{
"id": 2,
"start_date": "2022-12-10",
"end_date": "2022-12-31",
"start_time": "13:00",
"end_time": "16:00",
"entrance_time": "12:30",
"is_open_end": false,
"info": "7"
}
]
}
One of the standard ways is to POST or PUT the JSON for either the complete new record, with everything changed, effectively overwriting the old one, but keeping the same ID, or a subset.
The request would go to an endpoint for PUT /event/{id} where the action reads the current record, and gets the JSON with the information to update.
<?php
// various use statements as required
class ApiEventController extends AbstractController
{
#[Route('/api/event/{id}', methods: ['PUT'])]
public function eventPut(Request $request, \App\Entity\Event $event)
{
// Security here - ensure the current user has permission to access & edit the event
// a custom Deserializer can restrict what is used from the content
// for example, ensuring the ID, or other fields are not changed.
$serializer->deserialize(
$request->getContent(),
\App\Entity\Event::class,
'json',
[
// takes the new values, from the request content,
// and update the old value, fetched by ID from the URL
AbstractNormalizer::OBJECT_TO_POPULATE => $entity,
]
);
// $event is now the mix of the old, and new
$entityManager->persist($event);
$entityManager->flush();
// return the updated event details
}
Updating more complex contents (such as replacing an array of prices, or event_dates within the main entity) will need other deserializers and the configuration in the Event entity and others, so that the Symfony Serializer component understands what is required. https://symfony.com/doc/current/components/serializer.html and https://symfonycasts.com/tracks/symfony has more information and tutorials that well assist in learning more.
API-platform can make much of this simpler, for the simpler cases, but an understanding of the basics would be useful as a basis of understanding.
I have a JSON array, something like:
[{
"name": "John Smith",
"occupationId": 3
},
{
"name": "Steven Davis",
"occupationId": 2
}
]
The occupation response looks something like:
[{
"id": 2,
"name": "Teacher"
},
{
"id": 3,
"name": "Teaching Assistant"
}
]
Is there a way to allow RestKit to request the correct data for the occupations, given only their id? I know this can be done if the data is persisted using CoreData, via the addConnectionForRelationship:connectedBy: method, but I would rather that the data is transient, given that the server is local and there really is no need to persist the data. I'm also aware that RKObjectMapping does not support the identifiactionAttributes property, meaning I cannot (to my knowledge) designate a way to allow the class to declare a unique, identifying property.
Any help would be appreciated. I am using a mix of Objective-C and Swift, and as such, I do not mind answers in either language.
I am using MVC 4 WebApi to post several entities to Azure Table Storage. I believe that it's using formatting and not model binding because these are complex types (classes I've written) and they're being sent to the API in the body, not the URI.
This is working well for all of the entities except for one (a class called Comment), which points to the other entities (it has properties of the other entities). The JSON that I pass into the API in the body has 2 properties that contain other entities.
For Azure Table Storage, each entity has a RowKey attribute. I've noticed that once my controller builds the entity from the JSON in the request body (using the MVC4 formatting), it has the wrong value for the RowKey - it actually has the value for one of the entities referenced in the 2 properties that I mentioned. This other entity's RowKey attribute is also included in the JSON - so the JSON has 3 RowKeys, but they're all properly located in the JSON to be part of the correct entity. The Formatter just seems to be reading it wrong.
I can't save this Comment. I don't think the key problem is the reason, because the Table Storage service shouldn't care (there's no validation), but I believe that this is just part of a problem that makes the entity unsaveable by the Azure Table Storage service. Has anyone had similar problems with MVC formatting like this?
Thanks!
Edit
I forgot to mention - for testing, if I instantiate a new Comment entity inside the same controller method where the formatter is breaking, it saves just fine. So I'm fairly certain that the problem is occurring in the WebApi's parsing of the entity being passed to the controller's Post method.
Adding JSON and Model:
{
"PartitionKey": "US",
"RowKey": "com-dd1920ed-2e87-4f51-a6d1-32fa692aadae",
"AboutKey": "US|per-fb1de571-7142-47c8-bdb3-0eddd59f6ccd",
"FromPersonKey": "US|per-4c3261d8-3b1a-4bd4-8850-4d769cfbd7ef",
"CommentText": "Testing Create.",
"FromPerson": {
"PartitionKey": "US",
"RowKey": "per-4c3261d8-3b1a-4bd4-8850-4d769cfbd7ef",
"FirstName": "John",
"LastName": "Smith",
"NickName": null,
"FullName": "John Smith",
"Description": null,
"ImageLocation": null,
"Region": "US"
},
"About": {
"PartitionKey": "US",
"RowKey": "per-fb1de571-7142-47c8-bdb3-0eddd59f6ccd",
"FirstName": "George",
"LastName": "Martin",
"NickName": "Cowboy Hat",
"FullName": "George Martin",
"Description": "Ten gallons big.",
"ImageLocation": null,
"Region": "US"
},
"CommentDateTime": "2012-08-25T13:41:09.8899185Z"
}
Model (bound wrong from JSON, posted from debugging locals window). Another problem you'll notice here is that the "About" property is null. This should be a Person object, but Json.Net doesn't seem to be parsing this property, presumably because it's a type of interface rather than a class. Obviously here, it's a person that's being passed in that property in the JSON, but it could be something else, hence the use of an interface there:
comment {Classes.Comment} Classes.Comment
About null Classes.ICommentable
AboutKey US|per-fb1de571-7142-47c8-bdb3-0eddd59f6ccd string
CommentDateTime {1/1/0001 12:00:00 AM} System.DateTime
CommentText Testing Create. string
FromPerson {Classes.Person} Classes.Person
FromPersonKey US|per-4c3261d8-3b1a-4bd4-8850-4d769cfbd7ef string
PartitionKey US string
RowKey per-fb1de571-7142-47c8-bdb3-0eddd59f6ccd string
I have the following JSON structure which i get from a RestService:
{
"customer": {
"id": "123456",
[more attributes ....]
"items": [
{
"id": "1234",
},
{
"id": "2345",
}
[more items...]
]
}
}
which i successfully map into Core Data using RestKit. From another RestService (which i can not change) i then get more details to one single item in the items array. the JSON answer looks like
{
"customer": {
"id: "123456",
"item": {
"id": "1234",
"name": "foo",
[other attributes...]
}
}
}
Now the question: How can i map the second answer, so that the single item is added to the items array (or updated if it is already in there)?
Thanks for any ideas!
If you already know how to map JSON to Core Data, all that's left is just fetch theobject you want to add your item attributes to(using id or something else) and then just set it,rewriting the old one,or adding new fields.That's just general approach
If you set the appropriate primaryKeyAttribute of the RKManagedObjectMapping object you should be able to perform the mapping as you want it to.
It would actually be easier to help you, if you would post some of your mapping code, but this is how I meant it to be
Create the mapping for your customer object, defining all possible attributes and declare the mappingObject.primaryKeyAttribute = #"id"
Execute the mapping with the first request (or first answer as you put it)
After the first mapping step is finished execute the second request
This should initially create the customer objects you want and then update them.
I am looking for a library or framework that does JSON to Objective-C relational object mapping.
i.e. I need to map JSON containing objects, array of objects and dictionaries of objects to my custom objects.
something like:
DataObject {
"user" : {
"name":"Peter",
"id":1234
}
"place": "UK"
"job": {
"title" : "CTO",
"salary" : 1234567
}
"employess": [
{
"name":"Carlton",
"id":1235
},
{
"name":"Hugo",
"id":12346
}]
}
So there is a DataObject a UserObject and an employees array consisting of UserObjects.
I would like for the mapping from the JSON to my DataObject to happen "automatically", of course meant as I would like to describe the objects and there relations in the Object class and have the mapping done from this, instead of manually mapping each nested object.
(First level native objective-c properties are easily done with setValue:forKey and other KVO methods, but from there on it gets complicated).
I have been testing out RestKit but it seems there is no way to pick and choose which functionality you need from that framework, it is either all of it or none of it, and I do find it does too much for my needs.
Are anyone familiar with a library etc. out there that can do this?
Thank you in advance.
To map JSON to Objective-C objects, I have tried RestKit. I used it a while ago, so my criticisms might not apply anymore.
What I found out: nice idea. Not too complicated to plug-in. If it works, great for you. But if not, or if you need to push it a bit further, good luck to debug.
I regret the time I invested in it.
I am only looking for JSON to Objective-C objects, not the other way around.
I found a link on SO to JTObjectMapping - but can't find the original answer. Seems more lightweight and close to what I was searching, but I did not had the opportunity to try it.
An other similar class: jastor.
I prefer the approach of this two classes over RestKit, as it only takes care of one job, whereas RestKit tried to handle everything.
What you have posted above isn't valid JSON. If you made it valid JSON what you want to do is impossible without a specific schema, eg.
{
"DataObject": {
"user": {
"name": "Peter",
"id": 1234
},
"place": "UK",
"job": {
"title": "CTO",
"salary": 1234567
}
}
}
Is Dataobject a dictionary or an Object? What about User or Job? What is User is an instance of NSUser and job is an NSDictionary?
On the other hand, if you have a known schema:-
[
{
"class": "DataObject",
"properties": {
"user": {
"class": "User",
"properties": {
"name": "Peter",
"id": 1234
}
},
"place": "UK",
"job": {
"title": "CTO",
"salary": 1234567
}
}
}
]
you don't need a framework as it is trivial to map to your objects yourself once you have valid JSON. Pseudocode:-
createWithDict(dict) {
var newOb = create new(dict["class"]);
dict.properties.each( val, key ) {
if(val is dictionary && val.hasproperty("class"))
val = createWithDict(val)
newOb[key] = val
}
return newOb;
}