identifier of an instance of ...was altered from - spring-boot

i found many response about this title "identifier of an instance of ...was altered from ..." but none of this give me a solution.
i am using PostgreSQL
with just 2 column id_type and libelle.
here is my Model level :
package com.stev.pillecons.pilleCons.models;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
#Entity(name = "type_pille")
#JsonIgnoreProperties({"hibernateLazyInitializer","handler"})
public class LePille {
#Id
#GeneratedValue (strategy = GenerationType.IDENTITY)
private int id_type;
private String libelle;
public LePille(){}
public String getLibelle() {
return libelle;
}
public void setLibelle(String libelle) {
this.libelle = libelle;
}
public int getId_type() {
return id_type;
}
public void setId_type(int id_type) {
this.id_type = id_type;
}
}
My Service level :
#Override
public LePille updatePille(Integer id, LePille Sourcepille) {
Optional<LePille> existingSession = pilleRepo.findById(id);
if (existingSession.isPresent())
{
LePille Targetpile = existingSession.get();
BeanUtils.copyProperties(Sourcepille, Targetpile);
return pilleRepo.saveAndFlush(Targetpile);
}
else
{
throw new PilleException("pille not found");
}
}
when i debug it, with the data
{"id_type":10,"libelle":"dsf"}
with postman
the value of TargetPille is : {"id_type":10,"libelle":"dsf"}
and the value of SourcePille : {"id_type":0,"libelle":"popo"}
last but not least is Controller level:
#RequestMapping(value = "{id}", method = RequestMethod.PUT)
public ResponseEntity update(#PathVariable Integer id, #RequestBody LePille session) {
LePille updPille = pilleService.updatePille(id, session);
return new ResponseEntity<LePille>(updPille, HttpStatus.OK);
}
it is strange because juste update that not working, Create, Read and Delete works fine.
thanks in advance

i just change the code like this:
BeanUtils.copyProperties(Sourcepille, Targetpile, "id_type");
just add the id_type to ignore variable

Related

#OneToOne(cascade = {CascadeType.ALL}) problem

I have a problem with my code. I do a little CarRent webservice and when i try to assign Errand to the car, errand which i want to assign is add to list of errands...
this is controller of errand
package com.RentCar.Rent_A_car.domain.Controllers;
import com.RentCar.Rent_A_car.domain.Car;
import com.RentCar.Rent_A_car.domain.Errand;
import com.RentCar.Rent_A_car.domain.Services.CarService;
import com.RentCar.Rent_A_car.domain.Services.ErrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
#Controller
public class ErrandController {
#Autowired
CarService carService;
#Autowired
ErrandService errandService;
#RequestMapping("/assignErrand")
public String assignQuest(#RequestParam("plate") String plate, Model model){
Car car = carService.getCar(plate);
List<Errand> errandList = errandService.getAllCurrentErrands();
model.addAttribute("car",car);
model.addAttribute("errands",errandList);;
return "assignErrand";
}
#RequestMapping(value = "/assignErrand", method = RequestMethod.POST)
public String assignQuest(Car car){
carService.updateCar(car);
System.out.println("assignquest");
return "redirect:/cars";
}
These are my repositories
#Repository
public class CarsRepository {
// class to do CRUD operation on cars and errands
Map<String, Car> CarList = new HashMap<>();
#PersistenceContext
private EntityManager em;
#Transactional
public void AddCar (String mark, String plate, int mileage){
Car newCar = new Car(mark, plate, mileage);
em.persist(newCar);
}
//pobiera aktualne id i dodaje do mapy
#Transactional
public void AddCar(Car car) {
em.persist(car);
}
// dla każdego "powyzej" usuniętego trzeba zmniejszyć id o 1 ; pętla o dlugosci pozostałych aut id--; KONIECZNE FINALNIE, do budowy nie
#Transactional
public void DellateCar(String plate){
Car c = em.find(Car.class, plate);
em.remove(c);
}
public Car getCar(String plate){
Car car = em.createQuery("from Car c where c.plate=:plate", Car.class)
.setParameter("plate", plate).getSingleResult();
return car;
}
public Collection<Car> getAllCars() {
return em.createQuery("from Car",Car.class).getResultList();
}
#Transactional
public void updateCar(Car car) {
em.merge(car);
}
// public String getPlate() {
// if (CarList.isEmpty()) {
// return "Car list is empty";
// } else {
// return (String)CarList.keySet();
// }
// }
// #PostConstruct
// public void build() {
// AddCar("BMW","DW",100000);
// AddCar("Opel","DTR",100043);
// AddCar("Toyota","WB",1012300);
// AddCar("Audi","DST",102340);
//
// }
#Override
public String toString() {
return "CarsRepository{" +
"CarList=" +
'}' + "\n";
}
}
Nr
#Repository
public class ErrandRepository {
#PersistenceContext
private EntityManager ee;
List<Errand> ErrandList = new ArrayList<>();
#Transactional
public void createErrand(String description) {
Errand newErrand = new Errand(description);
ee.persist(newErrand);
System.out.println(newErrand);
}
public void createErrand(Errand errand){ErrandList.add(errand);}
public List<Errand> getAll () {
return ee.createQuery("from Errand", Errand.class).getResultList();
}
public void delateErrand(Errand errand) {
ee.remove(errand);
}
#Transactional
public void delateErrand(int x) {
ErrandList.remove(x);
}
public Errand getErrandId(Integer x){
return ee.find(Errand.class, x );
}
#PostConstruct
#Transactional
public void init(){
Errand e1 = new Errand("zlecenie na wrocław");
Errand e2 = new Errand("zlecenie na wasdw");
Errand e3 = new Errand("zlecenie na wfgasfdław");
}
#Override
public String toString() {
return "ErrandRepository{" +
"ErrandList=" + ErrandList +
'}';
}
}
this is a part of CarService
public void updateCar(Car car) {
carsRepository.updateCar(car);
System.out.println("tu sie wywołuje updatecar");
}
i don't know what is a problem... can you help me ?
edit, i add car and errand class
package com.RentCar.Rent_A_car.domain;
import javax.persistence.*;
import javax.persistence.Entity;
#Entity
public class Car {
// #Id
// #GeneratedValue(strategy = GenerationType.AUTO)
// public int id;
String mark;
#Id
String plate;
int mileage;
#OneToOne(cascade = CascadeType.ALL)
public Errand errand;
public Car() { }
public Car(String mark, String plate, int mileage) {
this.mark = mark;
this.plate = plate;
this.mileage = mileage;
}
public void setErrand(Errand errand) {
this.errand = errand;
}
public String getMark() {
return mark;
}
public void setMark(String mark) {
this.mark = mark;
}
public String getPlate() {
return plate;
}
public void setPlate(String plate) {
this.plate = plate;
}
public int getMileage() {
return mileage;
}
public void setMileage(int mileage) {
this.mileage = mileage;
}
public Errand getErrand() {
return errand;
}enter code here
And errand class
package com.RentCar.Rent_A_car.domain;
import net.bytebuddy.dynamic.loading.InjectionClassLoader;
import javax.persistence.*;
import javax.persistence.Entity;
#Entity
public class Errand {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public int Id;
public String description;
public Errand() {
}
public Errand(String description) {
this.description = description;
}
#Override
public String toString() {
return description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
I'm not quite sure about what is the actual problem. But anyway, I can make you some recommendations:
use plural nouns for REST uris, like:
#GetMapping("cars")
#GetMapping("errands")
and so on. Not verbs, like: assignErrand
If you split Repositories and Services, do not put login in repos, like
#Transactional
public void createErrand(String description) {
Errand newErrand = new Errand(description);
ee.persist(newErrand);
System.out.println(newErrand);
}
In the repos you should do just the persistence job. Leave the logic to the service
To add errands, I would go with something like this:
#PostMapping("/cars/{carId}/errands")
public Car addErranr(#PathVariable int carId, #RequestBody Errand errand){
Car car = this.carService.findById(carId);
car.getErrands().add(errand);
return this.carService.save(car);
}

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

How to retrieve data from DB and print in jsp using spring and hibernate?

I have already written the code for inserting my data into my DB but I'm a bit confused on how to retrieve that data in json format and print in my jsp view using a jQuery data table. I have written some code on retrieving but I'm still stuck. Please help.
Here are my code snippets:
entity class:
package model.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Size;
#Entity
public class Products {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int productId;
#Size(min=1)
private String productName;
#Min(value=1, message = "Value cannot be zero or negative")
private double unitPrice;
#Size(min=1)
private String productDescription;
#Size(min=1)
private String category;
#Min(value = 1, message = " Quantity should be greater than zero and positive")
#Max(value= 99, message = " Quantity limit exceeded, value should be less than 100")
private int productQty;
public Products() {}
public Products(int productId, String productName, double unitPrice, String productDescription, String category, int productQty) {
super();
this.productQty = productQty;
this.productId = productId;
this.productName = productName;
this.unitPrice = unitPrice;
this.productDescription = productDescription;
this.category = category;
}
public int getProductQty() {
return productQty;
}
public void setProductQty(int productQty) {
this.productQty = productQty;
}
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public double getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
DAOImplementation class:
package model.daoimpl;
import java.util.List;
import org.hibernate.Session;
import model.config.HibernateUtil;
import model.dao.IProductsDAO;
import model.entity.Products;
public class ProductsDAOImpl implements IProductsDAO {
private Session sess;
public ProductsDAOImpl() {
sess = HibernateUtil.getSessionFactory().openSession();
}
public boolean insertProduct(Products p) {
boolean b = true;
try
{
sess.beginTransaction();
sess.save(p);
sess.getTransaction().commit();
}catch(Exception ex)
{
b = false;
sess.getTransaction().rollback();
ex.printStackTrace();
}
return b;
}
public List<Products> getProducts()
{
List<Products> lp = null;
try
{
sess.beginTransaction();
lp = sess.createQuery("from Product",Products.class).getResultList();
}catch(Exception ex)
{
ex.printStackTrace();
}
return lp;
}
}
controller class:
#Controller
public class ProductController {
#RequestMapping(value="/manageproducts", method= RequestMethod.GET)
public String manageProductPage() {
return "manageproducts";
}
#RequestMapping(value="/insertproducts",method = RequestMethod.POST)
public String addInserProductsPage(#ModelAttribute("Products")Products p) {
IProductsDAO ip = new ProductsDAOImpl();
boolean b = ip.insertProduct(p);
if(b)
return "success";
else
return "manageproducts";
}
#RequestMapping(value="/listproducts", method = RequestMethod.GET)
public List<Products> listAllProducts(){
IProductsDAO ip = new ProductsDAOImpl();
return ip.getProducts();
}
}
So as you can see I have created the getproducts function but I haven't created the view for displaying products for which I want to use the jQuery datatable, Also I'm a bit confused on how to map the view with my controller. So please help.
You can use Model to send your list to the view page
#RequestMapping(value="/listproducts", method = RequestMethod.GET)
public String listAllProducts(Model model){
IProductsDAO ip = new ProductsDAOImpl();
List<Products> products = ip.getProducts();
model.addAttribute ("products",products);
Return "your view name without .jsp";
}

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.

Spring JPA annotation based web app

I am have JSON message as request object coming into Controller.
I am trying to map the object to model class in the Controller class but unable to do so.
Can anyone help me with the procedure.
package com.firm.trayportal.contoller;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.firm.trayportal.jparepository.trayMoveRepository;
import com.firm.trayportal.jparepository.LocationRepository;
import com.firm.trayportal.jparepository.StopoffRepository;
import com.firm.trayportal.model.trayMove;
import com.firm.trayportal.model.Location;
import com.firm.trayportal.model.Stopoff;
import com.firm.trayportal.service.trayMoveService;
#RestController
public class trayPortalquoteController {
/* #Autowired
JdbcTemplate template;*/
private trayMove trayMove;
private Location location;
private Stopoff stopoff;
// Service Layer
private trayMoveService trayMoveService;
private static final Logger logger = Logger
.getLogger(trayPortalquoteController.class);
#RequestMapping(value = "/quote", method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_JSON_VALUE} )
public ThumbsUp getActivetrayOrder(HttpServletRequest request, #RequestBody trayquoteRto rto) {
logger.debug("Start processing");
if (rto != null) {
logger.debug(String.format("Driver: %s/Load Number: %s/Stop %s",
rto.getDriver(), rto.getLn(), rto.getStops() != null
&& rto.getStops().get(0) != null ? rto.getStops()
.get(0).getStop() : "?"));
/*
* Querying String insertSql =
* "insert into tray_move (move_type, carrier_id, ln) values(?,?,?)"
* ;
*
* Object[] params = new Object[] {rto.getType(), rto.getDriver(),
* rto.getLn()}; // define SQL types of the arguments int[] types =
* new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR};
*/
// execute insert query to insert the data
// return number of row / rows processed by the executed query
try {
// int row = template.update(insertSql, params, types);
trayMove trayMove = new trayMove();
trayMove = savetrayInfo(rto);
// trayMoveService.populate(trayMove); // return type ?
// trayMove row = trayMoveRepo.saveAndFlush(trayMove);
// logger.debug(row + " row inserted.");
} catch (Exception _ex) {
logger.debug("Exception executing sql query:( Message: "
+ _ex.getMessage());
logger.debug("Exception executing sql query:( Message: "
+ _ex.getStackTrace());
}
} else {
logger.debug("quote RTO is NULL");
}
return new ThumbsUp();
}
private Stopoff saveStopOff(trayquoteRto rto) {
// TODO Auto-generated method stub
return null;
}
private Location saveLocationInfo(trayquoteRto rto) {
// TODO Auto-generated method stub
return null;
}
public trayMove savetrayInfo(trayquoteRto rto) {
System.out.println("In savetrayInfo method");
//trayMove.setMoveId(100005);
trayMove.setMoveType("IPU");
System.out.println("In savetrayInfo MoveType");
System.out.println("setMoveType");
trayMove.setCarrierId(rto.getDriver());
trayMove.setLn(rto.getLn());
// TODO:rto.getName(); ??
trayMove.setShippersno(rto.getShippersno());
return trayMove;
}
public Location saveLocInfo(trayquoteRto rto) {
// location.set
// location.setAddress1(address1);
return location;
}
}
/*
* create table tray_move ( move_type varchar(16), carrier_id varchar(32), ln
* varchar(32) );
*/
class trayquoteRto {
private String type;
private String driver;
private String ln;
private String shippersno;
private String oramplocation;
private String orampadd1;
private String orampadd2;
private String orampphone;
private String orampstate;
private String orampzip;
private String dramplocation;
private String drampadd1;
private String drampadd2;
private String drampphone;
private String drampstate;
private String drampzip;
private List<Stops> stops = new ArrayList<Stops>();
public String getType() {
return type;
}
public String getDriver() {
return driver;
}
public String getLn() {
return ln;
}
public String getShippersno() {
return shippersno;
}
public String getOramplocation() {
return oramplocation;
}
public String getOrampadd1() {
return orampadd1;
}
public String getOrampadd2() {
return orampadd2;
}
public String getOrampphone() {
return orampphone;
}
public String getOrampstate() {
return orampstate;
}
public String getOrampzip() {
return orampzip;
}
public String getDramplocation() {
return dramplocation;
}
public String getDrampadd1() {
return drampadd1;
}
public String getDrampadd2() {
return drampadd2;
}
public String getDrampphone() {
return drampphone;
}
public String getDrampstate() {
return drampstate;
}
public String getDrampzip() {
return drampzip;
}
public List<Stops> getStops() {
return stops;
}
}
class Stops {
String name;
String add1;
String add2;
String city;
String ext;
String phone;
String st;
String zip;
Integer stop;
Date apptment1;
Date apptment2;
public String getName() {
return name;
}
public String getAdd1() {
return add1;
}
public String getAdd2() {
return add2;
}
public String getCity() {
return city;
}
public String getExt() {
return ext;
}
public String getPhone() {
return phone;
}
public String getSt() {
return st;
}
public String getZip() {
return zip;
}
public Date getApptment1() {
return apptment1;
}
public Date getApptment2() {
return apptment2;
}
public Integer getStop() {
return stop;
}
}
class ThumbsUp {
private String message = "success";
public String getMessage() {
return message;
}
}
#Service
#Repository
public class trayMoveService {
#Autowired
private trayMoveRepository trayMoveRepo;
#Qualifier("trayMove")
public void populate(trayMove dm) {
trayMoveRepo.saveAndFlush(dm);
}
}
#Transactional
public interface trayMoveRepository extends JpaRepository<trayMove, Integer>{
}
The setter method doesnt work. I think m missing some annotations. Can someone direct me to the tutorial please ?
The application is Spring JPA(EclipseLink) annotation based.

Resources