Retrive a object of parent class into child class in spring boot application - spring

I am building REST API using spring boot application. I have connected application to Mongodb database. I have created a database named "Employee" and collection as "Employee" itself. Now i want to create a document. I have three class. Class A, Class B and class C.
Class A is the parent Class having property (id,name,password). Class B is child class and extends Class A with property(address,phoneNumber) and class C is child class which also extends class A with property (fatherName,MotherName).
Now i want to add the data to database as object of B or object of C and also want to retrive the data from database as object of B or Object of C.
here is code of Class A:
package com.example.webproject;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection="Employee")
public class A {
#Id
private String id;
private String passwd;
private String username;
public String getId() {
return id;
}
public void setIp(String string) {
this.ip = string;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
class B:
package com.example.webproject;
public class B extends A {
private String address;
private String phoneNumber;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber= phoneNumber;
}
}
Class C :
package com.example.webproject;
public class C extends A {
private String fatherName;
private String motherName;
public String getFatherName() {
return fatherName;
}
public void setFatherName(String fatherName) {
this.fatherName = fatherName;
}
public String getMotherName() {
return motherName;
}
public void setMotherName(String motherName) {
this.motherName = motherName;
}
}
EmployeeRepository.java
package com.example.webproject;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface EmployeeRepository extends MongoRepository<A,String> {}
EmployeeController.java
#RestController
public class EmployeeController {
#Autowired
private EmployeeRepository repo;
#PostMapping("/addByB")
public String addDataByB(#RequestBody B res) {
repo.save(res);
return "added";
}
#PostMapping("/addByC")
public String addDataByC(#RequestBody C res) {
repo.save(res);
return "added";
}
#GetMapping("/getByB")
public List<B> getDataByB(){
List<B> b= repo.findAll(); #Here it throws error because repo.findAll return object of A.
return b;
}
When i try to add data as B object or C object using swagger , the data is getting stored in database. Now i want to retrieve the data as B object or C object, how to achieve this?

Because you just create Repository of class A and call it, you nedd to creat two another repo of class B and C then call them like you call " EmployeeRepository " so you can use them and get the data.

Related

Why does MongoRepository save return an empty json and save empty value when a variable is not empty?

I have a simple document:
#Document
#NoArgsConstructor
#AllArgsConstructor
#Builder
#ToString
public class ProductUnit {
#Id
String id;
private String name;
private Integer price;
private LocalDateTime localDateTime;
}
Simple MongoRepository :
public interface productRepo extends MongoRepository<ProductUnit,String> {
ProductUnit deleteByName(String name);
List<ProductUnit> findByPrice(Integer price);
}
and Service :
#Service
public class productServiseImpl implements productServise {
#Autowired
productRepo repository;
#Override
public ProductUnit saveOrUpdate(ProductUnit productUnit) {
System.out.println("inside save or update");
return repository.save(productUnit);
}
#Override
public List<ProductUnit> findAll() {
return repository.findAll();
}
#Override
public ProductUnit deleteUnitByPrice(String name) {
return repository.deleteByName(name);
}
#Override
public List<ProductUnit> findByPrice(Integer price) {
return repository.findByPrice(price);
}
}
Now , inside RestController , I pass id through a post request and use a random class to generate a random value of the price and name .At this stage everything is fine, i.e. all values were initialized correctly, but when it comes to service.saveOrUpdate(forSave) It stores the value incorrectly, i.e. the request returns an empty json and the findAll method returns a list of empty json.Can you tell me what the error is? thanks
#RestController
public class productUnitRestController {
#Autowired
productServise service;
#Autowired
Supplier<MetaInfGenerator> generatorSupplier;
#GetMapping(path = "/all")
public List<ProductUnit> getAllProoduct(){
return service.findAll();
}
#PostMapping(path = "/products")
public ProductUnit createProoduct(#RequestParam("id") Optional<String> newId){
System.out.println("***** iside PostMapping ******");
MetaInfGenerator generator = generatorSupplier.get();
System.out.println("***** supplier PostMapping ******");
ProductUnit forSave = ProductUnit.builder()
.id(newId.get())
.name(generator.getRandomString())
.price(generator.getRandomInteger())
.localDateTime(LocalDateTime.now()).build();
System.out.println(forSave);
return service.saveOrUpdate(forSave);
}
}

Can I return DTO and domain entities from services?

I have a spring-boot application and I use DTO like that:
Service
#Service
public class UnitOfMeasureServiceImpl implements IUnitOfMeasureService {
private final IUnitsOfMeasureRepository unitOfMeasureRepository;
#Autowired
public UnitOfMeasureServiceImpl(IUnitsOfMeasureRepository unitOfMeasureRepository) {
this.unitOfMeasureRepository = unitOfMeasureRepository;
}
#Override
public UnitOfMeasureDTO getUnitOfMeasureById(UUID id) {
Optional<UnitOfMeasure> optionalUnitOfMeasure = unitOfMeasureRepository.findById(id);
if (!optionalUnitOfMeasure.isPresent()){
// throw new ComponentNotFoundException(id);
return null;
}
return UnitOfMeasureDTO.factory(optionalUnitOfMeasure.get());
}
dto:
#Data
#JsonInclude(JsonInclude.Include.NON_NULL)
public class UnitOfMeasureDTO {
private String id;
private String name;
private String description;
private String sourceInfoCompanyName;
private String originalId;
public static UnitOfMeasureDTO factory(UnitOfMeasure unitOfMeasure) {
UnitOfMeasureDTO dto = new UnitOfMeasureDTO();
dto.id = unitOfMeasure.getId().toString();
dto.name = unitOfMeasure.getName();
dto.description = unitOfMeasure.getDescription();
dto.sourceInfoCompanyName = unitOfMeasure.getSourceInfo().getSourceCompany().getName();
dto.originalId = unitOfMeasure.getOriginalId();
return dto;
}
}
controller:
#RestController
#RequestMapping(UnitOfMeasureController.BASE_URL)
public class UnitOfMeasureController {
public static final String BASE_URL = "/api/sust/v1/unitOfMeasures";
private final IUnitOfMeasureService unitOfMeasureService;
public UnitOfMeasureController(IUnitOfMeasureService unitOfMeasureService) {
this.unitOfMeasureService = unitOfMeasureService;
}
#GetMapping(path = "/{id}")
#ResponseStatus(HttpStatus.OK)
public UnitOfMeasureDTO getUnitOfMeasureDTO(#PathVariable("id") UUID id) {
UnitOfMeasureDTO unitOfMeasureDTO = unitOfMeasureService.getUnitOfMeasureById(id);
return unitOfMeasureDTO;
}
So in my service I have getUnitOfMeasureById(UUID id) that return a UnitOfMeasureDTO.
Now I need to call, from another service, getUnitOfMeasureById(UUID id) that return the domain entity UnitOfMeasure. I think it's correct to call a service method from another service (not a controller method!) and the separation between business logic is at the service layer. So is it correct to have 2 methods: getUnitOfMeasureDTOById and getUnitOfMeasureById in the service? (getUnitOfMeasureDTOById call getUnitOfMeasureById to avoid code duplication)

java.lang.ClassCastException: Entity A incompatible with Entity B

I'm trying to get proficient in generics in Java. I have some 100 entities that use the same findBy method in JPA interface. Almost all of them require a call to AwrSnapDetails so instead of adding
#ManyToOne private AwrSnapDetails awrSnapDetails; to each Entity, I've created a HelperEntity class and using #Embedded annotation. Now I have gotten to the point in coding where I can't figure out what I am doing wrong and how to go about resolving this error.
Entity
#Entity
public class AwrMemStats {
String description;
double begin_;
double end_;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
Long id;
#Embedded
private HelperEntity helperEntity;
public AwrMemStats() {
}
public AwrMemStats(String description, double begin_, double end_, AwrSnapDetails awrSnapDetails) {
this.description = description;
this.begin_ = begin_;
this.end_ = end_;
HelperEntity h = new HelperEntity(awrSnapDetails);
}
// getters/setters removed for clarity
}
Embedded Entity
#Embeddable
public class HelperEntity implements Serializable{
private static final long serialVersionUID = 1L;
#ManyToOne
AwrSnapDetails awrSnapDetails;
public HelperEntity() {
}
public HelperEntity(AwrSnapDetails awrSnapDetails) {
super();
this.awrSnapDetails = awrSnapDetails;
}
public AwrSnapDetails getAwrSnapDetails() {
return awrSnapDetails;
}
public AwrSnapDetails setAwrSnapDetails(AwrSnapDetails awrSnapDetails) {
return this.awrSnapDetails = awrSnapDetails;
}
}
Service Class
#Service
public class HelperService<T> {
#Autowired
private HelperRepository<T> repository;
public void add(T entity) {
repository.save(entity);
}
public void add(List<T> entities) {
repository.saveAll(entities);
}
public T get(T entity) {
T t = repository.findByHelperEntityAwrSnapDetailsStartSnapIdAndHelperEntityAwrSnapDetailsInstanceDetailDbNameAndHelperEntityAwrSnapDetailsInstanceDetailDbId(
((HelperEntity) entity).getAwrSnapDetails().getStartSnapId(),
((HelperEntity) entity).getAwrSnapDetails().getInstanceDetail().getDbName(),
((HelperEntity) entity).getAwrSnapDetails().getInstanceDetail().getDbId());
//((AwrMemStats) entity).getHelperEntity().getAwrSnapDetails().getStartSnapId(),
//((AwrMemStats) entity).getHelperEntity().getAwrSnapDetails().getInstanceDetail().getDbName(),
//((AwrMemStats) entity).getHelperEntity().getAwrSnapDetails().getInstanceDetail().getDbId());
if (t!= null) {
return t;
}
return null;
}
}
Controller
#RestController
public class HelperController<T> {
#Autowired
private HelperService<T> service;
public void add(T entity) {
service.add(entity);
}
public void add(List<T> entities) {
service.add(entities);
}
public T get(T entity) {
return service.get(entity);
}
}
Execution
getAwrSnapDetails() initilized in HelperLoader
#Component
public class LoadAwrMemStats extends HelperLoader{
#Autowired
private HelperController<AwrMemStats> controller;
public void doThis() {
AwrMemStats profile = new AwrMemStats("a",1.0,1.0,getAwrSnapDetails());
AwrMemStats s = controller.get(profile);
ANd finally the ERROR message
Exception in thread "restartedMain" java.lang.reflect.InvocationTargetException
...
...
Caused by: java.lang.ClassCastException: net.mharoon.perfmon.awr.entities.AwrMemStats incompatible with net.mharoon.perfmon.awr.entities.HelperEntity
at net.mharoon.perfmon.awr.service.HelperService.get(HelperService.java:27)
at net.mharoon.perfmon.awr.controller.HelperController.get(HelperController.java:24)
...
...
Update this code works but only for given class AwrMemStats.
public List<T> get(T entity) {
List<T> ts = repository.findByHelperEntityAwrSnapDetailsStartSnapIdAndHelperEntityAwrSnapDetailsInstanceDetailDbIdAndHelperEntityAwrSnapDetailsInstanceDetailDbName(
//((HelperEntity) entity).getAwrSnapDetails().getStartSnapId(),
//((HelperEntity) entity).getAwrSnapDetails().getInstanceDetail().getDbName(),
//((HelperEntity) entity).getAwrSnapDetails().getInstanceDetail().getDbId());
((AwrMemStats) entity).getHelperEntity().getAwrSnapDetails().getStartSnapId(),
((AwrMemStats) entity).getHelperEntity().getAwrSnapDetails().getInstanceDetail().getDbId(),
((AwrMemStats) entity).getHelperEntity().getAwrSnapDetails().getInstanceDetail().getDbName());
if (!ts.isEmpty()) {
return ts;
}
return null;
}
The reason is because you are returning an Object that is not AwrMemStats and assigning it to AwrMemStats.
A simple work around is to replace
public T get(T entity)
with
public <T extends AwrMemStats> T get(T entity)
EDIT : Another solution (which is more generic) is..
replace
public class AwrMemStats
with
public class AwrMemStats extends HelperEntity
then replace
AwrMemStats s = controller.get(profile);
with
AwrMemStats s = (AwrMemStats) controller.get(profile);

MapStruct does not detect setters in builder

I am building a simple REST service using spring. I separated my entities from DTOs and I made the DTOs immutable using Immutables. I needed mapping between DTOs and DAOs, so I chose MapStruct. The Mapper is not able to detect the setters I have defined in my DAOs.
The problem is exactly similar to this question. This question does not have an accepted answer and I have tried all of the suggestions in that question and they don't work. I don't want to try this answer because I feel it defeats the purpose for which I am using Immutables. #marc-von-renteln summarizes this reason nicely in the comment here
I tried the answer provided by #tobias-schulte. But that caused a different problem. In the Mapper class in the answer, trying to return Immutable*.Builder from the mapping method throws an error saying the Immutable type cannot be found.
I have exhaustively searched issues logged against MapStruct and Immutables and I haven't been able to find a solution. Unfortunately there are hardly few examples or people using a combination of MapStruct and Immutables. The mapstruct-examples repository also doesn't have an example for working with Immutables.
I even tried defining separate Mapper interfaces for each of the DtTOs (like UserStatusMapper). I was only making it more complicated with more errors.
I have created a sample spring project to demonstrate the problem.
GitHub Repo Link. This demo app is almost same as the REST service I am creating. All database (spring-data-jpa , hibernate) stuff is removed and I am using mock data.
If you checkout the project and run the demo-app you can make two API calls.
GetUser:
Request:
http://localhost:8080/user/api/v1/users/1
Response:
{
"id": 0,
"username": "TestUser",
"email": "TestUser#demo.com",
"userStatus": {
"id": 1,
"status": 1,
"statusName": "Active"
}
Createuser: PROBLEM HERE
http://localhost:8080/user/api/v1/users/create
Sample Input:
{
"username": "TestUser",
"email": "TestUser#demo.com",
"userStatus": {
"id": 1,
"status": 1,
"statusName": "Active"
}
}
Response:
{
"timestamp": "2019-04-28T09:29:24.933+0000",
"status": 500,
"error": "Internal Server Error",
"message": "Type definition error: [simple type, class com.immutablesmapstruct.demo.dto.model.ImmutableUserDto$Builder]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.immutablesmapstruct.demo.dto.model.ImmutableUserDto$Builder`, problem: Cannot build UserDto, some of required attributes are not set [username, email, userStatus]\n at [Source: (PushbackInputStream); line: 9, column: 1]",
"path": "/user/api/v1/users/create"
}
Below are important pieces of code related to problem:
Daos:
1. UserDao
public class User {
// Primary Key. Something that is annotated with #Id
private int id;
private String username;
private String email;
private UserStatus userStatus;
private User(Builder builder) {
id = builder.id;
username = builder.username;
email = builder.email;
userStatus = builder.userStatus;
}
public static Builder builder() {
return new Builder();
}
public int getId() {
return id;
}
public String getUsername() {
return username;
}
public String getEmail() {
return email;
}
public UserStatus getUserStatus() {
return userStatus;
}
public static final class Builder {
private int id;
private String username;
private String email;
private UserStatus userStatus;
private Builder() {
}
public Builder setId(int id) {
this.id = id;
return this;
}
public Builder setUsername(String username) {
this.username = username;
return this;
}
public Builder setEmail(String email) {
this.email = email;
return this;
}
public Builder setUserStatus(UserStatus userStatus) {
this.userStatus = userStatus;
return this;
}
public User build() {
return new User(this);
}
2. UserStatusDao:
package com.immutablesmapstruct.demo.dao.model;
/**
* Status of user.
* Example: Active or Inactive
*/
public class UserStatus {
// Primary Key. Something that is annotated with #Id
private int id;
// A value of 1 or 0
private int status;
// Active , InActive
private String statusName;
private UserStatus(Builder builder) {
id = builder.id;
status = builder.status;
statusName = builder.statusName;
}
public static Builder builder() {
return new Builder();
}
public int getId() {
return id;
}
public int getStatus() {
return status;
}
public String getStatusName() {
return statusName;
}
public static final class Builder {
private int id;
private int status;
private String statusName;
private Builder() {
}
public Builder setId(int id) {
this.id = id;
return this;
}
public Builder setStatus(int status) {
this.status = status;
return this;
}
public Builder setStatusName(String statusName) {
this.statusName = statusName;
return this;
}
public UserStatus build() {
return new UserStatus(this);
}
}
}
DTOs
1. UserDto:
package com.immutablesmapstruct.demo.dto.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.immutables.value.Value;
#Value.Immutable
#Value.Style(defaults = #Value.Immutable(copy = false), init = "set*")
#JsonSerialize(as = ImmutableUserDto.class)
#JsonDeserialize(builder = ImmutableUserDto.Builder.class)
public abstract class UserDto {
#Value.Default
#JsonProperty
public int id() {
return 0;
}
#JsonProperty
public abstract String username();
#JsonProperty
public abstract String email();
#JsonProperty
public abstract UserStatusDto userStatus();
2. UserStatusDto:
package com.immutablesmapstruct.demo.dto.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.immutables.value.Value;
#Value.Immutable
#Value.Style(defaults = #Value.Immutable(copy = false), init = "set*")
#JsonSerialize(as = ImmutableUserStatusDto.class)
#JsonDeserialize(builder = ImmutableUserStatusDto.Builder.class)
public abstract class UserStatusDto {
#JsonProperty
public abstract int id();
#JsonProperty
public abstract int status();
#JsonProperty
public abstract String statusName();
}
MapStruct UserMapper:
package com.immutablesmapstruct.demo.dto.mapper;
import com.immutablesmapstruct.demo.dao.model.User;
import com.immutablesmapstruct.demo.dao.model.UserStatus;
import com.immutablesmapstruct.demo.dto.model.UserDto;
import com.immutablesmapstruct.demo.dto.model.UserStatusDto;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
#Mapper(componentModel = "spring")
public interface UserMapper {
UserMapper USER_MAPPER_INSTANCE = Mappers.getMapper(UserMapper.class);
UserDto userDaoToDto(User user);
//Problem here.
User userDtoToDao(UserDto userDto);
UserStatusDto userStatusDaoToDto(UserStatus userStatusDao);
UserStatus userStatusDtoToDao(UserStatusDto userStatusDto);
}
If I look at the concrete method generated by MapStruct for userDtoToDao I can clearly see that the setters are not being recognized.
package com.immutablesmapstruct.demo.dto.mapper;
#Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2019-04-28T02:29:03-0700",
comments = "version: 1.3.0.Final, compiler: javac, environment: Java 1.8.0_191 (Oracle Corporation)"
)
#Component
public class UserMapperImpl implements UserMapper {
...
...
#Override
public User userDtoToDao(UserDto userDto) {
if ( userDto == null ) {
return null;
}
com.immutablesmapstruct.demo.dao.model.User.Builder user = User.builder();
return user.build();
}
....
....
}
Mapstruct doesn't recognize your getters in UserDto and UserStatusDto.
When you change the existing methods (like public abstract String username()) in these abstract classes to classic getters like
#JsonProperty("username")
public abstract String getUsername();
the MapperImpl will contain the required calls. Note, that the #JsonProperty needs to have the attributes name itself afterwards (because of the changed method name).
Here are the complete classes UserDto and UserStatusDto with said changes:
package com.immutablesmapstruct.demo.dto.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.immutables.value.Value;
#Value.Immutable
#Value.Style(defaults = #Value.Immutable(copy = false), init = "set*")
#JsonSerialize(as = ImmutableUserDto.class)
#JsonDeserialize(builder = ImmutableUserDto.Builder.class)
public abstract class UserDto {
#Value.Default
#JsonProperty("id")
public int getId() {
return 0;
}
#JsonProperty("username")
public abstract String getUsername();
#JsonProperty("email")
public abstract String getEmail();
#JsonProperty("userStatus")
public abstract UserStatusDto getUserStatus();
}
package com.immutablesmapstruct.demo.dto.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.immutables.value.Value;
#Value.Immutable
#Value.Style(defaults = #Value.Immutable(copy = false), init = "set*")
#JsonSerialize(as = ImmutableUserStatusDto.class)
#JsonDeserialize(builder = ImmutableUserStatusDto.Builder.class)
public abstract class UserStatusDto {
#JsonProperty("id")
public abstract int getId();
#JsonProperty("status")
public abstract int getStatus();
#JsonProperty("statusName")
public abstract String getStatusName();
}

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.

Resources