Not able to save data in cosmos db through spring boot micro service - spring-boot

i'm trying to save entity in cosmos db through spring boot micro service. I'm not getting any error, only 1 warning '[osEventLoop-6-1] c.a.d.c.i.d.rntbd.RntbdRequestManager : ChannelHandlerContext(RntbdRequestManager#0, [id: 0x999bfbac, L:0.0.0.0/0.0.0.0:56979 ! R:cdb-ms-prod-*****-****.documents.azure.com/********]) channelUnregistered exceptionally'
but data is not getting saved in cosmos db. i'm using reactivecosmosrepository.
here is my pom.xml
<properties>
<java.version>1.8</java.version>
<azure.version>2.2.0</azure.version>
</properties>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-cosmosdb-spring-boot-starter</artifactId>
<version>${azure.version}</version>
</dependency>
my entity
import com.microsoft.azure.spring.data.cosmosdb.core.mapping.Document;
#Document(collection = "dashboardsnapshot")
public class DashboardSnapshot {
private String id;
private String clientId;
private String snapshotJSON;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getSnapshotJSON() {
return snapshotJSON;
}
public void setSnapshotJSON(String snapshotJSON) {
this.snapshotJSON = snapshotJSON;
}
#Override
public String toString() {
return "DashboardSnapshot [id=" + id + ", clientId=" + clientId + ", snapshotJSON=" + snapshotJSON + "]";
}
}
my repository
import org.springframework.stereotype.Repository;
import com.ka.concept.dashboardconfig.entity.DashboardSnapshot;
import com.microsoft.azure.spring.data.cosmosdb.repository.ReactiveCosmosRepository;
import reactor.core.publisher.Flux;
#Repository
public interface SnapshotDao extends ReactiveCosmosRepository<DashboardSnapshot, String>{
Flux<DashboardSnapshot> findbyClientId(String ClientId);
}
my service
#Service
public class SnapshotServiceImpl implements SnapshotService{
#Autowired
public SnapshotDao snapshotdao;
#Override
public boolean saveSnapshotConfig(DashboardSnapshot snapshotJSON) {
// TODO Auto-generated method stub
snapshotdao.save(snapshotJSON);
return true;
}
}

#AksYou should call subscribe(). The publisher does not do anything till some one subscribes.
snapshotdao.save(snapshotJSON).subscribe();

Related

How i can separate a table which have null and non null elements using spring concept

for instance, I have a table with different locations and their description too. Now I need to print the locations which have descriptions on one page or in one box and simultaneously the locations which do not have descriptions should be displayed on another page.
NOTE:
this has to be done by using spring concept only
for reference, I was able to print the locations which have no descriptions in the below fashion.
entity
package com.test.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
#Entity
#Table(name= "loc_dtls")
public class Location {
#Id
#GeneratedValue(strategy = jakarta.persistence.GenerationType.IDENTITY)
private long id;
#Column(name="place_name")
private String placeName;
#Column(name="place_description")
private String placeDesc;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getPlaceName() {
return placeName;
}
public void setPlaceName(String placeName) {
this.placeName = placeName;
}
public String getPlaceDesc() {
return placeDesc;
}
public void setPlaceDesc(String placeDesc) {
this.placeDesc = placeDesc;
}
#Override
public String toString() {
return "Location [id=" + id + ", placeName=" + placeName + ", placeDesc=" + placeDesc + "]";
}
}
controller
#GetMapping("/")
public String singleElement(Model m) {
List<Location> util = locRepo.findByplaceDesc(null);
m.addAttribute("unlist_places", util);
return "index";
}
repository
#Repository
public interface LocationRepository extends JpaRepository<Location, Long> {
public List<Location> findByplaceName(String placeName);
public List<Location> findByplaceDesc(String placeDesc);
}
html
<select>
<option>--select--</option>
<option th:each="p : ${unlist_places}"
th:text="${p.placeName}">
</option>
</select>
MySql Database

Java Spring Boot Entites not saving to JpaRepository

That's my first project with Spring Boot implemented. I tried going step by step with official Spring tutorial but I'm stuck with a problem that I can't find any answer about.
Whenever I try to call findAll() or find() method on my repository it returns empty array [].
Even with manual preloading enitites like done in tutorial and immediately trying to display database content I get the same result.
I can guess I'm missing something silly, but I can't figure it out for some hours now. What's the cause? Tomcat/jpa/spring version mismatch? Missing annotation somewhere?
Here's my AnimalRepository.java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface AnimalRepository extends JpaRepository<Animal, Long> {
}
LoadDatabase.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.Transactional;
#Configuration
class LoadDatabase {
private static final Logger log = LoggerFactory.getLogger(LoadDatabase.class);
#Bean
CommandLineRunner initDatabase(AnimalRepository repository) {
return args -> {
log.info("Preloading " + repository.save(new Lion("Bilbo")));
log.info("Preloading " + repository.save(new Lion("Frodo")));
log.info(repository.findAll().toString()); //try to log content to console
};
}
}
The logging above basically ends up with this console output:
logging result
Probably not as important, but AnimalController.java
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
public class AnimalController {
private final AnimalRepository repository;
AnimalController(AnimalRepository repository) {
this.repository = repository;
}
#GetMapping("/animals")
List<Animal> all() {
repository.save(new Lion("Bilbo")); //this doesn't work either
return repository.findAll();
}
#PostMapping("/animals")
Animal newAnimal(#RequestBody Animal newAnimal) {
return repository.save(newAnimal);
}
#GetMapping("/animals/{id}")
Animal one(#PathVariable Long id) {
return repository.findById(id)
.orElseThrow(() -> new AnimalNotFoundException(id));
}
#PutMapping("/animals/{id}")
Animal replaceAnimal(#RequestBody Animal newAnimal, #PathVariable Long id) {
return repository.findById(id)
.map(animal -> {
animal.setName(newAnimal.getName());
animal.setSpecies(newAnimal.getSpecies());
return repository.save(animal);
})
.orElseGet(() -> {
newAnimal.setId(id);
return repository.save(newAnimal);
});
}
#DeleteMapping("/animals/{id}")
void deleteAnimal(#PathVariable Long id) {
repository.deleteById(id);
}
}
And the finally Lion.java
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import java.util.Objects;
#Entity
public class Lion implements Animal {
private #Id
#GeneratedValue Long id;
private String name;
private String species;
private int requiredFood;
//private Zone zone;
public Lion(String name) {
this.name = name;
this.species = this.getClass().getSimpleName();
this.requiredFood = LION_REQUIRED_FOOD;
}
public Lion() {
}
#Override
public Long getId() {
return id;
}
#Override
public void setId(Long id) {
this.id = id;
}
#Override
public String getName() {
return name;
}
#Override
public void setName(String name) {
this.name = name;
}
#Override
public String getSpecies() {
return species;
}
#Override
public void setSpecies(String species) {
this.species = species;
}
#Override
public int getRequiredFood() {
return requiredFood;
}
#Override
public void setRequiredFood(int requiredFood) {
this.requiredFood = requiredFood;
}
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Animal animal))
return false;
return Objects.equals(this.id, animal.getId()) && Objects.equals(this.name, animal.getName())
&& Objects.equals(this.species, animal.getSpecies());
}
#Override
public int hashCode() {
return Objects.hash(this.id, this.name, this.species);
}
#Override
public String toString() {
return "Animal{" + "id=" + this.id + ", name='" + this.name + '\'' + ", species='" + this.species + '\'' + '}';
}
}
I tried switching JpaRepository to CrudRepository, but that didn't work out.
I think the problem here is that your data haven't been saved to the database, because of the transaction. try to change your repository.save() to repository.saveAndFlush()

Spring Boot MongoDB - MongoDB cannot generate 'ID'

I have some problem with my Spring Boot application.
When I save one document in my repository application works fine, but when I save more than one documents, my aplication not working. Here is my code.
Article.java
import org.springframework.data.annotation.Id;
public class Article {
#Id
private String id;
private String title;
private String description;
public Article() {}
public Article(String title, String description) {
this.title = title;
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "Article{" +
"id='" + id + '\'' +
", title='" + title + '\'' +
", description='" + description + '\'' +
'}';
}
}
ArticleRepository.java
public interface ArticleRepository extends MongoRepository<Article, String> {}
DatabaseLoader.java
import java.util.HashSet;
import java.util.Set;
#Component
public class DatabaseLoader implements CommandLineRunner {
#Autowired
private ArticleRepository articleRepository;
#Override
public void run(String... args) throws Exception {
articleRepository.deleteAll();
// example 1: if I save one document to my repo everything works fine
// example: articleRepository.save(new Article("Title 1", "description 1"));
// console returns: Article{id='596f480e4e118123574a13f1', title='Title 1', description='description 1'}
// but here is problem
Set<Article> articleList = new HashSet<Article>(){
{
add(new Article("Title 1", "description 1"));
add(new Article("Title 2", "description 2"));
}
};
// because if I try to save my collection
articleRepository.save(articleList);
// console returns: com.mongodb.DuplicateKeyException:
// Write failed with error code 11000 and error message
// 'insertDocument :: caused by :: 11000 E11000 duplicate key
// error index: test.article.$user dup key: { : null }'
System.out.println(articleRepository.findAll());
}
}
Application.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(SimpleMongoApplication.class, args);
}
}
Do you know, why I have this problem?
Thank you for all your answers.
OK, here is #Afridi's solution.
All you need to do is adding #Document(collection="collection-name") annotation in your document. here is an example:
#Document(collection = "articles") // here is solution
public class Article {
#Id
private String id;
private String title;
private String description;
//getters, setters and constructor
}

Couchbase query exception on runtime Unsupported parameter type for key: class com.couchbase.client.protocol.views.Query

I am getting this exception every time i try to query a view on Couchbase DB from my spring boot application.
Unsupported parameter type for key: class com.couchbase.client.protocol.views.Query.
I was setting a string on setKey() method of Query class, got an exception. But then I checked the API and provided a json to setKey, still not working. Have searched a lot but could not get this to work.
I am sharing the code snippet in this post as well.
Application.properties
spring.couchbase.bucket.password=
spring.couchbase.bucket.name=default
spring.couchbase.bootstrap-hosts=127.0.0.1
spring.data.couchbase.repositories.enabled=true
PlayerRepository
public interface PlayerRepository extends CouchbaseRepository<Player, Integer>
{
#View(designDocument = "player", viewName = "all")
public List<Player> findAll();
#View(designDocument = "player", viewName = "by_Name")
public Player findByName(Query query);
#View(designDocument = "player", viewName = "by_TeamId")
public List<Player> findByTeamId(Query query);
}
Player.java
#Document
public class Player
{
#Id
int playerId;
#Field
String name;
#Field
String type;
#Field
String country;
#Field
String playingHand;
#Field
String era;
#Field
int teamId;
#Field
int odiCenturies;
#Field
int testCenturies;
public Player(){}
public Player(int playerId, String name, String type, String country, String playingHand, String era, int teamId,
int odiCenturies, int testCenturies) {
super();
this.playerId = playerId;
this.name = name;
this.type = type;
this.country = country;
this.playingHand = playingHand;
this.era = era;
this.teamId = teamId;
this.odiCenturies = odiCenturies;
this.testCenturies = testCenturies;
}
SpringBootApplication class
#SpringBootApplication
public class CricketTeamSelectionMain
{
/**
* #param args
*/
public static void main(String[] args)
{
SpringApplication.run(CricketTeamSelectionMain.class, args);
}
#Configuration
#EnableCouchbaseRepositories
public static class DBConfig extends AbstractCouchbaseConfiguration
{
#Value("${spring.couchbase.bucket.name}")
private String bucketName;
#Value("${spring.couchbase.bucket.password}")
private String password;
#Value("${spring.couchbase.bootstrap-hosts}")
private String ip;
#Override
public String getBucketName() {
return this.bucketName;
}
#Override
public String getBucketPassword() {
return this.password;
}
#Override
public List<String> getBootstrapHosts() {
return Arrays.asList(this.ip);
}
}
}
PlayerService class
package org.ups.fantasyCricket.service;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.ups.fantasyCricket.CricketTeamSelectionMain.DBConfig;
import org.ups.fantasyCricket.Model.Player;
import org.ups.fantasyCricket.Repository.PlayerRepository;
import com.couchbase.client.CouchbaseClient;
import com.couchbase.client.protocol.views.Query;
import com.couchbase.client.protocol.views.View;
import com.couchbase.client.protocol.views.ViewResponse;
#Service
public class PlayerService
{
#Autowired
PlayerRepository playerRepo;
private CouchbaseClient client;
public List<Player> getAllPlayers()
{
List<Player> allPlayerLists = new ArrayList<Player>();
/*allPlayerLists.addAll((Collection<? extends Player>) playerRepo.findAll());
return allPlayerLists;*/
playerRepo.findAll().forEach(allPlayerLists::add);
return allPlayerLists;
}
public Player getPlayerByName(String name)
{
DBConfig dbCon = new DBConfig();
try
{
Query query = new Query();
query.setIncludeDocs(true);
query.setKey(name);
Player player = playerRepo.findByName(query);
return player;
}
catch(Exception e)
{
e.printStackTrace();
System.out.println(e.getMessage());
}
return null;
}
public String addPlayer(Player player)
{
playerRepo.save(player);
return "Success";
}
public String updatePlayer(Player player, int id)
{
playerRepo.save(player);
return "Success";
}
public List<Player> getPlayersByTeamId(int teamId)
{
List<Player> allPlayerLists = new ArrayList<Player>();
Query query = new Query();
query.setKey(String.valueOf(teamId));
playerRepo.findByTeamId(query).forEach(allPlayerLists::add);
return allPlayerLists;
}
public String addPlayers(List<Player> players)
{
playerRepo.save(players);
return "Success";
}
}
View by_Name on CouchBase DB
function (doc) {
emit(doc.name, doc);
}
Which version of spring-data-couchbase are you using? Starting with 2.x, the #Query annotation uses query derivation and you cannot use a ViewQuery as a parameter anymore... Have a look at the docs, on query derivation with a view.
You could probably use the CouchbaseTemplate to perform a manual query though.

Jackson doesn't serialize nested classes in Spring

I have an implementation of a REST front-end UI and a Spring JPA based backend.
In it, I have a class like this:
public class TaskInfo {
// 4 fields
private Parent parentList;
// 3 fields
// Getters and Setters
}
class Parent {
// Parent class code
}
When I try to take a Response, I find that in place of Parent, I get a null value. Why is this Parent object not getting serialized? Is there a workaround to this? Or should I just include the fields of Parent in this class directly?
Edit: I'm using Jackson for serialization.
For me the below works fine. I think this is equivalent to the code present in your question
package jackson;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class TaskInfo {
public TaskInfo(String id, Parent parentList) {
super();
this.id = id;
this.parentList = parentList;
}
private String id;
private Parent parentList;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Parent getParentList() {
return parentList;
}
public void setParentList(Parent parentList) {
this.parentList = parentList;
}
public static void main(String args[]) throws IOException {
Parent parent = new Parent("123");
TaskInfo taskInfo = new TaskInfo("taskID", parent);
String json = new ObjectMapper().writeValueAsString(taskInfo);
System.out.println(json);
}
}
class Parent {
public Parent(String parentId) {
this.parentId = parentId;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
private String parentId;
// Parent class code
}
It prints the following output
{"id":"taskID","parentList":{"parentId":"123"}}
I used jackson
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.1</version>
</dependency>
It doesn't serialize because your properties are not public. Make the properties public and it works.

Resources