Spring Data JDBC: Can I create my UUID PKs on the client side, and not on the server? [duplicate] - spring-data

I'm playing around with spring-data-jdbc and discovered a problem, with I can't solve using Google.
No matter what I try to do, I just can't push a trivial object into the database (Bean1.java:25):
carRepository.save(new Car(2L, "BMW", "5"));
Both, without one and with a TransactionManager +#Transactional the database (apparently) does not commit the record.
The code is based on a Postgres database, but you might also simply use a H2 below and get the same result.
Here is the (minimalistic) source code:
https://github.com/bitmagier/spring-data-jdbc-sandbox/tree/stackoverflow-question
Can somebody tell me, why the car is not inserted into the database?

This is not related to transactions not working.
Instead, it's about Spring Data JDBC considering your instance an existing instance that needs updating (instead of inserting).
You can verify this is the problem by activating logging for org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate. You should see an update but no insert.
By default, Spring Data JDBC considers an entity as new when it has an id of an object type and a value of null or of a primitive type (e.g. int or long) and a value of 0.
If your entity has an attribute with #Version annotation that attribute will be used to determine if the instance is a new one.
You have the following options in order to make it work:
Set the id to null and configure your database schema so that it will automatically create a new value on insert. After the save your entity instance will contain the generated value from the database.
Note: Spring Data JDBC will set the id even if it is final in your entity.
Leave the id null and set it in a Before-Convert listener to the desired value.
Let your entity implement Persistable. This allows you to control when an entity is considered new. You'll probably need a listener as well so you can let the entity know it is not new any longer.
Beginning with version 1.1 of Spring Data JDBC you'll also be able to use a JdbcAggregateTemplate to do a direct insert, without inspecting the id, see https://jira.spring.io/browse/DATAJDBC-282. Of course, you can do that in a custom method of your repository, as is done in this example: https://github.com/spring-projects/spring-data-examples/pull/441

Related

FIWARE Orion: change entity type

In Orion, is it possible to change the type of an entity?
Related question, it is possible to change the type of an attribute?
Edit: Changing the type of an entity doesn't seem to be possible. So creating a new entity seems to be a solution. But how to preserve dateCreated and dateModified?
In Orion, is it possible to change the type of an entity
Not directly. Entity id and entity type are immutable. However, you can create a copy of the entity with the new type, then delete the old entity. That will have effectively the same effect.
Related question, it is possible to change the type of an attribute?
Yes, it is. When you update an attribute, not only the value but also the type (and metadata) can be changed.
EDIT: dateModified and dateCreation attributes and metadata are designed to be managed by Context Broker automatically. Clients cannot modify them, they are "read-only". The idea is that a given context consumer client (which, in principle, is independent of the context producer client creating/updating the entity) has a trustable timestamp that nobody could alter.
So, you have basically two alternatives:
Use your custom timestamp attributes and metadata. They can be "moved" to the new entity when you create it. However, CB will not maintain them automatically so your application would have to do it.
Use an out-of-API process, moving the entity at DB level. However, this can be complicated, as you need direct access to DB.
EDIT2: for the second case (DB based process) take into account the Orion DB model. In particular:
_id.type is for the entity type
creDate is for the entity creation date
modDate is for the entity modification date
attrs.A.creDate is for the attribute A creation date
attrs.A.modDate is for the attribute A modification date

How to properly use EFCore with SignalR Core (avoid caching entities)

I just found some really strange behaviour which turns out it is not so strange at all.
My select statement (query from database) worked only the first time. The second time, query from database was cached.
Inside Hub method I read something from database every 10 seconds and return result to all connected clients. But if some API change this data, Hub context does not read actual data.
In this thread I found this:
When you use EF it by default loads each entity only once per context. The first query creates entity instance and stores it internally. Any subsequent query which requires entity with the same key returns this stored instance. If values in the data store changed you still receive the entity with values from the initial query. This is called Identity map pattern. You can force the object context to reload the entity but it will reload a single shared instance.
So my question is how to properly use EFCore inside SignalR Core hub method?
I could use AsNoTracking, but I would like to use some global setting. Developer can easily forget to add AsNoTracking and this could mean serving outdated data to user.
I would like to write some code in my BaseHub class which will tell context do not track data. If I change entity properties, SaveChanges should update data. Can this be achieved? It is hard to think all the time to add AsNoTracking when querying from hub method.
I would like to write some code in my BaseHub class which will tell context do not track data.
The default query tracking behavior is controlled by the ChangeTracker.QueryTrackingBehavior property with default value of TrackAll (i.e. tracking).
You can change it to NoTracking and then use AsTracking() for queries that need tracking. It's a matter of which are more commonly needed.
If I change entity properties, SaveChanges should update data.
This is not possible if the entity is not tracked.
If you actually want tracking queries with "database wins" strategy, I'm afraid it's not possible currently in EF Core. I think EF6 object context services had an option for specifying the "client wins" vs "database wins" strategy, but EF Core currently does not provide such control and always implements "client wins" strategy.

Updating the ID of an instance in JPA

I am using JPA annotations(hibernate implementation), and i want to change the ID of an entity by merging it.There is any annotation or solution to avoid duplicating then removing the entity?
This is not possible using JPA, for good reasons:
you have an entity removed from the persistence context and you want to reattach it, how possibly could it be connected to the original row it was modified from if you remove the only way to make the connection? Ok, let's assume we store the original id and try to go from there, but now since id is modifiable there is 0 guarantee that it wasn't changed by some other process as well while it was detached, making our stored original id useless and causing complete chaos.
You can do workarounds though:
use a native query to modify the row
don't use this column as your primary key but instead create a new one with generated sequences
duplicate then remove entity as you said is also completely valid and safe as it's in the same transaction
you can change Entity's id in jpa using JPQL like this example :
public void updateUsername(User userToUpdate,String newUserName) {
EntityManager manager=ConnectionDao.getConnecting();
User user=find(userToUpdate.getUsername());
manager.getTransaction().begin();
manager.createQuery("update User u set u.username=\'"+newUserName+"\'").executeUpdate();
manager.getTransaction().commit();
return;
}

persisting an update query using openJPA

I am attempting to update an existing record using JPA. The following link seems to suggest that the only way to update a record would be to write the update query for it
enter link description here
Which is fine. But again, I am wondering why am I pulling this out of stored proc to use all f the magic of open JPA?
I thought that If I had an instance of a JPA object that if I tried to persist to the database using a call similar to this
emf.persist(launchRet)
the JPA framework would check to see if the record allready exists, if so, it would then proceed to make the changes to that record, if not, it would just add a new record. Which would be really cool. Instead, I am going to have to end up writing all that logic myself in an update query. Which is fine, But why can't I just use a stored proc and just pass it all the necessary values?
UPDATE: CODE EXPLAINING WHAT MY LAST COMMENT IS ALL ABOUT
try{
launchRet = emf.find(QuickLaunch.class, launch.getQuickLaunchId());
if(launchRet==null){
emf.getTransaction().begin();
emf.persist(launchRet);
emf.getTransaction().commit();
}
else{
emf.refresh(launchRet);
}
}
The variable launch is passed into the method...
public QuickLaunch UpdateQuickLaunchComponent(QuickLaunch launch)
Would I simple just set the found launch launchRet equal to the launch that was passed in?
Read the link that you posted:
You can modify an entity instance in one the following ways:
Using an Updating Query
Using the Entity's Public API
[...]
The way used in 99% of the cases is the second way:
Foo someExistingFoo = em.find(Foo.class, someExistingFooId);
someExistingFoo.setSomeValue(theNewValue);
// no need to call any persist method: the EM will flush the new state
// of the entity to the database when needed
Of course, the entity can also be loaded via a query, or by navigating through the graph of entities.
If you have a detached entity, and you want to persist its state to the database, use the EntityManager.merge() method. It finds the entity with the same ID as the detached one passed as argument, copies the state from the detached entity to the attached one, and returns the attached one:
Foo attachedModifiedFoo = em.merge(detachedFoo);
If the detached entity isn't persistent (i.e. doesn't have any ID), then it is created and made persistent.

Create new or update existing entity at one go with JPA

A have a JPA entity that has timestamp field and is distinguished by a complex identifier field. What I need is to update timestamp in an entity that has already been stored, otherwise create and store new entity with the current timestamp.
As it turns out the task is not as simple as it seems from the first sight. The problem is that in concurrent environment I get nasty "Unique index or primary key violation" exception. Here's my code:
// Load existing entity, if any.
Entity e = entityManager.find(Entity.class, id);
if (e == null) {
// Could not find entity with the specified id in the database, so create new one.
e = entityManager.merge(new Entity(id));
}
// Set current time...
e.setTimestamp(new Date());
// ...and finally save entity.
entityManager.flush();
Please note that in this example entity identifier is not generated on insert, it is known in advance.
When two or more of threads run this block of code in parallel, they may simultaneously get null from entityManager.find(Entity.class, id) method call, so they will attempt to save two or more entities at the same time, with the same identifier resulting in error.
I think that there are few solutions to the problem.
Sure I could synchronize this code block with a global lock to prevent concurrent access to the database, but would it be the most efficient way?
Some databases support very handy MERGE statement that updates existing or creates new row if none exists. But I doubt that OpenJPA (JPA implementation of my choice) supports it.
Event if JPA does not support SQL MERGE, I can always fall back to plain old JDBC and do whatever I want with the database. But I don't want to leave comfortable API and mess with hairy JDBC+SQL combination.
There is a magic trick to fix it using standard JPA API only, but I don't know it yet.
Please help.
You are referring to the transaction isolation of JPA transactions. I.e. what is the behaviour of transactions when they access other transactions' resources.
According to this article:
READ_COMMITTED is the expected default Transaction Isolation level for using [..] EJB3 JPA
This means that - yes, you will have problems with the above code.
But JPA doesn't support custom isolation levels.
This thread discusses the topic more extensively. Depending on whether you use Spring or EJB, I think you can make use of the proper transaction strategy.