I want to maintain createdAt
and updatedAt
fields in my entity, while using a custom ID instead of an auto-generated one.
You can create a property for that (I have one called uuid
across all my nodes), create an index if you want it to be unique - it will depend on your graph how "unique" you need it to be.
CREATE CONSTRAINT <unique_identifier_name>
FOR (n:<Label>)
REQUIRE n.<property> IS UNIQUE;
When you are working with your nodes, you can use code similar to the following (you need at least your ParamId property - I also keep track of the Uuid of the agent creating).
MERGE (n:Node { uuid: $ParamId })
// this happens when you create the node
ON CREATE
SET n.createdAt = timestamp(),
n.updatedAt = timestamp(),
n.createdBy = $CreatedBy
// this happens when you update the node
ON MATCH
SET n.updatedAt = timestamp(),
n.updatedBy = $CreatedBy
no like,
I have Car object
public class Car{
@Id
private Long carId;
private String name;
@CreatedDate
private LocalDateTime createdAt;
@LastModifiedDate
private LocalDateTime updatedAt;
}
here for carId i have my own id's
so here i want to get audit of createdAt and updatedAt
You can map whatever Java properties are used for your Cypher query. Those are the variables with $ in my example.
but if i want to do it for many objects with many fields it will be difficult,
I was looking for more generic approach
You can dynamically build queries in your Java (no matter how many properties your objects/nodes have. You will need to create a mapping mechanism to work that out.
something like:
---
[prop1] --- [$prop1]
You just have to provide the a @Version
annotated property (SDN Reference | Version). With this, SDN can keep track of the object and determine if the entity is new or was updated on save.
@gerrit.meier
That’s great, it's working now!
Currently, if I use findById
to retrieve an object, make data changes, and save it back, the createdAt
and updatedAt
timestamps are working fine. However, what if I don’t want to use findById
and just directly create an object with a known ID, regardless of whether the ID already exists or not?
If the ID exists, only the updatedAt
timestamp should be updated. But if the ID doesn't exist, the createdAt
timestamp should also be updated.
This sounds like a bad practice in general. I would advise to also do a query upfront for an optional existing entity here. From there you could either create a new instance or use the returned one for modification.
In you case, SDN cannot determine before the update/save operation, if the object already exists because it does not have the version hint. As a consequence, this object will always be treated as new and overwrite the created data.