REST - Fetch newly created resource without hibernate - spring

I am using Spring MVC and NamedParameterJdbcOperations .
I am making a rest call to create an object and I want to return this newly created object.
How can then I return the newly created object regardless of the database used?
I am not using hibernate. In hibernate the persisted object can be returned immediately .But I want to achieve this without hibernate.

I used NamedParameterJdbcOperations's update method to get the key of newly created object and then fetched the object using this key.
To get the key -
GeneratedKeyHolder holder = new GeneratedKeyHolder();
namedParameterJdbcOperations.update(sql,sqlParameterSource,holder);
int key = holder.getKey().intValue();

Related

Retrieve the deleted record spring JPA

I am working on a spring application.
We have a specific requirement where when we get a specific event, we want to look it up in the DB. If we find the record in the DB, then we delete it from DB, create another event using the details and trigger it.
Now my concern is:
I do not want to use two different calls, one to find the record and another to
delete the record.
I am looking for a way where we can delete the record using a custom
query and simultaneously fetch the deleted record.
This saves two differnet calls to DB, one for fetch and another for delete.
What I found on the internet so far:
We can use the custom query for deletion using the annotation called #Modifying. But this does not allow us to return the object as a whole. You can only return void or int from the methods that are annotated using #Modifying.
We have removeBy or deleteBy named queries provided by spring. but this also returns int only and not the complete record object that is being deleted.
I am specifically looking for something like:
#Transactional
FulfilmentAcknowledgement deleteByEntityIdAndItemIdAndFulfilmentIdAndType(#Param(value = "entityId") String entityId, #Param(value = "itemId") String itemId,
#Param(value = "fulfilmentId") Long fulfilmentId, #Param(value = "type") String type);
Is it possible to get the deleted record from DB and make the above call work?
I could not find a way to retrieve the actual object being deleted either by custom #Query or by named queries. The only method that returns the object being deleted is deleteById or removeById, but for that, we need the primary key of the record that is being deleted. It is not always possible to have that primary key with us.
So far, the best way that I found to do this was:
Fetch the record from DB using the custom query.
Delete the record from DB by calling deleteById. Although, you can now delete it using any method since we would not be requiring the object being returned by deleteById. I still chose deleteById because my DB is indexed on the primary key and it is faster to delete it using that.
We can use reactor or executor service to run the processes asynchronously and parallelly.

saveChangesAsync update object I didn't save it

I'm using entity framework core to get an object from the database this object I will use it to create another object, so my steps was
1- get object form database
2- change a property in this object
3- use this object to add another object of another type to database
4- call
await _context.AppLogs.AddAsync(log);
await _context.SaveChangesAsync();
after that EF add my object "log" and automatically update my first object property in the database
I want to ask if that valid, and why as I didn't call update function I just change a property!!
EF will automatically detect changes made to an existing entity that is tracked by the context. The entity is tracked when you load/query from the database . So that simply modify the values assigned to properties and then call SaveChanges will automatically update the database :
var blog = context.Blogs.First();
blog.Url = "http://sample.com/blog";
context.SaveChanges();
If you don't want to update database for the entity , you can set entity state to Unchanged:
var blog = context.Blogs.First();
blog.Url = "http://sample.com/blog";
context.Entry(blog).State = EntityState.Unchanged;
context.SaveChanges();
Unchanged entities are not touched by SaveChanges. Updates are not sent to the database for entities in the Unchanged state.

Table inserting as NULL values when using springboot with spring Data JPA in save method

I am trying to save my form data into database table drivers. And using springboot with spring Data JPA . By using .save() method, database is inserting as null values. But not showing any error. I am adding my controller fie below,
DriverRepository driverRepo;
#RequestMapping(value="/driverSubmit", method=RequestMethod.POST)
public ModelAndView driverSubmit(#ModelAttribute Driver driver, Model model)
{
model.addAttribute("driver", driver);
driverRepo.save(driver);
return new ModelAndView("redirect:/dHome"); //to home page after insertoin
}
Try to test your api from swagger or postman first, and debug the code first whether you are getting values in your driver object or not. If you are getting the data in driver properly then it must be some error coming out of your form request from UI. I guess an entry of driver object is getting created in db but all the values are getting saved according to their default initial values.

How to use Hazelcast with MapStore

I am using Hazelcast as caching Solution for my application.
My application has few inserts and updates to the database and these needs to be synced to Cache also.
I want to use MapStore functionality so that when I do IMap.put(), Hazelcast takes care of persisting the Object in underlying Db and also update its cache.
In the overridden store implementation, I want to call my DAO in following way to persist the Data.
public void store(Long key, Product value)
{
log.info("Storing Data for Employee {} in Database using DataStore ", value);
Long employeeId = employeeDao.create(value);
value.setId(employeeId );
}
There are few issues listed below:-
1) In put call, I want to use "key" as the "employeeId", but this is generated only after insertion happens for this record in the Db. So how do I put into the Cache when I don't have the Id.? I want Hazelcast to use the "id" generated as part of store method call (or any other way) as the key to my Object.
Imap.put(key,new Employee("name_of_Employee","age_of_employee"))
2) The MapStore implementation's store method returns a void so I cannot return the Id generated for this Object to the Client. How can I achieve this?
I tried using MapEntryListeners on the Map but the entry added callback does not return new Object. I also added PostProcessingMapStore interface to my MapStore but could not get the new Value back to client.
Please advice
You have 2 options:
1) Generate the employeeId outside of the database. You can use the IdGenerator from Hazelcast to do this.
2) If you must let the database generate the id, then you need to put the Employee in the cache manually AFTER it has been stored in the database.

Get original object property stored in DB with Hibernate in same transaction

I opened hibernate transaction and read the object. I changed some properties of object without store. I want to get the original properties stored in DB but with
Criteria cr = new Criteria(...);
cr.add(Restrictions.eq("id", id));
cr.setProjection(Projections.property("someProperty"));
cr.uniqueResult();
or reload whole object with getSession().get(id). But as a result I got changed properties and if I reload whole object I got the same instance of changed object. How to get original object properties stored in DB with same transaction, changed object must remain with changed properties.
And how to do it with Spring transaction annotations?
You can use session.refresh() method. See documentation: http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html_single/#objectstate-loading
But this will overwrite any changes. You can clone the object before refresh, i think.

Resources