How to send a Request body in postman for Embedded entity class in spring data jpa? - spring-boot

Can anyone please help me on how to send a nested json requestbody in postman for the below entity class.
ProcessRequestInfo.java
import java.sql.Date;
import java.time.ZonedDateTime;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="PROCESS_REQUEST_INFO")
public class ProcessRequestInfo {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private int id;
private String userName;
private String contactNumber;
#Embedded
private DefectiveComponentInfo defectiveComponentInfo;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public DefectiveComponentInfo getDefectiveComponentInfo() {
return defectiveComponentInfo;
}
public void setDefectiveComponentInfo(DefectiveComponentInfo defectiveComponentInfo) {
this.defectiveComponentInfo = defectiveComponentInfo;
}
#Override
public String toString() {
return "ProcessRequestInfo [id=" + id + ", userName=" + userName + ", contactNumber=" + contactNumber
+ ", defectiveComponentInfo=" + defectiveComponentInfo + "]";
}
public ProcessRequestInfo(int id, String userName, String contactNumber,
DefectiveComponentInfo defectiveComponentInfo, ZonedDateTime date) {
super();
this.id = id;
this.userName = userName;
this.contactNumber = contactNumber;
this.defectiveComponentInfo = defectiveComponentInfo;
}
public ProcessRequestInfo() {
super();
// TODO Auto-generated constructor stub
}
}
DefectiveComponentInfo.java
import javax.persistence.Embeddable;
#Embeddable
public class DefectiveComponentInfo {
private String componentType;
private String componentName;
private Long quantity;
private String description;
public String getComponentType() {
return componentType;
}
public void setComponentType(String componentType) {
this.componentType = componentType;
}
public String getComponentName() {
return componentName;
}
public void setComponentName(String componentName) {
this.componentName = componentName;
}
public Long getQuantity() {
return quantity;
}
public void setQuantity(Long quantity) {
this.quantity = quantity;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "DefectiveComponentDetail [componentType=" + componentType + ", componentName=" + componentName
+ ", quantity=" + quantity + ", description=" + description + "]";
}
public DefectiveComponentInfo(String componentType, String componentName, Long quantity, String description) {
super();
this.componentType = componentType;
this.componentName = componentName;
this.quantity = quantity;
this.description = description;
}
public DefectiveComponentInfo() {
super();
// TODO Auto-generated constructor stub
}
}
I have tried few nested json requestbody in postman but the inner class data is getting null.
Below is my json request body which I have tried.
{
"userName" : "sam",
"contactNumber" : "96014587555",
"DefectiveComponentInfo":
[ {
"componentType":"Integral",
"componentName":"Bummper",
"quantity":5,
"description": "Repair product"
}]
}
Thanks in advance!!!

You are almost there. few things to be corrected
{
"userName" : "sam",
"contactNumber" : "96014587555",
"defectiveComponentInfo": {
"componentType":"Integral",
"componentName":"Bummper",
"quantity":5,
"description": "Repair product"
}
}
What i have corrected here
As per #Ausgefuchster already mentioned about the incorrect usage of [] array syntax. Removed it.
Your property name is defectiveComponentInfo not capital D.

Try this:
"DefectiveComponentInfo":
{
"componentType": "Integral",
"componentName": "Bummper",
"quantity": 5,
"description": "Repair product"
}
Because you're using [] but these indicate a list.

Related

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)

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

DAO instance not working in service class - NullPointerException

In my spring boot project I created a Repository interface (which extends CRUDRepository) and an Entity class of the Table in my DB.
This is my Repo:
#Repository
public interface AuthPaymentDao extends CrudRepository<TFraudCard,String> {
#Query("SELECT t FROM TFraudCard t where t.tokenNumber = (?1)")
TFraudCard findByTokenNumber(String tokenNumber);
}
This is my Entity Class (TOKEN_NUMBER is the primary Key in the TFRAUDCARD TABLE):
#Entity
#Table(name = "TFRAUDCARD")
public class TFraudCard {
#Id
#Column(name="TOKEN_NUMBER")
private String tokenNumber;
#Column(name="TRANSACTIONNUMBER")
private int transactionNumber;
#Column(name="CARDNUMBER")
private int cardNumber;
#Column(name="DATEADDED", insertable = false, updatable = false, nullable = false)
private Timestamp dateAdded;
#Column(name="CALLINGENTITY", nullable = false)
private String callingEntity;
#Column(name="ACCOUNTID")
private String accountId;
#Column(name="ROUTINGNUMBER")
private String routingNumber;
#Column(name="BANKACCOUNTNUMBER")
private String bankAccountNumber;
#Column(name="COMMENTS")
private String comments;
#Column(name="USERID")
private String userId;
#Column(name="REMOVEDATE")
private Timestamp removeDate;
public String getTokenNumber() {
return tokenNumber;
}
public void setTokenNumber(String tokenNumber) {
this.tokenNumber = tokenNumber;
}
public int getTransactionNumber() {
return transactionNumber;
}
public void setTransactionNumber(int transactionNumber) {
this.transactionNumber = transactionNumber;
}
public int getCardNumber() {
return cardNumber;
}
public void setCardNumber(int cardNumber) {
this.cardNumber = cardNumber;
}
public Timestamp getDateAdded() {
return dateAdded;
}
public void setDateAdded(Timestamp dateAdded) {
this.dateAdded = dateAdded;
}
public String getCallingEntity() {
return callingEntity;
}
public void setCallingEntity(String callingEntity) {
this.callingEntity = callingEntity;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getRoutingNumber() {
return routingNumber;
}
public void setRoutingNumber(String routingNumber) {
this.routingNumber = routingNumber;
}
public String getBankAccountNumber() {
return bankAccountNumber;
}
public void setBankAccountNumber(String bankAccountNumber) {
this.bankAccountNumber = bankAccountNumber;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Timestamp getRemoveDate() {
return removeDate;
}
public void setRemoveDate(Timestamp removeDate) {
this.removeDate = removeDate;
}
public TFraudCard() {
super();
}
public TFraudCard(String tokenNumber, int transactionNumber, int cardNumber, Timestamp dateAdded,
String callingEntity, String accountId, String routingNumber, String bankAccountNumber, String comments,
String userId, Timestamp removeDate) {
super();
this.tokenNumber = tokenNumber;
this.transactionNumber = transactionNumber;
this.cardNumber = cardNumber;
this.dateAdded = dateAdded;
this.callingEntity = callingEntity;
this.accountId = accountId;
this.routingNumber = routingNumber;
this.bankAccountNumber = bankAccountNumber;
this.comments = comments;
this.userId = userId;
this.removeDate = removeDate;
}
#Override
public String toString() {
return "TFraudCard [tokenNumber=" + tokenNumber + ", transactionNumber=" + transactionNumber + ", cardNumber="
+ cardNumber + ", dateAdded=" + dateAdded + ", callingEntity=" + callingEntity + ", accountId="
+ accountId + ", routingNumber=" + routingNumber + ", bankAccountNumber=" + bankAccountNumber
+ ", comments=" + comments + ", userId=" + userId + ", removeDate=" + removeDate + "]";
}
}
My Service Class:
Autowiring the DAO instance inside my Service Class:
Implementing the DAO instance inside a Method in the Service Class:
private void fraudCheck(PaymentDetail paymentDetail) throws RegularPaymentBusinessException {
logger.info("INSIDE FRAUD CHECK METHOD");
String pmtInd=paymentDetail.getPmtInd();
logger.info("pmtInd: " + pmtInd);
String tokenizedCardNum=paymentDetail.getTokenizedCardNum();
logger.info("tokenizedCardNum: " + tokenizedCardNum);
if(pmtInd.equalsIgnoreCase(VepsConstants.GIFT_CARD_IDENTIFIER) || pmtInd.equalsIgnoreCase(VepsConstants.CREDIT_CARD_IDENTIFIER) || pmtInd.equalsIgnoreCase(VepsConstants.DEBIT_CARD_IDENTIFIER)) {
logger.info("INSIDE CARD CHECK");
TFraudCard fraudCard = authPaymentDao.findByTokenNumber(tokenizedCardNum);
logger.info("fraudCard Details: " + fraudCard.toString());
if(fraudCard!=null) {
logger.info("INSIDE EXCEPTION FLOW FOR CARD FRAUD CHECK");
throw new RegularPaymentBusinessException(VepsConstants._9966, VepsConstants._9966_MESSAGE, VepsConstants.FAILURE);
}
}
}
Even though I pass the same token Number (tokenizedCardNumber) in my method as the data in the TOKEN_NUMBER column of my TFRAUDCARD table I still get a NullPointerException when I try to print a toString() of the Entity Object.
Here is the NullPointerException on my cloudFoundry logs (Click on it to see zoomed image) :
I'm providing the DB details in my dev properties file:
I have gone over every scenario in my head for why it breaks but I still can't come up with an answer. I'm using my variable marked with #Id i.e. the Primary Key for my find() method in the Repository.
I'm also adding a #Query annotation just to be even more specific.
It still does not work.

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

Spring Boot MongoDB - MongoDB cannot generate 'ID'

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

Resources