How to customize response from #query in springboot API - java

I have a problem with my API #query reponse in SpringBoot.
First I will show u my code:
#RestController
#RequestMapping("/api/osoba")
public class APIController {
#Autowired
private KsiazkaRepo ksiazkaRepo;
#JsonView(OnlyName.class)
#RequestMapping(method = RequestMethod.POST, value = "/getAll")
public Ksiazka find(#RequestParam("id") int id){
String autor = ksiazkaRepo.findInfoById(id);
Ksiazka ksiazka = new Ksiazka();
ksiazka.setAutor(autor);
return ksiazka;
}
**#Repository
public interface KsiazkaRepo extends JpaRepository<Ksiazka, Integer> {
#Query(value = "SELECT ksiazka.tytul, ksiazka.autor FROM IEci8d0gZc.ksiazka WHERE ksiazka.id_ksiazka = :id", nativeQuery = true)
String findInfoById(#Param("id") int id);
}**
#Entity
#Validated
public class Ksiazka {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int idKsiazka;
private int idKategoria;
private String isbn;
#JsonView(OnlyName.class)
private String tytul;
#JsonView(OnlyName.class)
private String autor;
private int stron;
private String wydawnictwo;
private int rokWydania;
private String opis;
public Ksiazka(){ }
public Ksiazka(int idKsiazka, int idKategoria, String isbn, String tytul, String autor, int stron, String wydawnictwo, int rokWydania, String opis) {
this.idKsiazka = idKsiazka;
this.idKategoria = idKategoria;
this.isbn = isbn;
this.tytul = tytul;
this.autor = autor;
this.stron = stron;
this.wydawnictwo = wydawnictwo;
this.rokWydania = rokWydania;
this.opis = opis;
}
public int getIdKsiazka() {
return idKsiazka;
}
public void setIdKsiazka(int idKsiazka) {
this.idKsiazka = idKsiazka;
}
public int getIdKategoria() {
return idKategoria;
}
public void setIdKategoria(int idKategoria) {
this.idKategoria = idKategoria;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getTytul() {
return tytul;
}
public void setTytul(String tytul) {
this.tytul = tytul;
}
public String getAutor() {
return autor;
}
public void setAutor(String autor) {
this.autor = autor;
}
public int getStron() {
return stron;
}
public void setStron(int stron) {
this.stron = stron;
}
public String getWydawnictwo() {
return wydawnictwo;
}
public void setWydawnictwo(String wydawnictwo) {
this.wydawnictwo = wydawnictwo;
}
public int getRokWydania() {
return rokWydania;
}
public void setRokWydania(int rokWydania) {
this.rokWydania = rokWydania;
}
public String getOpis() {
return opis;
}
public void setOpis(String opis) {
this.opis = opis;
}
And my interface OnlyName is empty.
When I'm using it like that like it is right not I can get simple response
Like:
{
"tytul": null,
"autor": "Mistrz czystego kodu. Kodeks postępowania profesjonalnych programistów,Robert C. Martin"
}
I understand that my response from #query is in String and that's why I'm getting only one result, but How should I change to get all String or something like that? Maybe String[]?
I can also create 2 different custom asking #query and get from them
1. imie,
2. nazwisko,
but this should not be the case.
Many thanks for help,
Ciao
UPDATE

Follow the steps here
In here, I am trying to tell you how to do this simply
Change the query , It should return list
#Query(value = "SELECT ksiazka.tytul, ksiazka.autor FROM IEci8d0gZc.ksiazka WHERE ksiazka.id_ksiazka = :id", nativeQuery = true)
List<String> findInfoById(#Param("id") int id); // here you can return result as list
Change the return type in "public Ksiazka find" as list
#RestController
#RequestMapping("/api/osoba")
public class APIController {
#Autowired
private KsiazkaRepo ksiazkaRepo;
#JsonView(OnlyName.class)
#RequestMapping(method = RequestMethod.POST, value = "/getAll")
public List<Ksiazka> find(#RequestParam("id") int id){
}
Inside body try to do get result as list ,
#RestController
#RequestMapping("/api/osoba")
public class APIController {
#Autowired
private KsiazkaRepo ksiazkaRepo;
#JsonView(OnlyName.class)
#RequestMapping(method = RequestMethod.POST, value = "/getAll")
public List<Ksiazka> find(#RequestParam("id") int id){
List<String> autor = ksiazkaRepo.findInfoById(id); // get result as as list
List<Ksiazka> ksiazkaList = new ArrayList<>(); // create list from Ksiazka
for (String autors : autor) { // returned result you can loop
Ksiazka ksiazka = new Ksiazka(); // create Object to Ksiazka
ksiazka.setAutor(autors);
ksiazkaList.add(ksiazka); //add created object to List
}
return ksiazkaList; // return your list
}

Related

SpringBoot Hibernate, CriteriaBuilder

Is it possible to fetch Data from 3 tables in hibernate where the controller is of a different model.
codeAModel.Java
#Entity
#Table(name="demo")
//#NamedQuery(name="Demo.findAll", query="SELECT m FROM Demo m")
public class AModel implements Serializable {
#Column(name="demo_loc")
private String location;
#Column(name="name")
private String name;
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
BModel.Java
#Entity
#Table(name="location")
//#NamedQuery(name="City.findAll", query="SELECT c FROM City c")
public class BModel implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="locationNoid")
private int locationNoId;
#Column(name="Code")
private int Code;
public int getLocationNoId() {
return locationNoId;
}
public void setLocationNoId(int locationNoId) {
this.locationNoId = locationNoId;
}
public int getCode() {
return Code;
}
public void setCode(int code) {
Code = code;
}
}
CModel.java
#Entity
#Table(name="offers")
public class CModel implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int OfferShopid;
#Column(name="offerCount")
private int offerCount;
#Column(name="foodCount")
private int foodCount;
public int getOfferShopid() {
return OfferShopid;
}
public void setOfferShopid(int offerShopid) {
OfferShopid = offerShopid;
}
public int getOfferCount() {
return offerCount;
}
public void setOfferCount(int offerCount) {
this.offerCount = offerCount;
}
public int getFoodCount() {
return foodCount;
}
public void setFoodCount(int foodCount) {
this.foodCount = foodCount;
}
}
DemoDTO.java
public class LocationDTO {
private int demoId;
private String name;
private int Code;
private int foodCount;
public int getDemoId() {
return demoId;
}
public void setDemoId(int demoId) {
this.demoId = demoId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCode() {
return Code;
}
public void setCode(int code) {
Code = code;
}
public int getFoodCount() {
return foodCount;
}
public void setFoodCount(int foodCount) {
this.foodCount = foodCount;
}
}
DemoController.java
#RestController
#RequestMapping("/api/abcService")
#Api(description = "REST API to list details")
public class DemoController {
#Autowired
private DemoService DemoService;
#RequestMapping(value = "/list/v1/{user_id}/uid/{locationNoId}/location",
method = RequestMethod.GET)
#ResponseBody
#ApiOperation(value = "Get all Lists", notes = "Get all Address related
information")
public ResponseEntity<?> getAll(#PathVariable("user_id") int userId,
#PathVariable("locationNoId") int locationNoId)
{
try {
ModelMapper modelMapper = new ModelMapper();
Type listType = new TypeToken<List<DemoDTO>>() {
}.getType();
List<DemoDTO> listAll=DemoService.ListAll(userId,locationNoId);
return new ResponseEntity<>(listAll, HttpStatus.OK);
}catch (Exception ex){
String errorMessage;
errorMessage = ex.getMessage();
return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);
}
}
}
DemoDAOImpl
#Component
#Repository
#Transactional
public class DemoDAOImpl implements DemoDAO {
#PersistenceContext
private EntityManager entityManager;
#Autowired
private AService aService;
AModel aModel;
#Override
public #ResponseBody List<DemoDTO> ListAll(int User_id, int locationNoId) {
// TODO Auto-generated method stub
List<DemoDTO> listDemo=new ArrayList<>();
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<AModel> query =
criteriaBuilder.createQuery(AModel.class); Root<AModel> root =
query.from(AModel.class); query.select(root); CriteriaQuery<AModel>
select = query.select(root); TypedQuery<AModel> typedQuery =
entityManager.createQuery(select); List<AModel> AllLists =
typedQuery.getResultList();
for(AModel listofAll :AllLists ) {
System.out.println(listofAll.getid());
System.out.println(listofAll.getname());
System.out.println(listofAll.getlocation());
System.out.println(listofAll.getid());
System.out.println(listofAll.getRating());
listMalls.(AllLists);
return listMalls;
}
Base DemoController you have already a DemoService that you can reuse between other controlers. So if you have
#RestController
#RequestMapping("/api/abcServiceA")
public class DemoControllerA {
#Autowired
private DemoServiceA demoServiceA;
#RestController
#RequestMapping("/api/abcServiceB")
public class DemoControllerB {
#Autowired
private DemoServiceB demoServiceB;
You can create controler:
#RestController
#RequestMapping("/api/abcServiceB")
public class DemoControllerD {
#Autowired
private DemoServiceA demoServiceA;
#Autowired
private DemoServiceB demoServiceB;
Use this two services in one method:
#RequestMapping(value = "/list/v1/{user_id}/uid/{locationNoId}/location",method = RequestMethod.GET)
#ResponseBody
#ApiOperation(value = "Get all Lists", notes = "Get all Address related information")
public ResponseEntity<?>getAll(#PathVariable("user_id")int userId,
#PathVariable("locationNoId")int locationNoId) {
try {
ModelMapper modelMapper = new ModelMapper();
Type listType = new TypeToken<List<DemoDTO>>() {}.getType();
List<DemoDTO> listAllFromA = aemoServiceA.ListAll(userId, locationNoId);
List<DemoDTO> listAllFromB = aemoServiceB.ListAll(userId, locationNoId);
// do something with listAllFromA and listAllFromB
return new ResponseEntity<>(listAll, HttpStatus.OK);
} catch (Exception ex) {
String errorMessage;
errorMessage = ex.getMessage();
return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);
}
}

Room can't retrieve the following columns

This is the entity but I don't see any problem with this page.
I can get the word but not the other 4 columns.
#Entity(tableName = "words")
public class Model {
#PrimaryKey
#ColumnInfo(name = "_id")
private int id;
#ColumnInfo(name = "en_word")
private String en_word;
#ColumnInfo(name = "en_definition")
private String en_definition;
#ColumnInfo(name = "example")
private String example;
#ColumnInfo(name = "synonyms")
private String synonyms;
#ColumnInfo(name = "antonyms")
private String antonyms;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEn_word() {
return en_word;
}
public void setEn_word(String en_word) {
this.en_word = en_word;
}
public String getEn_definition() {
return en_definition;
}
public void setEn_definition(String en_definition) {
this.en_definition = en_definition;
}
public String getExample() {
return example;
}
public void setExample(String example) {
this.example = example;
}
public String getSynonyms() {
return synonyms;
}
public void setSynonyms(String synonyms) {
this.synonyms = synonyms;
}
public String getAntonyms() {
return antonyms;
}
public void setAntonyms(String antonyms) {
this.antonyms = antonyms;
}
}
This is the query from DAO
#Query("SELECT en_definition, example,synonyms,antonyms FROM words WHERE UPPER(:text)")
Cursor getMeaning(String text);
and this from the activity
Cursor c = application.getmDatabase().wordsDao().getMeaning(enWord);
Log.d(TAG, enWord);
if (c.moveToFirst()) {
enDefinition= c.getString(c.getColumnIndex("en_definition"));
example=c.getString(c.getColumnIndex("example"));
synonyms=c.getString(c.getColumnIndex("synonyms"));
antonyms=c.getString(c.getColumnIndex("antonyms"));
Log.d(TAG, enDefinition); //no output
}
I can log the enWord but can't reach the 4 columns within.It's working fine in databasehelper class but no output with room.
Please edit your query to:
#Query("SELECT en_definition, example, synonyms, antonyms FROM words WHERE en_word = UPPER(:text)")
Cursor getMeaning(String text);

How to call native query for spring repository(Join three tables and tables haven't any relationship)

I have three tables which called SLSNotification,SLSWorkflow and Importer These tables are not any relationships... I want to get three tables for jasper report.. So I create a native query for it.. It works fine on MySQL... But when i add it to the SLSWorkflowRepository retrieve only workflow class only.. I want to get other classes also from this repository... I think it retrieves only because i write this like this
#Query(value = "select * from slsnotification a join sls_wrkflw b on a.snumber = b.snumber join importers c on c.importer_vat_number = a.importervat where a.importervat = :importerVatNumber and a.snumber = :snumber", nativeQuery = true)
Object getForPrint(#Param("snumber") Long snumber,#Param("importerVatNumber") String importerVatNumber);
can i get other classes for SLSIWorkflow getForPrint() methord...
If i wrong please give some onother way...
This is my models
SLSNotification Model
#Entity
#Table(name = "slsnotification")
public class SLSNotification {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(length = 16)
private Long snumber;
#Column(length = 100)
private String serialCord;
private String date;
// #JsonFormat(pattern = "yyyy-MM-dd")
// private Date appPostdate = new Date();
#Column(nullable = false)
private String appPostdate;
#Column(length = 8)
private String cusOffice;
#Column(length = 1)
private String cusSerial;
#Column(length = 50)
private String cusDecNo;
#JsonFormat(pattern = "yyyy-MM-dd")
private Date cusDate;
#Column(length = 300)
private String manufacturer;
#Column(length = 300)
private String exporterAddress;
#Column(length = 20, nullable = false)
private String importerVAT;
#NotEmpty
#Column(length = 20, nullable = false)
private String declarantVAT;
private String declarantDetails;
private String vessel;
private String blNo;
private String loadingPort;
private String tradingCountry;
private String countryOrigin;
private String invoiceNo;
#JsonFormat(pattern = "yyyy-MM-dd")
private Date invoiceDate;
private Double invoiceValue;
public Long getSnumber() {
return snumber;
}
public void setSnumber(Long snumber) {
this.snumber = snumber;
}
public String getSerialCord() {
return serialCord;
}
public void setSerialCord(String serialCord) {
this.serialCord = serialCord;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getCusOffice() {
return cusOffice;
}
public void setCusOffice(String cusOffice) {
this.cusOffice = cusOffice;
}
public String getCusSerial() {
return cusSerial;
}
public void setCusSerial(String cusSerial) {
this.cusSerial = cusSerial;
}
public String getCusDecNo() {
return cusDecNo;
}
public void setCusDecNo(String cusDecNo) {
this.cusDecNo = cusDecNo;
}
public Date getCusDate() {
return cusDate;
}
public void setCusDate(Date cusDate) {
this.cusDate = cusDate;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getExporterAddress() {
return exporterAddress;
}
public void setExporterAddress(String exporterAddress) {
this.exporterAddress = exporterAddress;
}
public String getImporterVAT() {
return importerVAT;
}
public void setImporterVAT(String importerVAT) {
this.importerVAT = importerVAT;
}
public String getDeclarantVAT() {
return declarantVAT;
}
public void setDeclarantVAT(String declarantVAT) {
this.declarantVAT = declarantVAT;
}
public String getVessel() {
return vessel;
}
public void setVessel(String vessel) {
this.vessel = vessel;
}
public String getBlNo() {
return blNo;
}
public void setBlNo(String blNo) {
this.blNo = blNo;
}
public String getLoadingPort() {
return loadingPort;
}
public void setLoadingPort(String loadingPort) {
this.loadingPort = loadingPort;
}
public String getTradingCountry() {
return tradingCountry;
}
public void setTradingCountry(String tradingCountry) {
this.tradingCountry = tradingCountry;
}
public String getCountryOrigin() {
return countryOrigin;
}
public void setCountryOrigin(String countryOrigin) {
this.countryOrigin = countryOrigin;
}
public String getInvoiceNo() {
return invoiceNo;
}
public void setInvoiceNo(String invoiceNo) {
this.invoiceNo = invoiceNo;
}
public Date getInvoiceDate() {
return invoiceDate;
}
public void setInvoiceDate(Date invoiceDate) {
this.invoiceDate = invoiceDate;
}
public Double getInvoiceValue() {
return invoiceValue;
}
public void setInvoiceValue(Double invoiceValue) {
this.invoiceValue = invoiceValue;
}
SLSWorkflow Model
#Entity
#Table(name = "sls_wrkflw")
public class SLSIWorkflow {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long SNumber;
private String qc;
private String inv;
private String manuTr;
private String packList;
private String blAttached;
private String otherDoc;
private String otherDocName;
private String ad;
private String MAUsername;
private String appMan;
private String accptdQc;
private String accptTR;
private String manufacturer;
private String validMark;
private String otherDocBoolean;
private String cnfrmtyTest;
private String dtSampling;
private String otherDocDet;
private String adUsername;
private String recom;
private String reaRec;
private String tests;
private String wfStatus;
public Long getSNumber() {
return SNumber;
}
public void setSNumber(Long SNumber) {
this.SNumber = SNumber;
}
public String getQc() {
return qc;
}
public void setQc(String qc) {
this.qc = qc;
}
public String getInv() {
return inv;
}
public void setInv(String inv) {
this.inv = inv;
}
public String getManuTr() {
return manuTr;
}
public void setManuTr(String manuTr) {
this.manuTr = manuTr;
}
public String getPackList() {
return packList;
}
public void setPackList(String packList) {
this.packList = packList;
}
public String getBlAttached() {
return blAttached;
}
public void setBlAttached(String blAttached) {
this.blAttached = blAttached;
}
public String getMaattachUser() {
return maattachUser;
}
public void setMaattachUser(String maattachUser) {
this.maattachUser = maattachUser;
}
public String getMauser() {
return mauser;
}
public void setMauser(String mauser) {
this.mauser = mauser;
}
public String getMareattachUser() {
return mareattachUser;
}
public void setMareattachUser(String mareattachUser) {
this.mareattachUser = mareattachUser;
}
public String getOtherDoc() {
return otherDoc;
}
public void setOtherDoc(String otherDoc) {
this.otherDoc = otherDoc;
}
public String getOtherDocName() {
return otherDocName;
}
public void setOtherDocName(String otherDocName) {
this.otherDocName = otherDocName;
}
}
Importer Model
#Entity
#Table(name = "importers")
public class Importer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "importer_id")
private long importerId;
private String importerBrc;
#NotEmpty
#Column(unique = true, nullable = false)
private String importerVatNumber;
#Column(nullable = false)
private String category;
private String importerSVatNumber;
#NotEmpty
private String importerName;
private String importerAddress1;
#NotEmpty
private String officePhoneNumber;
#NotEmpty
private String mobilePhoneNumber;
#Email
#NotEmpty
private String email;
#Email
private String optemail1;
#Email
private String optemail2;
#NotEmpty
private String userIDandTime;
#NotEmpty
private String recentUpdateBy;
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 getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getImporterSVatNumber() {
return importerSVatNumber;
}
public void setImporterSVatNumber(String importerSVatNumber) {
this.importerSVatNumber = importerSVatNumber;
}
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;
}
}
SLSIWorkflowRepository
public interface SLSIWorkflowRepository extends CrudRepository<SLSIWorkflow,Long> {
#Override
SLSIWorkflow save(SLSIWorkflow slsiWorkflow);
#Override
SLSIWorkflow findOne(Long Long);
#Override
boolean exists(Long Long);
#Override
Iterable<SLSIWorkflow> findAll();
#Override
long count();
#Override
void delete(SLSIWorkflow entity);
#Query(value = "select * from slsnotification a join sls_wrkflw b on a.snumber = b.snumber join importers c on c.importer_vat_number = a.importervat where a.importervat = :importerVatNumber and a.snumber = :snumber", nativeQuery = true)
Object getForPrint(#Param("snumber") Long snumber,#Param("importerVatNumber") String importerVatNumber);
WorkflowServices
public class WorkflowServices {
private static final Logger serviceLogger = LogManager.getLogger(WorkflowServices.class);
private static final String INIT_WORKFLOW_STATUS = "INIT";
#Autowired
private SLSIWorkflowRepository workflowRepository;
#Autowired
private FileSystemStorageService storageService;
#Autowired
private SLSNotificationRepository slsNotificationRepository;
public void initWorkflow(Long slsNumber) {
SLSIWorkflow workflow = new SLSIWorkflow();
workflow.setSNumber(slsNumber);
workflow.setWfStatus(INIT_WORKFLOW_STATUS);
workflowRepository.save(workflow);
}
public SLSIWorkflow getApplicationForPrint(Long SNumber, String importerVatNumber) {
return workflowRepository.getForPrint(SNumber, importerVatNumber);
}
}
Workflow Controller //this is large and i gives my cord only
#RequestMapping(path = "/viewTAXInvoice/{snumber}/{importerVatNumber}", method = RequestMethod.POST)
public ModelAndView getPDFReport(#PathVariable("snumber") String snumber, #PathVariable("importerVatNumber") String importerVatNumber) {
File reportsDir = Paths.get(servletContext.getRealPath(reportDataLocation)).toFile();
if (!reportsDir.exists()) {
throw ProductWithSameSerialExistsException.getInstance();
}
JRDataSource dataSource = new JRBeanCollectionDataSource(Arrays.asList(workflowServices.getApplicationForPrint(Long.parseLong(snumber), importerVatNumber)));
Map<String, Object> parameterMap = new HashMap<>();
parameterMap.put("datasource", dataSource);
parameterMap.put("JasperCustomSubReportDatasource", dataSource);
parameterMap.put(JRParameter.REPORT_FILE_RESOLVER, new SimpleFileResolver(reportsDir));
System.out.println("Dt Source1 "+dataSource);
return new ModelAndView("pdfReportforVAT", parameterMap);
}
How to connect three tables... Please help me someone...
You are getting a SLSIWorkflow only because you are returning that Entity only in the following code in WorkflowServices.
public SLSIWorkflow getApplicationForPrint(Long SNumber, String importerVatNumber) {
return workflowRepository.getForPrint(SNumber, importerVatNumber);
}
If you return an Object it will have all the fields from tables slsnotification, sls_wrkflw, importers as a Object[].
Plus using a Plain JOIN it will result in an INNER JOIN by default. This will not return anything if one joined table doesn't satisfy the ON criteria. It is good if you use LEFT JOIN so that the null will be returned.

javax.el.PropertyNotFoundException: Property not found on type java.lang.String in a Spring-Hibernate-MySQL application

I have a mysql query which returns multiple rows if I run it in query editor of mysql workbench. Now I want to push the results from the query to a list, add the list to the model, and show the result in the view. But, I am getting an error. What am I doing wrong, and how this can be fixed?
Code snippet from the controller:
#Transactional
#RequestMapping(value = "/question-editor", method = RequestMethod.GET)
public ModelAndView viewQuestionsToEdit(#RequestParam("username")String user, ModelAndView model, Principal principal){
model.setViewName("question-editor");
int id2 = 0;
try
{
if(user != null)
id2 = Integer.parseInt(user);
}
catch (NumberFormatException e)
{
id2 = 0;
}
Question question = em.find(com.databaseproject.questor.model.Question.class, id2);
model.addObject("question", question);
List<Question> questions = (List<Question>)em.createNativeQuery("SELECT q.questionText FROM question q WHERE idQuestion IN (SELECT qchq.Question_idQuestion FROM questioncart_has_question qchq JOIN (SELECT qc.idQuestionCart FROM questioncart qc WHERE User_username =:id2 ORDER BY idQuestionCart DESC LIMIT 1) qc ON qchq.QuestionCart_idQuestionCart = qc.idQuestionCart );")
.setParameter("id2", user).getResultList();
model.addObject("questionstoedit", questions);
String name = principal.getName(); //get logged in username
model.addObject("username", name);
return model;
}
Trying to get the values into the jsp view file:
<c:forEach var="question" items="${questionstoedit}">
<p>Question no. ${question.questionText}</p>
</c:forEach>
The error I am getting is:
javax.el.PropertyNotFoundException: Property 'questionText' not found
on type java.lang.String
Here is the model class: Question.java:
package com.databaseproject.questor.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Transient;
#Entity
public class Question {
#Id
private int idQuestion;
private String questionText;
private String solutionText;
private byte[] image;
private String filepath;
private int year;
private String User_username;
private int Teacher_idTeacher;
private String Course_coursecode;
#Transient
private String encodedImage;
public int getIdQuestion() {
return idQuestion;
}
public void setIdQuestion(int idQuestion) {
this.idQuestion = idQuestion;
}
public String getQuestionText() {
return questionText;
}
public void setQuestionText(String questionText) {
this.questionText = questionText;
}
public String getSolutionText() {
return solutionText;
}
public void setSolutionText(String solutionText) {
this.solutionText = solutionText;
}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
public String getFilepath() {
return filepath;
}
public void setFilepath(String filepath) {
this.filepath = filepath;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getUser_username() {
return User_username;
}
public void setUser_username(String user_username) {
User_username = user_username;
}
public int getTeacher_idTeacher() {
return Teacher_idTeacher;
}
public void setTeacher_idTeacher(int teacher_idTeacher) {
Teacher_idTeacher = teacher_idTeacher;
}
public String getCourse_coursecode() {
return Course_coursecode;
}
public void setCourse_coursecode(String course_coursecode) {
Course_coursecode = course_coursecode;
}
public String getEncodedImage() {
return encodedImage;
}
public void setEncodedImage(String encodedImage) {
this.encodedImage = encodedImage;
}
}
Change the return type to a List of String :
List<String> questions = (List<String>)em.createNativeQuery("...");
You are selecting a List of strings, without a specific Mapper it can't be mapped to the Question class.
Apply this change on the JSP :
<c:forEach var="question" items="${questionstoedit}">
<p>Question no. ${question}</p>
</c:forEach>

org.hibernate.exception.DataException: could not execute statement

I am new in Spring and Hibernate and i'm develop E-Commerce management system and my trouble is in the uploading files into DB with Hibernate. I have some service but that i see it doesn't work.
here is my code
domain
#Entity
#Table(name = "DEPUTES_APPEAL")
public class DeputesAppeal implements Serializable {
#Id
#Column(name = "ID")
#GeneratedValue
private long id;
#Column(name = "NumberOfAppeal")
private Integer number;
#Column(name = "DateOfIncomingAppeal")
private Date IncomingDate;
#Column(name = "NameOfDepute")
private String NameOfDepute;
#Column(name = "ResolutionOfChief")
private String ResolutionOfChief;
#Column(name = "TypeOfAppeal")
private String typeOfAppeal;
#OneToMany(mappedBy = "deputesAppeal", cascade =
CascadeType.ALL, fetch= FetchType.EAGER)
private final Set<UploadFiles> fileUpload = new HashSet<UploadFiles>
();
public DeputesAppeal(){}
public DeputesAppeal(int id, int number, Date incomingDate, String
nameOfDepute, String resolutionOfChief) {
this.id = id;
this.number = number;
this.IncomingDate = incomingDate;
this.NameOfDepute = nameOfDepute;
this.ResolutionOfChief = resolutionOfChief;
}
public long getId() {
return id;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public Date getIncomingDate() {
return IncomingDate;
}
public void setIncomingDate(Date incomingDate) {
IncomingDate = incomingDate;
}
public String getNameOfDepute() {
return NameOfDepute;
}
public void setNameOfDepute(String nameOfDepute) {
NameOfDepute = nameOfDepute;
}
public String getResolutionOfChief() {
return ResolutionOfChief;
}
public void setResolutionOfChief(String resolutionOfChief) {
ResolutionOfChief = resolutionOfChief;
}
public String getTypeOfAppeal() {
return typeOfAppeal;
}
public void setTypeOfAppeal(String typeOfAppeal) {
this.typeOfAppeal = typeOfAppeal;
}
public Set<UploadFiles> getFileUpload() {
return fileUpload;
}
}
dao layer where i am save object whose field is Set of UploadFiles
public class MysqlImpl implements DeputesAppealDao{
#Autowired
SessionFactory sessionFactory;
public List<DeputesAppeal> getAll() {
Query query = sessionFactory.getCurrentSession().createQuery("from
DeputesAppeal");
return query.list();
}
public DeputesAppeal getById(Integer id) {
DeputesAppeal deputesAppeal = (DeputesAppeal)
sessionFactory.getCurrentSession().get(DeputesAppeal.class, id);
return deputesAppeal;
}
public void addAppeal(DeputesAppeal deputesAppeal,
CommonsMultipartFile[] fileUpload) {
if (fileUpload != null && fileUpload.length > 0) {
for (CommonsMultipartFile aFile : fileUpload) {
UploadFiles uploadFiles = new UploadFiles();
uploadFiles.setFileName(aFile.getOriginalFilename());
uploadFiles.setData(aFile.getBytes());
deputesAppeal.addFile(uploadFiles);
sessionFactory.getCurrentSession().save(deputesAppeal);
}
}
}
public void deleteAppeal(Integer id) {
DeputesAppeal deputesAppeal = (DeputesAppeal)
sessionFactory.getCurrentSession().get(DeputesAppeal.class, id);
sessionFactory.getCurrentSession().delete(deputesAppeal);
}
public void editAppeal(DeputesAppeal deputesAppeal, DeputesAppeal
existingDeputesAppeal) {
sessionFactory.getCurrentSession().save(existingDeputesAppeal);
}
public DeputesAppeal modSession(DeputesAppeal deputesAppeal) {
DeputesAppeal deputesAppeal1 = (DeputesAppeal)
sessionFactory.getCurrentSession().get(DeputesAppeal.class,
deputesAppeal.getId());
return deputesAppeal1;
}
public List<DeputesAppeal> abstractSearch(String searchingChar) {
Query query = sessionFactory.getCurrentSession().createQuery("from
DeputesAppeal where id = " + searchingChar);
return query.list();
}
}
and at least is Controller
#Controller
#RequestMapping(value = "/main")
public class MainController {
#Qualifier("deputesAppealServiceBean")
#Autowired
DeputesAppealService deputesAppealService;
#RequestMapping(value = "/mainFrame", method = RequestMethod.GET)
public String getMainPage(){
return "mainPage";
}
#RequestMapping(value = "/resultOfSearching", method =
RequestMethod.GET)
public String getSearchResult(Model model,
#ModelAttribute("searchChar")String searchResult){
List<DeputesAppeal> deputesAppeals =
deputesAppealService.abstractSearch(searchResult);
model.addAttribute("ListOfAppeals", deputesAppeals);
return "searchingResultPage";
}
#RequestMapping(value = "mainFrame/new", method = RequestMethod.GET)
public String getAddNewAppealPage(){
return "addPage";
}
#RequestMapping(value = "mainFrame/new", method = RequestMethod.POST)
public String addNewAppeal(#ModelAttribute("Appeal")DeputesAppeal
deputesAppeal,
#RequestParam("fileUpload")CommonsMultipartFile[] fileUpload){
deputesAppealService.add(deputesAppeal, fileUpload);
return "mainPage";
}
#RequestMapping(value = "mainFrame/deleted", method =
RequestMethod.GET)
public String deleteAppeal(#RequestParam(value = "id", required =
true) Integer id, Model model){
deputesAppealService.delete(id);
model.addAttribute("id", id);
return "deletedPage";
}
#RequestMapping(value = "mainFrame/editPage", method =
RequestMethod.GET)
public String GetEdit(#RequestParam(value = "id", required = true)
Integer id, Model model){
model.addAttribute("editedAppeal",
deputesAppealService.getById(id));
return "editPage";
}
#RequestMapping(value = "mainFrame/editPage", method =
RequestMethod.POST)
public String editCurrentAppeal(#ModelAttribute("userAttribute")
DeputesAppeal deputesAppeal,#RequestParam(value = "id", required =
true)Integer id, Model model) {
deputesAppeal.setNumber(id);
deputesAppealService.edit(deputesAppeal);
model.addAttribute("id", id);
return "editedPage";
}
}
and when on JSP page i submit input data i handle the next errors
HTTP Status 500 - Request processing failed; nested exception is
org.springframework.dao.DataIntegrityViolationException: could not
execute statement; SQL [n/a]; nested exception is
org.hibernate.exception.DataException: could not execute statement
domain of UploadFiles
#Entity
#Table(name = "UploadFiles")
public class UploadFiles implements Serializable {
#Id
#GeneratedValue
#Column(name = "FILE_ID")
private long id;
#Column(name = "FILE_NAME")
private String fileName;
#Column(name = "FILE_DATA")
private byte[] data;
#ManyToOne
#JoinColumn(name = "ID")
private DeputesAppeal deputesAppeal;
public UploadFiles(){}
public UploadFiles(long id, String fileName, byte[] data){
this.id = id;
this.fileName = fileName;
this.data = data;
}
public long getId() {
return id;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
public DeputesAppeal getDeputesAppeal() {
return deputesAppeal;
}
public void setDeputesAppeal(DeputesAppeal deputesAppeal) {
this.deputesAppeal = deputesAppeal;
}
For anyone else stumbling on this - it has to do with the data you are trying to insert - for me it was attempting to insert a String that was longer than the size set in the Hibernate annotations. In debugging, you can follow the cause of the Exception to find the root cause.
I got this error because I was saving too much data in varchar. I changed it to type text and increased char limit to 65535.
I got this error due to not enough filed length in the database table.

Categories

Resources