Building controller using Spring RestController and Jackson give me HTTP Stats 406 - java

I'm building a rest controller using Spring to handle request and Jackson to serialize data.However I followed tutorial online but I end up getting an error.
HTTP Status 406 -
type Status report
message
description The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.
After Google for a while, I realized that it is because I don't have "application/json" as my "Accept" header in my request:
So I use a tool called Postman to manually add this "Accept" header in the request, send the request again, but still getting the same error:
I'm so confused, I've already included "application/json" as one of accepted data-type, why I still have this data-unsupported error? FYI, here is my Rest Controller class:
package mywebapp.controller;
import java.io.IOException;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import mywebapp.dao.model.interfaces.PetDao;
import mywebapp.model.Pet;
#RestController
#RequestMapping(value = "petJson.htm")
public class PetControllerAjax {
private static final Logger LOG = LoggerFactory.getLogger(PetController.class);
public static Logger getLog() {
return LOG;
}
#Autowired
#Qualifier("PetDaoJpaImpl")
private PetDao petDao;
public PetDao getPetDao() {
return petDao;
}
public void setPetDao(PetDao petDao) {
this.petDao = petDao;
}
#RequestMapping(method = RequestMethod.GET)
public List<Pet> getAllPets() throws IOException {
getLog().info("Rest Controller activating........");
List<Pet> petList = getPetDao().getAllPets();
return petList;
}
}
And here is my Pet entity class:
package mywebapp.model;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Date;
import java.util.Set;
#Entity
#Table(name = "pet")
public class Pet {
private int petId;
private String name;
private String owner;
private String species;
private String sex;
private Date birth;
private Date death;
private Set<Toy> toys;
#Id
#Column(name = "pet_id")
#GeneratedValue
#JsonProperty(value="pet_id",required=true)
public int getId() {
return petId;
}
public void setId(int id) {
this.petId = id;
}
#JsonProperty(value="pet_name",required=true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Date getDeath() {
return death;
}
public void setDeath(Date death) {
this.death = death;
}
#OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER,targetEntity=Toy.class, mappedBy="pet")
public Set<Toy> getToys() {
return toys;
}
public void setToys(Set<Toy> toys) {
this.toys = toys;
}
}
Anyone knows what's going on here? Any hint will be appreciated, lots of thanks in advance!

Jackson 2.7 is not supported by Spring 4.2 - it will be in 4.3+.
Check out the library requirements for Spring on the Spring wiki and see SPR-13728 and SPR-13483.

Related

Spring Repository Bean Not Being Found

I'm trying to do a simple CRUD in postgres with spring, but for no reason my IoD mechanism doesn't work and throws an error like this:
Description:
Parameter 0 of constructor in br.com.maptriz.formulario_dinamico.service.FormularioDinamicoService required a bean of type 'br.com.maptriz.formulario_dinamico.repository.FormularioDinamicoRepository' that could not be found.
Action:
Consider defining a bean of type 'br.com.maptriz.formulario_dinamico.repository.FormularioDinamicoRepository' in your configuration.
Here's my code:
FormularioDinamicoApplication.java
package br.com.maptriz.formulario_dinamico;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
// #EnableJpaRepositories("br.com.maptriz.formulario_dinamico.repository")
// #EnableScheduling
// #EnableDiscoveryClient
// #ComponentScan
#SpringBootApplication
public class FormularioDinamicoApplication {
public static void main(String[] args) {
SpringApplication.run(FormularioDinamicoApplication.class, args);
}
}
FormularioDinamico
package br.com.maptriz.formulario_dinamico.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "formulario_dinamico")
public class FormularioDinamico {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne
#JoinColumn(name="tipo_tabela")
private Long tabelaId;
private String name;
private String campos;
protected FormularioDinamico() {}
public FormularioDinamico(Long tabelaId, String name, String campos) {
this.tabelaId = tabelaId;
this.name = name;
this.campos = campos;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getTabelaId() {
return this.tabelaId;
}
public void setTabelaId(Long tabelaId) {
this.tabelaId = tabelaId;
}
public String getName() {
return this.name;
}
public void setObservacao(String name) {
this.name = name;
}
public String getCampos() {
return this.campos;
}
public void setCampos(String campos) {
this.campos = campos;
}
#Override
public String toString() {
return "EntidadeGenerica{" +
"id=" + id +
", dataAtualizacao=" + tabelaId +
", dataCadastro=" + name +
", observacao='" + campos + '}';
}
}
FormlarioDinamicoController.java
package br.com.maptriz.formulario_dinamico.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import br.com.maptriz.formulario_dinamico.model.FormularioDinamico;
import br.com.maptriz.formulario_dinamico.service.FormularioDinamicoService;
#RestController
#RequestMapping
public class FormularioDinamicoController {
private final FormularioDinamicoService service;
#Autowired
public FormularioDinamicoController(FormularioDinamicoService service) {
this.service = service;
}
// #GetMapping
// public List<DynamicForm> getDynamicForm() {
// return dynamicFormService.getDynamicForm();
// }
#PostMapping("/create")
public void registrarNovoFormularioDinamico(#RequestBody FormularioDinamico formularioDinamico) {
System.out.println("TEST");
service.adicionarNovoFormularioDinamico(formularioDinamico);
}
}
FormularioDinamicoService.java
package br.com.maptriz.formulario_dinamico.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.maptriz.formulario_dinamico.model.FormularioDinamico;
import br.com.maptriz.formulario_dinamico.repository.FormularioDinamicoRepository;
#Service
public class FormularioDinamicoService {
private final FormularioDinamicoRepository repository;
#Autowired
public FormularioDinamicoService(FormularioDinamicoRepository repository) {
this.repository = repository;
}
// public List<DynamicForm> getDynamicForm() {
// return dynamicFormRepository.findAll();
// }
public void adicionarNovoFormularioDinamico(FormularioDinamico formularioDinamico) {
List<FormularioDinamico> topicos = repository.findAll();
System.out.println("HEREEEE");
System.out.println(topicos);
}
}
And finally FormularioDinamicoRepository.java
package br.com.maptriz.formulario_dinamico.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import br.com.maptriz.formulario_dinamico.model.FormularioDinamico;
public interface FormularioDinamicoRepository
extends JpaRepository<FormularioDinamico, Long> {
List<FormularioDinamico> findAll();
}
My Folder Structure:
src
main
java/br/com/maptriz/formulario_dinamico
controller
model
repository
service
FormularioDinamicoApplication.java
Add #Repository annotation on the interface FormularioDinamicoRepository. It should be working seamlessly.
The moment you add it spring identifies it as a bean and creates an object and injects the bean wherever autowired.

Not able to instatiate Repository bean in Springboot test class

I try to test my JPA in Springboot but I get error as following. Referred several threads related to it and tried every solution but none of them are working.
If I use #MockBean for repository class, the data is not persisting and retrieving. IF I use #Autowired, I am getting the above error.
I used #SpringbootTest as well as #DataJpaTest with #ContextConfiguration but none of the annotations solves the problem. What am I missing here? Please help.
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [de.api.repository.StyledLayerDescriptorStorageRepository]: Specified class is an interface
import de.api.entity.StyledLayerDescriptorEntity;
import de.api.entity.StyledLayerDescriptorEntityBuilder;
import de.api.repository.StyledLayerDescriptorStorageRepository;
import de.api.service.StyledLayerDescriptorStorageService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Profile;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.junit4.SpringRunner;
import java.time.OffsetDateTime;
import java.util.Optional;
#RunWith(SpringRunner.class)
#ContextConfiguration(classes = {de.api.repository.StyledLayerDescriptorStorageRepository.class})
#DataJpaTest
#EnableAutoConfiguration
public class StyledLayerDescriptorStorageRepositoryTest {
#Autowired
StyledLayerDescriptorStorageRepository styledLayerDescriptorStorageRepository;
#Test
#Profile(("Test"))
public void testRepository(){
String sldId = "5c0405b0-2a09-4d52-a702-6395445bd575";
StyledLayerDescriptorEntity sld =
new StyledLayerDescriptorEntityBuilder(
sldId,
OffsetDateTime.parse("2021-03-11T09:00:07Z"),
"my content")
.build();
styledLayerDescriptorStorageRepository.save(sld);
Optional<StyledLayerDescriptorEntity> sldRes = styledLayerDescriptorStorageRepository.findById(sldId);
}
}
Repository class
package de.api.repository;
import de.api.entity.StyledLayerDescriptorEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import java.time.OffsetDateTime;
import java.util.List;
#Component
#Repository
public interface StyledLayerDescriptorStorageRepository extends JpaRepository<StyledLayerDescriptorEntity, String> {
public final static String FIND_BY_TIME_STAMP = "SELECT S.id FROM StyledLayerDescriptorEntity S WHERE S.timestamp<:timestamp";
#Query(FIND_BY_TIME_STAMP)
public List<String> findByTimeStamp(#Param("timestamp")OffsetDateTime timestamp);
}
Entity class
package de.api.entity;
import javax.persistence.*;
import java.time.OffsetDateTime;
#Entity
#Table(name = "StyledLayerDescriptor")
public class StyledLayerDescriptorEntity {
#Id private String id;
private OffsetDateTime timestamp;
#Column(columnDefinition = "NVARCHAR(max)")
private String sldContent;
public StyledLayerDescriptorEntity() {}
public StyledLayerDescriptorEntity(String id, OffsetDateTime timestamp, String sldContent) {
this.id = id;
this.timestamp = timestamp;
this.sldContent = sldContent;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSldContent() {
return sldContent;
}
public void setSldContent(String sldContent) {
this.sldContent = sldContent;
}
public OffsetDateTime getTimestamp() {
return timestamp;
}
public void setTimestamp(OffsetDateTime timestamp) {
this.timestamp = timestamp;
}
}
Entity Builder
package de.api.entity;
import java.time.OffsetDateTime;
public class StyledLayerDescriptorEntityBuilder {
private String id;
private OffsetDateTime timestamp;
private String sldContent;
public StyledLayerDescriptorEntityBuilder(String id, OffsetDateTime timestamp, String sldContent) {
this.id = id;
this.timestamp = timestamp;
this.sldContent = sldContent;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public OffsetDateTime getTimestamp() {
return timestamp;
}
public void setTimestamp(OffsetDateTime timestamp) {
this.timestamp = timestamp;
}
public String getSldContent() {
return sldContent;
}
public void setSldContent(String sldContent) {
this.sldContent = sldContent;
}
public StyledLayerDescriptorEntity build() {
return new StyledLayerDescriptorEntity(id, timestamp, sldContent);
}
}

Lazy loading doesn't work in simple Hibernate/Spring boot example, after retrieving object from JpaRepository

I have developped a Spring boot application that was using fetch = EAGER annotation on all relationships between entities. I think this is causing severe performance issues and I've since learned that it is seemingly an anti-pattern (https://vladmihalcea.com/the-open-session-in-view-anti-pattern/ & https://vladmihalcea.com/eager-fetching-is-a-code-smell/).
I've been trying to figure out how to use lazy loading properly. I've come up with a minimal example that allows me to reproduce it.
TestJpaApplication
package com.myproject.testJpa;
import com.myproject.testJpa.entity.Host;
import com.myproject.testJpa.entity.HostSet;
import com.myproject.testJpa.entity.repository.HostRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import com.myproject.testJpa.entity.repository.HostSetRepository;
import org.springframework.transaction.annotation.Transactional;
#SpringBootApplication
public class TestJpaApplication {
private final Logger logger = LoggerFactory.getLogger(TestJpaApplication.class);
#Autowired
private HostRepository hostRepository;
#Autowired
private HostSetRepository hostSetRepository;
public static void main(String[] args) {
SpringApplication.run(TestJpaApplication.class, args);
}
#Bean
public CommandLineRunner demo() {
return (args) -> {
init();
fetch();
};
}
private void init() {
Host host1 = findOrCreateHost("HOST 1");
Host host2 = findOrCreateHost("HOST 2");
Host host3 = findOrCreateHost("HOST 3");
HostSet hostSet = findOrCreateHostSet("HOST SET 1");
hostSet.addHost(host1);
hostSetRepository.save(hostSet);
hostRepository.save(host1);
hostRepository.save(host2);
hostRepository.save(host3);
}
#Transactional
private void fetch() {
HostSet hostSet = hostSetRepository.findOneByNameIgnoreCase("HOST SET 1");
for(Host host : hostSet.getHosts()) {
logger.debug("Host: {}", host);
}
}
public Host findOrCreateHost(String name) {
Host host = hostRepository.findOneByNameIgnoreCase(name);
if(host == null) {
host = new Host(name);
hostRepository.save(host);
}
return host;
}
public HostSet findOrCreateHostSet(String name) {
HostSet hostSet = hostSetRepository.findOneByNameIgnoreCase(name);
if (hostSet == null) {
hostSet = new HostSet(name);
hostSetRepository.save(hostSet);
}
logger.debug("Host: {}", hostSet.getHosts());
return hostSet;
}
}
Host
package com.myproject.testJpa.entity;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
#Entity
public class Host {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "host__id")
private Long id;
private String name;
#ManyToMany(mappedBy = "hosts")
private Set<HostSet> hostSets = new HashSet<>();
public Host() {
}
public Host(Long id) {
this.id = id;
}
public Host(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<HostSet> getHostSets() {
return hostSets;
}
public void setHostSets(Set<HostSet> hostSets) {
this.hostSets = hostSets;
hostSets.forEach(hs -> addToHostSet(hs));
}
public Host addToHostSet(HostSet hostSet) {
if (!hostSets.contains(hostSet)) {
hostSets.add(hostSet);
hostSet.getHosts().add(this);
}
return this;
}
public Host removeFromHostSet(HostSet hostSet) {
if (hostSets.contains(hostSet)) {
hostSets.remove(hostSet);
hostSet.getHosts().remove(this);
}
return this;
}
}
HostSet
package com.myproject.testJpa.entity;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
#Entity
public class HostSet {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "host_set__id")
private Long id;
private String name;
#ManyToMany
#JoinTable(
name = "host_set__host",
joinColumns = #JoinColumn(name = "host_set__id"),
inverseJoinColumns = #JoinColumn(name = "host__id")
)
private Set<Host> hosts = new HashSet<>();
public HostSet() {
}
public HostSet(Long id) {
this.id = id;
}
public HostSet(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Host> getHosts() {
return hosts;
}
public void setHosts(Set<Host> hosts) {
this.hosts = hosts;
}
public HostSet addHost(Host host) {
if(!hosts.contains(host)) {
hosts.add(host);
host.addToHostSet(this);
}
return this;
}
public HostSet removeHost(Host host) {
if(hosts.contains(host)) {
hosts.remove(host);
host.removeFromHostSet(this);
}
return this;
}
}
HostRepository
package com.myproject.testJpa.entity.repository;
import com.myproject.testJpa.entity.Host;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface HostRepository extends JpaRepository<Host, Long> {
public Host findOneByNameIgnoreCase(String name);
}
HostSetRepository
package com.myproject.testJpa.entity.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.myproject.testJpa.entity.HostSet;
#Repository
public interface HostSetRepository extends JpaRepository<HostSet, Long> {
public HostSet findOneByNameIgnoreCase(String name);
}
When I run the application, it throws the following error when looping over the hosts of the retrieved hostSet in the fetch() method.
Caused by: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.myproject.testJpa.entity.HostSet.hosts, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:606)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:218)
at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:585)
at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:149)
at org.hibernate.collection.internal.PersistentSet.iterator(PersistentSet.java:188)
at com.myproject.testJpa.TestJpaApplication.fetch(TestJpaApplication.java:58)
at com.myproject.testJpa.TestJpaApplication.lambda$demo$0(TestJpaApplication.java:34)
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:784)
I've tried adding the #Transactional annotation in several places but to no avail. It's driving me crazy because I don't see what I'm doing wrong.
Thanks for your help!
It turns out that the #Transactional was not working in the TestJpaApplication class (I did not set it on the anonymous method, don't know how or if it's possible).
I moved the content to a separate service and it worked.

how to find students Bydate (findByDate)

I went to develop an application to manage students in a university, I am looking for how to find students in relation to a date entered for that I have developed the following code lines:
1- Model student.java
package com.avatar.model;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.JoinColumn;
#Entity
#Table(name = "Students")
public class Student{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String nom;
private String prenom;
private String numTel;
private String mail;
#Temporal(TemporalType.DATE)
private Date dateCurrent;
#ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
#JoinTable(name = "student_techno",
joinColumns = { #JoinColumn(name = "student_id") },
inverseJoinColumns = { #JoinColumn(name = "techno_id") })
private Set<Techno> techno = new HashSet<>();
public Student() {
}
#SuppressWarnings("unchecked")
public Student(String nom, String prenom,String numTel, String mail, Date dateCurrent,
) {
super();
this.nom = nom;
this.prenom = prenom;
this.numTel = numTel;
this.mail = mail;
this.dateCurrent = dateCurrent;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getNumTel() {
return numTel;
}
public void setNumTel(String numTel) {
this.numTel = numTel;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getdateCurrent() {
return dateCurrent;
}
public void setdateCurrent(Date dateCurrent) {
this.dateCurrent = dateCurrent;
}
#Override
public String toString() {
return "Student[nom=" + nom + ", prenom=" + prenom + ", numTel=" + numTel + ", mail="
+ mail + ", dateCurrent=" + dateCurrent+ "]";
}
}
2- Controller
package com.avatar.web;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.avatar.dao.StudentDao;
import com.avatar.model.Student;
#CrossOrigin(origins = "http://localhost:4200")
#RestController
#RequestMapping("/avatar")
public class StudentController {
#Autowired
StudentDao studentdao;
#GetMapping(value = "/all-students")
public List<Student> listeDesStudent() {
List<Student> students= studentdao.findAll();
if (students.isEmpty())
throw new ProductNotFoundException("No student is registered in the database");
return students;
}
#GetMapping(value = "/all-students/dateCurrent/{dateCurrent}")
public List<Student> viewStudent(#PathVariable("dateCurrent") #DateTimeFormat(pattern = "yyyy-MM-dd") Date dateCurrent) {
Calendar c = Calendar.getInstance();
c.setTime(dateCurrent);
c.add(Calendar.DATE, 1);
dateCurrent = c.getTime();
return studentdao.findByDate(dateCurrent);
}
#GetMapping(value = "/all-students /techno/{nomTechno}")
List<Student > viewStudent(#PathVariable("nomTechno") String nomTechno) {
return studentdao.findDistinctByTechnoNomTechno(nomTechno);
}
#PostMapping(value = "/add-student")
public Student addStudent(#RequestBody Student student) {
Student studentAdded= studentdao.save(Student);
return studentAdded;
}
}
3- DAO
package com.avatar.dao;
import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.avatar.model.Student;
#Repository
public interface StudentDao extends JpaRepository<Student, String> {
List<Student> findByDate(Date dateCurrent);
List<> findDistinctByTechnoNomTechno(String nomTechno);
}
4- applications.properties
server.port= 8080
# MySQL Properties
spring.jpa.show-sql = true
spring.datasource.url= jdbc:mysql://localhost:3306/avatar?serverTimezone=UTC&useLegacyDatetimeCode=false
spring.datasource.username=*****
spring.datasource.password=*****
# Hibernate Properties
spring.jpa.hibernate.ddl-auto=update
in my console i have:
Failed to create query for method public abstract java.util.List com.avatar.dao.StudentDao.findByDate(java.util.Date)! No property date found for type Student!
Please update DAO as per for below mentioned changes
If the field name is dateCurrent then findByDateCurrent.
package com.avatar.dao;
import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.avatar.model.Student;
#Repository
public interface StudentDao extends JpaRepository<Student, String> {
List<Student> findByDateCurrent(Date dateCurrent);
List<> findDistinctByTechnoNomTechno(String nomTechno);
}
You are missing field name, in Entity class it is not the date by dateCurrent, thus your JPA should be findByDateCurrent

Request method 'POST' not supported in spring boot

I am developing a project in Spring Boot Billing. I have successfully build and run this project but there is some issue.
When i am trying insert data via POST method but Browser shows POST method not supported.
Here is my controller
BillingController.java
package com.billing.controller;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.billing.model.Restaurant_billing;
import com.billing.model.Restaurant_billingDao;
import com.billing.model.billing;
import com.billing.model.billingDao;
import com.billing.model.itemDao;
import com.billing.model.tax_billing;
import com.billing.model.tax_billingDao;
#Controller
#RestController
#RequestMapping("/restaurant")
public class BillingController {
#Autowired
private itemDao itemDao;
#Autowired
private billingDao billingDao;
#Autowired
private Restaurant_billingDao restaurant_billingDao;
#Autowired
private tax_billingDao tax_billingDao;
SessionFactory sessionFactory;
Session sesion=null;
org.hibernate.Transaction tx=null;
#RequestMapping(value="/create", method = RequestMethod.POST, consumes =
MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public String R_billing(#RequestBody final Restaurant_billing r_billing[] ,HttpServletResponse response,HttpServletRequest request)
throws ServletException {
try{
billing billingObject = new billing();
billingDao.save(billingObject);
int billing_id = billingObject.getId();
tax_billing tax_billing= new tax_billing();
tax_billing.setBilling_id(billing_id);
tax_billing.setTax_amount("140");
tax_billingDao.save(tax_billing);
for(Restaurant_billing prof:r_billing){
prof.setBilling_id(billing_id);
restaurant_billingDao.save(prof);
}
}
catch(Exception ex){
return "Error creating the user: " + ex.toString();
}
return ("User profession added successfully");
}
}
Here is my model class
Restaurant_billing.java
package com.billing.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name ="billing_restaurant")
public class Restaurant_billing {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column(name="billing_id")
private int billing_id;
#Column(name="itemid")
private String itmeid;
#Column(name="quantity")
private String quantity;
#Column(name="billing_type")
private String billing_type;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getBilling_id() {
return billing_id;
}
public void setBilling_id(int billing_id) {
this.billing_id = billing_id;
}
public String getItmeid() {
return itmeid;
}
public void setItmeid(String itmeid) {
this.itmeid = itmeid;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getBilling_type() {
return billing_type;
}
public void setBilling_type(String billing_type) {
this.billing_type = billing_type;
}
}
No need to use #Controller use only #RestController and also assign sesion and tx values.
After that you just try the following code,
#RequestMapping(value = "/create", method = RequestMethod.POST)
public #RequestBody Restaurant_billing R_billing(final HttpServletResponse response){
try{
billing billingObject = new billing();
//Here set the billingObject values
billingDao.save(billingObject);
int billing_id = billingObject.getId();
tax_billing tax_billing= new tax_billing();
tax_billing.setBilling_id(billing_id);
tax_billing.setTax_amount("140");
tax_billingDao.save(tax_billing);
for(Restaurant_billing prof:r_billing){
prof.setBilling_id(billing_id);
restaurant_billingDao.save(prof);
}
}
catch(Exception ex){
return "Error creating the user: " + ex.toString();
}
return ("User profession added successfully");
}
//here return obj
}

Categories

Resources