Angular HttpErrorResponse GET Request - java

I have a simple Quarkus project and want to show the data in an Angular table with HttpClient. I also have a CORS Filter. Anyway, I get the following error:
Angular table with no date, HttpErrorResponse Status 0
service.ts
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { School } from './model/school';
#Injectable({
providedIn: 'root'
})
export class SchoolService {
url = "localhost:8080/school"
constructor(public http: HttpClient) { }
getAll(): Observable<School[]> {
return this.http.get<School[]>(this.url);
}
getById(id: number): Observable<School> {
const url = "locahlost:8080/school/{id}";
return this.http.get<School>(url);
}
}
ts of component
import { Component, OnInit } from '#angular/core';
import { School } from '../model/school';
import { SchoolService } from '../school.service';
#Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
schools: School[] = [];
constructor(public schoolService: SchoolService) { }
ngOnInit(): void {
this.schoolService.getAll().subscribe(e => {
this.schools = e;
});
}
}
html
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Street</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let school of schools">
<td>{{school.id}}</td>
<td>{{school.name}}</td>
<td>{{school.street}}</td>
</tr>
</tbody>
</table>
server model
package model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class School {
#Id
#GeneratedValue
private int id;
private String name;
private String street;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
}
resource
package rest;
import model.School;
import javax.inject.Inject;
import javax.transaction.Transactional;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;
#Path("school")
#Produces(MediaType.APPLICATION_JSON)
#Transactional
public class SchoolResource {
#Inject
SchoolDao dao;
#GET
public List<School> getAll() {
return dao.getAll();
}
#Path("id")
#GET
public School getById(#PathParam("id") int id) {
return dao.getById(id);
}
}
dao
package rest;
import model.School;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import java.util.List;
#Dependent
public class SchoolDao {
#Inject
EntityManager em;
public List<School> getAll() {
return em.createQuery("select s from School s", School.class).getResultList();
}
public School getById(int id) {
return em.find(School.class, id);
}
}
Thank you in advance, I think the problem must be on the server, because I tried showing data with a JSON file instead of Quarkus data already, and it does work.

As #R.Richards mentioned in a comment, putting "http://" in front of the url in the service file solved the problem.

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.

How to connect/bind two tables using Spring MVC and hibernate

My English is not very well, so sorry for mistakes.
I'am using a Spring, Spring MVC, Hibernate, Spring Data.
I have two entities Customer and CustomerDetails I would like to connect/bind them.
I'am using #OneToOne annotation, but I have no idea how to set a customer for CusomerDetails and vice versa. I found that I should create Customer and CustomerDetails in controller, and there connect them, but it is not working and I think that it is a bad approach. Anyone knows How should it looks?
Thanks for help.
Customer class:
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="customer")
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="customer_id")
private int id;
#Column(name="name")
private String name;
#Column(name="email")
private String email;
#Column(name="address")
private String address;
#OneToOne(cascade=CascadeType.ALL)
private CustomerDetails customerDetails;
public Customer() {
}
public Customer(CustomerDetails customerDetails)
{
this.customerDetails=customerDetails;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public CustomerDetails getCustomerDetails() {
return customerDetails;
}
public void setCustomerDetails(CustomerDetails customerDetails) {
this.customerDetails = customerDetails;
}
#Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", email=" + email + ", address=" + address
+ ", customerDetails=" + customerDetails + "]";
}
}
CustomerDetails:
import javax.persistence.CascadeType;
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.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="customer_details")
public class CustomerDetails {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column(name="surname")
private String lastName;
#Column(name="number")
private int number;
#OneToOne(cascade= {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH})
private Customer customer;
public CustomerDetails() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
#Override
public String toString() {
return "CustomerDetails [id=" + id + ", lastName=" + lastName + ", number=" + number + ", customer=" + customer
+ "]";
}
}
Services:
import java.util.List;
import com.firstapp.entity.Customer;
public interface CustomerService {
public List<Customer>getCustomers();
public Customer getCustomer(int id);
public void saveCustomer(Customer customer);
public void deleteCustomer(int id);
public List<Customer>search(String keyword);
}
public interface CustomerDetailsService {
public List<CustomerDetails> getCustomers();
public CustomerDetails getCustomer(int id);
public void saveCustomer(CustomerDetails customer);
public void deleteCustomer(int id);
}
#Service
public class CustomerServiceImpl implements CustomerService {
#Autowired
private CustomerRepository repo;
public List<Customer> getCustomers() {
return repo.findAll();
}
public Customer getCustomer(int id) {
Optional<Customer>result= repo.findById(id);
return result.get();
}
public void saveCustomer(Customer customer) {
repo.save(customer);
}
public void deleteCustomer(int id) {
repo.deleteById(id);
}
public List<Customer>search(String keyword)
{
return repo.search(keyword);
}
}
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.firstapp.entity.CustomerDetails;
import com.firstapp.repository.CustomerDetailsRepository;
#Service
public class CustomerDetailsServiceImpl implements CustomerDetailsService{
#Autowired
private CustomerDetailsRepository repo;
public List<CustomerDetails> getCustomers() {
return repo.findAll();
}
public CustomerDetails getCustomer(int id) {
return repo.findById(id).get();
}
public void saveCustomer(CustomerDetails customer) {
repo.save(customer);
}
public void deleteCustomer(int id) {
repo.deleteById(id);
}
}
Repositories:
import java.util.List;
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.Repository;
import com.firstapp.entity.Customer;
#Repository
public interface CustomerRepository extends JpaRepository<Customer, Integer> {
#Query(value="SELECT c from Customer c where c.name LIKE '%'|| :keyword || '%'"
+ "OR c.email LIKE '%'|| :keyword || '%'"
+ "OR c.address LIKE '%'|| :keyword || '%'")
public List<Customer>search(#Param("keyword")String keyword);
}
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.firstapp.entity.CustomerDetails;
#Repository
public interface CustomerDetailsRepository extends JpaRepository<CustomerDetails, Integer> {
}
My controller:
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.firstapp.entity.Customer;
import com.firstapp.entity.CustomerDetails;
import com.firstapp.service.CustomerDetailsService;
import com.firstapp.service.CustomerDetailsServiceImpl;
import com.firstapp.service.CustomerService;
import com.firstapp.service.CustomerServiceImpl;
#Controller
#RequestMapping("/customer")public class CustomerController {
#Autowired
private CustomerService service;
#Autowired
private CustomerDetailsService serviceCD;
#GetMapping("/home")public String home(Model model)
{
List<Customer>customers=service.getCustomers();
model.addAttribute("message","Hello from Spring MVC"); model.addAttribute("customers",customers);
return "home-page";
}
#GetMapping("/showForm")
public String showForm(Map<String,Object>model)
{
Customer customer=new Customer();
CustomerDetails cd=new CustomerDetails();
customer.setCustomerDetails(cd);
model.put("customer",new Customer());
model.put("customerDetails", cd);
return "new-customer";
}
#PostMapping("/add")
public String addCustomer(#ModelAttribute("customer") Customer customer)
{
service.saveCustomer(customer);
return "redirect:/customer/addDetails";
}
#RequestMapping("/addDetails")
public String addCustomerDetails(#ModelAttribute("customerDetails") CustomerDetails customerDt)
{
serviceCD.saveCustomer(customerDt);
return "redirect:/customer/home";
}
#GetMapping("/edit")
public String editCustomer(#RequestParam int id, Model model)
{
Customer customer=service.getCustomer(id);
model.addAttribute("customer",customer);
return "edit-customer";
}
#GetMapping("/delete")
public String deleteCustomer(#RequestParam int id)
{
service.deleteCustomer(id);
return "redirect:/customer/home";
}
#GetMapping("/search")
public String search(#RequestParam String keyword,Model model)
{
List<Customer>customers=service.search(keyword);
model.addAttribute("customers",customers);
return "search-page";
}
}
my jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Customer registration</title>
</head>
<body>
<div align="center">
<h2>New Customer</h2>
<form:form action="add" method="post" modelAttribute="customer">
<table>
<tr>
<td>Name:</td>
<td><form:input path="name"/></td>
</tr>
<tr>
<td>E-mail:</td>
<td><form:input path="email"/></td>
</tr>
<tr>
<td>Address:</td>
<td><form:input path="address"/></td>
</tr>
<tr>
<td></td><td><input type="submit" value="Submit"/></td>
</tr>
</table>
</form:form>
</div>
</body>
</html>
Set the CustomerDetails for Customer:
customer.setCustomerDetail(customerDetail);
customerDetail.setCustomer(customer);
It's enough. Spring JPA automatically sets references and id's between table entities.
In additional try to change model layer:
1) First what you should to change - add the mappedBy parameter with table name into '#OneToOne'
2) Use #JoinColumn for one of entity:
for Customer:
#OneToOne(mappedBy = "customer")
#JoinColumn(name = "customer_details_id", referencedColumnName = "id")
for CustomerDetails:
#OneToOne(mappedBy = "customer_detail")
in additional: try to save CustomerDetail entity into table after creating, but before saving a Customer.
PS
Does no matter technically where are you create entities - it is just patterns and SOLID principals.
All parameters in #OneToOne and #JoinColumn should be named as fields in entity and as tables. Once I had a very difficult and long resolving with this issue. So be precise.

UnsatisfiedDependencyException: Error creating bean with name 'procjectController': Unsatisfied dependency expressed through field

I am building simple ManyToOne relationship using spring JAP. i get UnsatisfiedDependencyException Error with bean name Unsatisfied dependency expressed through field
UnsatisfiedDependencyException: Error creating bean with name 'procjectController': Unsatisfied
Here is my file.
project.java
package com.ganesh.dto;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
public class Project {
#Id
private int projectId;
private String projectName;
//Relation establish
#ManyToOne(
fetch = FetchType.LAZY,
optional = false
)
#JoinColumn(
name = "employee_id",
nullable = false
)
#JsonIgnore
private Employee employee;
public Project() {
}
public Project(int projectId, String projectName, int eId) {
super();
this.projectId = projectId;
this.projectName = projectName;
//Adding employee
this.employee = new Employee(eId,"","");
}
public int getProjectId() {
return projectId;
}
public void setProjectId(int projectId) {
this.projectId = projectId;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
//Adding getter and setters Employee reference
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
}
ProjectDao.java
package com.ganesh.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.ganesh.dto.Project;
#Repository
public interface ProjectDao extends JpaRepository<Project, Integer> {
List<Project> findEmployeeById(int eId);
}
ImpProjectService.java
package com.ganesh.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ganesh.dao.*;
import com.ganesh.dto.Project;
#Service
public class ImpProjectService implements ProjectService {
#Autowired
private ProjectDao projectDao;
#Override
public List<Project> getProjectList(int eId) {
System.out.println("in Dao class employee id"+ eId);
return projectDao.findEmployeeById(eId);
}
#Override
public Project getProjectById(int id) {
return projectDao.getOne(id);
}
#Override
public void addProject(Project project) {
projectDao.save(project);
}
#Override
public void updateProject(Project project) {
projectDao.save(project);
}
#Override
public void deleteProjectById(int id) {
projectDao.deleteById(id);
}
#Override
public List<Project> getAllProject() {
return projectDao.findAll();
}
}
ProcjectController.java
package com.ganesh.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
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.RestController;
import com.ganesh.dto.*;
import com.ganesh.service.*;
#RestController
public class ProcjectController {
#Autowired
private ImpProjectService projectService;
#RequestMapping("/projects")
public List<Project> getProjectList(){
return projectService.getAllProject();
}
#RequestMapping("/employees/{eId}/projects")
public List<Project> getAllProjects(#PathVariable int eId){
System.out.println("In Project Controller");
List<Project> projList = projectService.getProjectList(eId);
System.out.println(projList);
return projList;
}
#RequestMapping("/employees/{eId}/projects/{id}")
public Project getProjectById(#PathVariable int id) {
return projectService.getProjectById(id);
}
#RequestMapping(method = RequestMethod.POST, value="/employees/{eId}/projects")
public void addProject(#RequestBody Project project, #PathVariable int eId) {
project.setEmployee(new Employee(eId,"",""));
projectService.addProject(project);
}
#RequestMapping(method = RequestMethod.PUT, value="/employees/{eId}/projects/{id}")
public void updateProject(#RequestBody Project project, #PathVariable int eId) {
project.setEmployee(new Employee(eId,"",""));
projectService.updateProject(project);
}
#RequestMapping(method = RequestMethod.DELETE, value="/projects/{id}")
public void deleteProjecstById(#PathVariable int id) {
projectService.deleteProjectById(id);
}
}
Note: This answer is based on insufficient data, because stack trace is not available. With correct and complete stacktrace, we might be able to provide more precise answer.
Answer:
Looks like a problem in your Dao class.
You have written
#Repository
public interface ProjectDao extends JpaRepository<Project, Integer> {
List<Project> findEmployeeById(int eId);
}
Which means you are creating a repository of type Project and trying to fire a query as findEmployeeById, It should either be findByEmployee, which accepts Employee as a parameter, or should not be there in place at all. Because the query syntax and the Template parameters do not match. So Spring will not be able to initialize the query handlers for the same.
Try changing it as below, if is satisfies your purpose.
#Repository
public interface ProjectDao extends JpaRepository {
List<Project> findAllByEmployee(Employee emp);
}
Please check the same, and correct. If it still doesn't work, please post the full stack trace, and we can help you out.

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

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.

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