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

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";
}

Related

identifier of an instance of ...was altered from

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

cant send a postman data with ManyToOne

hi i'm working with spring boot and rest in my project and i estableshed a relation ManyToOne between two enteties but i'm unable to send the postman request to add a mission along with its category i'm not even sure that the two enteties are correctly related
he are the two entities and the contoller
the mission etity
#Entity
#Table(name="missions")
public class Mission {
public Mission() {
}
public Mission(int id, String state, String adresse, int etatMission, String image, List<Categorie> categories,
String ville, int duree, String description, String domaine) {
this.id = id;
this.state = state;
this.adresse = adresse;
this.etatMission = etatMission;
this.image = image;
this.categories = categories;
this.ville = ville;
this.duree = duree;
this.description = description;
this.domaine = domaine;
}
public List<Categorie> getCategories() {
return categories;
}
public void setCategories(List<Categorie> categories) {
this.categories = categories;
}
public String getVille() {
return ville;
}
public void setVille(String ville) {
this.ville = ville;
}
public Mission(Map<String,Object> userMap) {
if (userMap.get("id") != null)
this.id = (int )userMap.get("id");
this.state = (String) userMap.get("state");
this.duree = (int) userMap.get("duree");
this.domaine = (String) userMap.get("domaine");
this.description = (String) userMap.get("description");
this.ville=(String) userMap.get("ville");
this.adresse=(String) userMap.get("adresse");
this.etatMission=(int) userMap.get("etatMission");
this.image=(String) userMap.get("image");
this.categories=(List<Categorie>) userMap.get("categories");
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String state;
private String adresse;
private int etatMission;
private String image;
#OneToMany(mappedBy="mission",cascade=CascadeType.ALL)
private List<Categorie> categories;
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
private String ville;
public int getEtatMission() {
return etatMission;
}
public void setEtatMission(int etatMission) {
this.etatMission = etatMission;
}
private int duree;
private String description;
private String domaine;
public String getDomaine() {
return domaine;
}
public void setDomaine(String domaine) {
this.domaine = domaine;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
#Override
public String toString() {
return "Mission [id=" + id + ", state=" + state + ", duree=" + duree + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getDuree() {
return duree;
}
public void setDuree(int duree) {
this.duree = duree;
}
public void add(Categorie cat) {
if (categories == null) {
categories = new ArrayList<>();
}
categories.add(cat);
cat.setMission(this);
}
}
the category entety
#Entity
#Table(name="categorie")
public class Categorie {
public Categorie() {
}
public Categorie(Map<String, Object> catMap) {
this.id=(int) catMap.get("id");
this.nom = (String) catMap.get("nom");
this.mission =(Mission) catMap.get("mission_id") ;
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id ;
private String nom;
#ManyToOne
#JoinColumn(name="mission_id",referencedColumnName="id")
private Mission mission;
public Categorie(int id, String nom, Mission mission) {
this.id = id;
this.nom = nom;
this.mission = mission;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
#Override
public String toString() {
return "Categorie [nom=" + nom + "]";
}
public Mission getMission() {
return mission;
}
public void setMission(Mission mission) {
this.mission = mission;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
here's the controller for mission
package ma.ac.emi.MinuteBrico.Controllers;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import ma.ac.emi.MinuteBrico.Services.MissionServices;
import ma.ac.emi.MinuteBrico.Models.Mission;
#RestController
public class MissionController {
#Autowired
private MissionServices missionService;
#CrossOrigin
#GetMapping("/missions")
public List<Mission> index(){
return missionService.findAll();
}
#CrossOrigin
#GetMapping("/missions/{id}")
public Optional<Mission> indexById(#PathVariable String id){
int missionId = Integer.parseInt(id);
return missionService.findById(missionId);
}
#CrossOrigin()
#PostMapping("/missions")
public String create(#RequestBody Map<String, Object> missionMap) {
System.out.println(missionMap);
Mission mission = new Mission(missionMap);
missionService.savemission(mission);
return "Mission ajouté";
}
}
package ma.ac.emi.MinuteBrico.Repositories;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import ma.ac.emi.MinuteBrico.Models.Mission;
public interface MissionRepository extends JpaRepository<Mission,Integer> {
}
the postman request
{
"state": "Urgent",
"adresse": "Av ben drisse",
"etatMission": 0,
"image": "assets/Brand.jpeg",
"ville": "Chefchaouen",
"duree": 480000,
"description": "je veux quelqu\\'un pour me faire une cuisne",
"domaine": "Plomberie",
"categories":[
{
"id":15,
"nom":"Menuiserie",
"mission":{
"field":"value"
}
}
]
}
try to add #ManyToOne(cascade = CascadeType.ALL)

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

ManyToMany select query is correct and the query is viewed in console. But I cant put values into jsp

I added many to many relationship to importers and agents table..data save successfully and middle table created...but i cannot retrieve data to my jsp ...How can i retrieve agents table data to my jsp.
My model is
package lk.slsi.domain;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name = "importers")
public class Importer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "importer_id")
private long importerId;
#NotEmpty
#Column(unique = true, nullable = false)
private String importerBrc;
private String importerVatNumber;
private String importerName;
private String importerAddress1;
private String importerAddress2;
private String importerAddress3;
private String importerCityName;
private String officePhoneNumber;
private String mobilePhoneNumber;
#Email
private String email;
#Email
private String optemail1;
#Email
private String optemail2;
public String getOptemail1() {
return optemail1;
}
public void setOptemail1(String optemail1) {
this.optemail1 = optemail1;
}
public String getOptemail2() {
return optemail2;
}
public void setOptemail2(String optemail2) {
this.optemail2 = optemail2;
}
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinTable(name = "importer_agents",
joinColumns = {#JoinColumn(name = "importerId")},
inverseJoinColumns = {#JoinColumn(name = "agentId")})
private List<Agent> agentList;
public String getImporterBrc() {
return importerBrc;
}
public void setImporterBrc(String importerBrc) {
this.importerBrc = importerBrc;
}
public String getImporterVatNumber() {
return importerVatNumber;
}
public void setImporterVatNumber(String importerVatNumber) {
this.importerVatNumber = importerVatNumber;
}
public String getImporterName() {
return importerName;
}
public void setImporterName(String importerName) {
this.importerName = importerName;
}
public String getImporterAddress1() {
return importerAddress1;
}
public void setImporterAddress1(String importerAddress1) {
this.importerAddress1 = importerAddress1;
}
public String getImporterAddress2() {
return importerAddress2;
}
public void setImporterAddress2(String importerAddress2) {
this.importerAddress2 = importerAddress2;
}
public String getImporterAddress3() {
return importerAddress3;
}
public void setImporterAddress3(String importerAddress3) {
this.importerAddress3 = importerAddress3;
}
public String getImporterCityName() {
return importerCityName;
}
public void setImporterCityName(String importerCityName) {
this.importerCityName = importerCityName;
}
public String getOfficePhoneNumber() {
return officePhoneNumber;
}
public void setOfficePhoneNumber(String officePhoneNumber) {
this.officePhoneNumber = officePhoneNumber;
}
public String getMobilePhoneNumber() {
return mobilePhoneNumber;
}
public void setMobilePhoneNumber(String mobilePhoneNumber) {
this.mobilePhoneNumber = mobilePhoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getImporterId() {
return importerId;
}
public void setImporterId(long importerId) {
this.importerId = importerId;
}
public List<Agent> getAgentList() {
return agentList;
}
public void setAgentList(List<Agent> agentList) {
this.agentList = agentList;
}
}
my agent table model is
package lk.slsi.domain;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.*;
#Entity
#Table(name = "agents")
public class Agent {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "agent_id")
private long agentId;
#NotEmpty
#Column(unique = true, nullable = false)
private String nic;
private String vatNumber;
private String name;
private String agentAddress1;
private String agentAddress2;
private String agentAddress3;
private String agentCityName;
private String officePhoneNumber;
private String mobilePhoneNumber;
#Email
private String email;
public long getAgentId() {
return agentId;
}
public void setAgentId(long agentId) {
this.agentId = agentId;
}
public String getNic() {
return nic;
}
public void setNic(String nic) {
this.nic = nic;
}
public String getVatNumber() {
return vatNumber;
}
public void setVatNumber(String vatNumber) {
this.vatNumber = vatNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAgentAddress1() {
return agentAddress1;
}
public void setAgentAddress1(String agentAddress1) {
this.agentAddress1 = agentAddress1;
}
public String getAgentAddress2() {
return agentAddress2;
}
public void setAgentAddress2(String agentAddress2) {
this.agentAddress2 = agentAddress2;
}
public String getAgentAddress3() {
return agentAddress3;
}
public void setAgentAddress3(String agentAddress3) {
this.agentAddress3 = agentAddress3;
}
public String getAgentCityName() {
return agentCityName;
}
public void setAgentCityName(String agentCityName) {
this.agentCityName = agentCityName;
}
public String getOfficePhoneNumber() {
return officePhoneNumber;
}
public void setOfficePhoneNumber(String officePhoneNumber) {
this.officePhoneNumber = officePhoneNumber;
}
public String getMobilePhoneNumber() {
return mobilePhoneNumber;
}
public void setMobilePhoneNumber(String mobilePhoneNumber) {
this.mobilePhoneNumber = mobilePhoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
my repository is
package lk.slsi.repository;
import java.util.List;
import lk.slsi.domain.Importer;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
/**
* Created by ignotus on 2/8/2017.
*/
public interface ImporterRepository extends CrudRepository<Importer,Long> {
#Override
Importer save(Importer importer);
#Override
Importer findOne(Long importerId);
#Override
List<Importer> findAll();
#Override
void delete(Long aLong);
#Override
void delete(Importer importer);
#Override
void delete(Iterable<? extends Importer> iterable);
#Query("select u from Importer u where u.importerVatNumber = :importerVatNumber")
Importer getImporterByimporterVatNumber(#Param("importerVatNumber") String importerVatNumber);
#Query("select u from Importer u inner join u.agentList where u.importerId = :importerId")
List<Importer> findAgents(#Param("importerId") long importerId);
#Query("select u from Importer u where u.importerId = :importerId")
Importer getImporterByimporterID(#Param("importerId") long importerId);
}
my services is
public List<Importer> getAllIAgents(long importerId) {
return importerRepository.findAgents(importerId);
}
My controller is
#RequestMapping(path = "/viewImporter", method = RequestMethod.POST)
public String updateImporterAll(#RequestParam("importerId") long importerId, Model model) {
slsiLogger.info("Updating user with Id [{}]", importerId);
System.out.println("Importer id is " + importerId);
model.addAttribute("importerDetails", importerServices.getImporterByimporterID(importerId));
model.addAttribute("Agentsdetail", importerServices.getAllIAgents(importerId));
return "importerEdit";
}
Jsp is
<th width="15%">Registered Agents</th>
<c:forEach items="${Agentsdetail}" var="Agent">
<tr>
<td>${Agent.agentList.vatNumber}</td>
</tr>
/c:forEach>
</thead>
The query shows in netbeans console like this
Hibernate: select importer0_.importer_id as importer1_2_, importer0_.email as email2_2_, importer0_.importer_address1 as importer3_2_, importer0_.importer_address2 as importer4_2_, importer0_.importer_address3 as importer5_2_, importer0_.importer_brc as importer6_2_, importer0_.importer_city_name as importer7_2_, importer0_.importer_name as importer8_2_, importer0_.importer_vat_number as importer9_2_, importer0_.mobile_phone_number as mobile_10_2_, importer0_.office_phone_number as office_11_2_, importer0_.optemail1 as optemai12_2_, importer0_.optemail2 as optemai13_2_ from importers importer0_ inner join importer_agents agentlist1_ on importer0_.importer_id=agentlist1_.importer_id inner join agents agent2_ on agentlist1_.agent_id=agent2_.agent_id where importer0_.importer_id=?
How can i insert agent table values to my jsp.Please help me

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