Spring Boot save method is trying to update and returns error like:
org.springframework.dao.IncorrectUpdateSemanticsDataAccessException:
Failed to update entity [com.xx.xx.Account#78a31407]. Id 1 not found
in database.
But my database is completely empty and I want to add new Entity. Here is the screenshots:
And here is the code:
#RequestMapping(path = "/banking/add", method = RequestMethod.POST)
public #ResponseBody ResponseEntity addAccount(#Validated #RequestBody Account account) throws IOException {
if(!account.getType().equals("TL") && !account.getType().equals("Altın") && !account.getType().equals("Dolar")) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid Account Type: " + account.getType());
}
System.out.println(account.getId());
account.setLastDate(new SimpleDateFormat("dd-MM-yyyy").format(new Date()));
BankingLogger.writeAccountToTheFile(account);
AccountCreateSuccessResponse res = new AccountCreateSuccessResponse("Account Created", account.getId());
this.repository.save(account);
return ResponseEntity.status(HttpStatus.CREATED).body(res);
}
and here is the request json:
{
"id": "1",
"name" : "Doğukan",
"surname" : "Gülyaşar",
"email" : "xxxx#gmail.com",
"tc" : "123123123",
"type" : "Dolar",
"isDeleted": "false"
}
Remove the id from the payload. Create or update logic is triggered by having or not having id. If the id is set beforehand, the entity with specified id is updated, otherwise new entity is created and id will be assigned by the database.
Related
First of all, the api works as intended locally, when deploying to azure functions app, the api endpoint keeps loading and it will eventually show HTTP.504(Gateway Timeout)
page keeps loading, no response from azure functions
Integration
I'm looking to fetch all data from the collection when I call HttpTrigger
Function.java
#FunctionName("get")
public HttpResponseMessage get(
#HttpTrigger(name = "req",
methods = {HttpMethod.GET, HttpMethod.POST},
authLevel = AuthorizationLevel.ANONYMOUS)
HttpRequestMessage<Optional<String>> request,
#CosmosDBInput(name = "database",
databaseName = "progMobile",
collectionName = "news",
partitionKey = "{Query.id}",
connectionStringSetting = "CosmosDBConnectionString")
Optional<String> item,
final ExecutionContext context) {
// Item list
context.getLogger().info("Parameters are: " + request.getQueryParameters());
context.getLogger().info("String from the database is " + (item.isPresent() ? item.get() : null));
// Convert and display
if (!item.isPresent()) {
return request.createResponseBuilder(HttpStatus.BAD_REQUEST)
.body("Document not found.")
.build();
}
else {
// return JSON from Cosmos. Alternatively, we can parse the JSON string
// and return an enriched JSON object.
return request.createResponseBuilder(HttpStatus.OK)
.header("Content-Type", "application/json")
.body(item.get())
.build();
}
}
Function.json
{
"scriptFile" : "../ProgMobileBackend-1.0-SNAPSHOT.jar",
"entryPoint" : "com.function.Function.get",
"bindings" : [ {
"type" : "httpTrigger",
"direction" : "in",
"name" : "req",
"methods" : [ "GET", "POST" ],
"authLevel" : "ANONYMOUS"
}, {
"type" : "cosmosDB",
"direction" : "in",
"name" : "database",
"databaseName" : "progMobile",
"partitionKey" : "{Query.id}",
"connectionStringSetting" : "CosmosDBConnectionString",
"collectionName" : "news"
}, {
"type" : "http",
"direction" : "out",
"name" : "$return"
} ]
}
Azure Functions monitor log does not show any error
Running the function in the portal(Code + Test menu) does not show any error either
httpTrigger I'm using: https://johnmiguel.azurewebsites.net/api/get?id=id
I added CosmosDBConnectionString value to Azure Functions App configuration(did not check on "Deployment slot" option)
I'm using an instance of CosmosDB for NoSQL
Functions App runtime is set to Java and version set to Java 8
figured it out. Java function was in Java 17 and Function App in Java 8.
I have successfully implemented adding a visit and showing a list of all visits, but now I'm stuck on creating a view for a single visit.
My findById function works:
logger.info("Visit id 2 -> {}", repository.findById(2));
Visit id 2 -> DentistVisitDTO[id='0', dentistName='Mait Kuusevaik', visitTime='2018-10-12T12:15']
And when I click on a list item it sucessfully redirects to a url using ID (i.e "/results/1" and so on. Is there a way I can use the ID from the URL and somehow render the item on the page using findById()?
I'm new to Spring and Thyme.
public DentistVisitDTO findById(long id) {
return jdbcTemplate.queryForObject("SELECT * FROM DENTIST_VISIT where id=?", new Object[] { id },
new BeanPropertyRowMapper<DentistVisitDTO>(DentistVisitDTO.class));
}
You can use the #RequestMapping annotation of SpringMVC/SpringWeb to get the id attribute from the URL:
import org.springframework.web.bind.annotation.RequestMapping;
#RequestMapping(value="/results/{id}", method=RequestMethod.GET)
public String detail(#PathVariable(value="id") String id, Model model) {
DentistVisitDTO dentistVisit = repository.findById(id);
System.out.println("GET /results [" + id + "]");
model.addAttribute("dentistVisit", dentistVisit);
return "details";
}
This question already has answers here:
Calling spring data rest repository method doesn't return links
(2 answers)
Closed 6 years ago.
I'm using Spring Data Rest to create a RESTful api. I want to handle an exception returning an entity representation like the ones generated by the Spring Data Rest repositories (with HATEOAS links). The method from where I need to return the entity representation is the following:
#ExceptionHandler(value = {ExistentUGVException.class})
#ResponseBody
protected ResponseEntity<UGV> existentUGVHandler(HttpServletRequest request, HttpServletResponse response, ExistentUGVException ex) {
return new ResponseEntity<UGV>(ex.ugv, HttpStatus.OK);
}
This implementation returns the UGV representation without links:
{
"title" : "Golden Eagle Snatches Kid",
"publishDate" : "2012-12-19T13:55:28Z",
"url" : "https://www.youtube.com/watch?v=Xb0P5t5NQWM"
}
But it would be:
{
"title" : "Golden Eagle Snatches Kid",
"publishDate" : "2012-12-19T13:55:28Z",
"url" : "https://www.youtube.com/watch?v=Xb0P5t5NQWM",
"_links" : {
"self" : {
"href" : "http://localhost/youTubeVideos/Xb0P5t5NQWM"
},
"youTubeVideo" : {
"href" : "http://localhost/youTubeVideos/Xb0P5t5NQWM{?projection}",
"templated" : true
},
"user" : {
"href" : "http://localhost/youTubeVideos/Xb0P5t5NQWM/user"
}
}
}
You'll have to transform your ResponseEntity to Resource first and then add the links manually.
It should be something like this :
#ExceptionHandler(value = {ExistentUGVException.class})
#ResponseBody
protected ResponseEntity<Resource<UGV>> existentUGVHandler(HttpServletRequest request, HttpServletResponse response, ExistentUGVException ex) {
final Resource<UGV> resource = getResource(ex.ugv);
return new ResponseEntity<Resource<UGV>>(resource, HttpStatus.OK);
}
public Resource<T> getResource(T object, Link... links) throws Exception {
Object getIdMethod = object.getClass().getMethod("getId").invoke(object);
Resource<T> resource = new Resource<T>(object); // The main resource
final Link selfLink = entityLinks.linkToSingleResource(object.getClass(), getIdMethod).withSelfRel();
String mappingRel = CLASSMAPPING.getMapping(this.getClass());
final Link resourceLink = linkTo(this.getClass()).withRel(mappingRel);
resource.add(selfLink, resourceLink);
resource.add(links);
return resource;
}
Take a look here, there's all you need : spring hateoas documentation
I am using Spring Data with a Mongo DB embedded database and have the following document structure:
{
id : 111
messaage : abcd
commentsList: [
{
id : 123
text: test text
numberOfLikes : 5
numberOfDislikes: 2
}
]
}
I am trying to get a comment by id and update the numberOfLikes field by one and can't seem to get it to work, here is what I've tried and the java class structure:
public class Post {
private String id;
private String message;
private List<Comment> commentsList = new ArrayList<>();
...
}
public class Comment {
private String id;
private String text;
private int numberOfLikes;
private int numberOfDislikes;
...
}
Query query = new Query();
query.addCriteria(Criteria.where("commentsList._id").is("123"));
List<MongoComment> commentList = mongoTemplate.find(query, MongoComment.class);
Currently the returned list is always null.
Since you are trying to get a comment by id and update the numberOfLikes field by one, you essentially want to replicate this mongo shell update operation:
db.post.update(
{ "commentsList.id": "123" },
{
"$inc": { "commentsList.$.numberOfLikes": 1 }
}
)
The equivalent Spring Data MongoDB code follows:
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query;
import static org.springframework.data.mongodb.core.query.Update;
...
WriteResult wr = mongoTemplate.updateMulti(
new Query(where("commentsList.id").is("123")),
new Update().inc("commentsList.$.numberOfLikes", 1),
MongoPost.class
);
The id of the elements in the array "commentsList" is "id" (without the '_').
query.addCriteria(Criteria.where("commentsList.id").is("123"))
That should work.
The "_id" you're trying to query is the identifier Mongodb automatically generates for each document. Your document in the database looks like this:
{
_id: ObjectId("56b46e1d1d1353e38886dcc34f"),
id : 111,
messaage : "abcd",
commentsList: [
{
id : 123,
text: "test text",
numberOfLikes : 5,
numberOfDislikes: 2
}
]
}
I have a document in Cloudant DB which is as follows:
{
"_id": "9567e004dc1f1063f4e5cfa9471f5f6b",
"_rev": "1-77c3cab7cc5ba63277843b4dafc6af42",
"DocumentUri": "http://www.ibm.com/common/ssi/cgi-bin/ssialias?htmlfid=515-125EN&infotype=AN&subtype=CA&appname=skmwww",
"username": "SKM",
"DocumentDetails": {
"ContentType": "text/plain",
"Language": "en",
"Content": "515-125 Price Change(s):Price change: DOORS Family AU price change Today,
}
The _id value is stored in a properties file in my app. I need to know how to get the id name from my properties file, then assign it to document id in Cloudant DB using Java.
You can read this to figure out how to read a properties file.
Then you can create a Java Object with _id as a member variable, then insert that object into your db - the _id attribute in Cloudant will automatically use whatever you set the _id to in your object
public class Reservation {
public String _id;
public String name;
public Reservation(){
_id = "";
name = "";
}
}
And when you are ready to save it. This uses the java-cloudant client
//Cloudant Connection
CloudantConnect connectParams = new CloudantConnect();
CloudantClient client = new CloudantClient(cloudantUrl,cloudantUsername, cloudantPassword);
Database db = client.database("myDatabase", false);
Reservation reservation = new Reservation();
Response dbResponse = db.save(reservation);
System.out.print(dbResponse.toString());