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

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.

Related

Expose custom query in Spring Boot Rest API with multiple joins

I have an Spring REST Api and a MySQL Database, now I would like to expose the result of an custom query with multiple joins.
I have tried multiple suggestions that I found online but none of them were working for me so far.
What I want to do is something like a read only DTO that has all the fields of my custom query so that in the end I have one api page exposing the DTO data as JSON so my client (Angular) can read the data from there.
I already tried to:
create an #RestController with an injected EntityManager that executes a NativeQuery and then populates the DTO with the returned data but since my DTO is no Entity I get an Hibernate Mapping Exception
create a custom Repository and its Impl but with a similar outcome
place the Query inside an existing #Entity that is part of the Query statement
What am I missing here? Do I have to annotate my DTO maybe? Cuttently it's just a POJO, I think the #Entity annotation is not the right thing here since I don't want a Table created from my DTO.
Fixed it by letting the Query return an Array of type Object and afterwards mapping it to the DTO Constructor.

REST - Fetch newly created resource without hibernate

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();

spring hibernate merge example

I have a Spring 4 and Hibernate 5 back-end RESTful web-service. This works great and is all unit tested. The front-end is a SmartGWT 5.0p application which uses DataSources, not RestDataSources to communicate with the back-end.
The front-end SmartGWT 5.0p uses a listgrid to edit data, and then the ListGrid is attched to a datasource. Only the edited data in the ListGrid is sent back, not the entire row. If I could, I'd like to be able send backthe entire listgrid row with edited data, and the unedited data. If I could get an answer to that, that would be great.
Or, the alternate is we let SmartGWT only send back part of the data which is edited. This comes to the back-end as JSON and is changed into an Object/Entity. The controller/end-point is not in a session yet, but then we call a method in the service layer which is transactional.
So, then question becomes we have a detached object in a session in the method in the service layer. We have a detached object with a database primary key ... but it also has 1 or 2 fields of updated data, and now we want to merge that data back to the database. We can't call an update with this entity because with the partial data, some of the fields are being set to null. In reality, we want to pull back the item from the databae, update the edited fields, and then write the data back to the database.
I could do this all manually ... but do I have to? I expect there is a more graceful way to handle this.
Thanks!
This is only a partial answer:
I can make SmartGWT combine old values and new values with a link I found here:
SMARTGWT DataSource (GWT-RPC-DATASource) LISTGRID
And the code is as follows:
private ListGridRecord getEditedRecord(DSRequest request)
{
// Retrieving values before edit
JavaScriptObject oldValues = request
.getAttributeAsJavaScriptObject("oldValues");
// Creating new record for combining old values with changes
ListGridRecord newRecord = new ListGridRecord();
// Copying properties from old record
JSOHelper.apply(oldValues, newRecord.getJsObj());
// Retrieving changed values
JavaScriptObject data = request.getData();
// Apply changes
JSOHelper.apply(data, newRecord.getJsObj());
return newRecord;
}
This JSON string contains the new fields updated, and the old fields. When this json string is sent back to the RESTful back end, the Jackson Mapper creates an entity and puts all the fields in, this is essentially a detached entity. It's an object outside of the session, but the id resides in the database.
Because I have a complete entity, I can all an update, and that works.
Problem solved.
BUT, I'd still like to find out an elegant solution for taking a detached entity, get the original record from the database, and then merge these two objects, and then finally update the record.
In the Service layer in Spring which has a transaction, and creates the session,
a manual process, which I don't want to do might look something like this:
1) get the id from the updatedEntity
2) get that attachedEntity from the database using that id
3) compare the fields
if( updatedEntity.updateField1 != null )
{ attachedEntity.setField1(updatedEntity.updateField1) }
If I had to do step 3 for multiple fields,
that's not very elegant.
4) Update attachedEntity to the database, because it now has updated fields.
So, again, an elegant solution to fix this might be helpful. Thanks!

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