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
}
Related
This is probebly a repetition to my yesturday's question here
Can't save data to a database with DTO
I can get a request as DTO. But then I convert it to a model class back I get value of regionid column as null.
My DTO Class
package com.example.dto;
import java.util.HashSet;
import java.util.Set;
import lombok.Data;
#Data
public class TownDTO {
public String name;
public String regionid;
}
My model:
package com.example.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
#Data
#NoArgsConstructor
#AllArgsConstructor
#Entity
#Table(name = "towns")
public class Towns {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column(name = "name")
private String name;
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "regionid", nullable = false)
#OnDelete(action = OnDeleteAction.CASCADE)
private Regions regionid;
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 Regions getRegionid() {
return regionid;
}
public void setRegionid(Regions regionid) {
this.regionid = regionid;
}
}
Controller:
package com.example.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.dto.TownDTO;
import com.example.model.Regions;
import com.example.model.Towns;
import com.example.repository.TownsRepository;
import com.example.repository.RegionsRepository;
import java.util.stream.Collectors;
import org.modelmapper.Conditions;
import org.modelmapper.ModelMapper;
#CrossOrigin(origins = "http://localhost:8081")
#RestController
#RequestMapping("/towns")
public class TownsController {
#Autowired
TownsRepository townsrepository;
#Autowired
RegionsRepository regionsrepository;
#Autowired
private ModelMapper modelMapper;
#GetMapping("/list")
public ResponseEntity<List<Towns>> getAllTowns(#RequestParam(required = false) String name) {
try {
List<Towns> towns = new ArrayList<Towns>();
if (name == null)
townsrepository.findAll().forEach(towns::add);
else
townsrepository.findByNameContaining(name).forEach(towns::add);
if (towns.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(towns, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
#GetMapping("/list/{id}")
public ResponseEntity<Towns> getTownById(#PathVariable("id") int id) {
Optional<Towns> townData = townsrepository.findById(id);
if (townData.isPresent()) {
return new ResponseEntity<>(townData.get(), HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
#PostMapping("/add")
public ResponseEntity<TownDTO> createPost(#RequestBody TownDTO townDto) {
// convert DTO to entity
Towns townRequest = modelMapper.map(townDto, Towns.class);
System.out.println("reg");
System.out.println(townRequest.getName());
System.out.println(townRequest.getRegionid());
//Regions rid=regionsrepository.findById(2).get();
// townRequest.setRegionid(townDto.regionid);
Towns town = townsrepository.save(townRequest);
// convert entity to DTO
TownDTO townResponse = modelMapper.map(town, TownDTO.class);
return new ResponseEntity<TownDTO>(townResponse, HttpStatus.CREATED);
}
/*
#PostMapping("/addt")
public ResponseEntity<Towns> createtown2(#RequestBody Towns town) {
try {
Towns _town = townsrepository
.save(town);
// Towns _town = townsrepository .save(new Towns( town.getName(), regionsrepository.findByRegionId(town.getRegionid())));
return new ResponseEntity<>(_town, HttpStatus.CREATED);
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println("region");
System.out.println(town.getRegionid());
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
*/
#PutMapping("/edit/{id}")
/*
public ResponseEntity<Towns> updateTown(#PathVariable("id") int id, #RequestBody Towns town) {
Optional<Towns> townData = townsrepository.findById(id);
if (townData.isPresent()) {
Towns _town = townData.get();
_town.setName(town.getName());
_town.setRegionid(town.getRegionid());
return new ResponseEntity<>(townsrepository.save(_town), HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
*/
#DeleteMapping("/delete/{id}")
public ResponseEntity<HttpStatus> deleteTown(#PathVariable("id") int id) {
try {
townsrepository.deleteById(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
Try to set id to an entety.
Regions rgid=regionsrepository.findById(2).get();
townRequest.setRegionid(rgid.getId());
use ModelMapper.
If your entity class id field uses #Id annotation with auto-generating JPA key like #GeneratedValue(strategy = GenerationType.IDENTITY) as id, then using only model mapper and saving the entity should give you the expected result.
Otherwise, if set your PKID value manually and then save the entity.
Update: for your updated question,
add the whole Region in your Towns entity:
Regions rgid=regionsrepository.findById(2).get();
townRequest.setRegionid(rgid);
I asked previously basically the same question and solved it somehow, but here is a problem again:
I am sending post data from my Angular 12 app
{
"qty": 2,
"paid": 200,
"ticketid": 2
}
This is for userticket model which looks like this in java:
package com.example.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import java.util.Date;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#Entity
#Table(name = "tickettouser")
public class TicketUser {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "userid", nullable = false)
#OnDelete(action = OnDeleteAction.CASCADE)
private Users userid;
#Column(name = "qty")
private int qty;
#Column(name = "paid")
private float paid;
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler","ignoreUnknown = true"})
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "ticketid", nullable = false)
#OnDelete(action = OnDeleteAction.CASCADE)
private Tickets ticketid;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Users getUserid() {
return userid;
}
public void setUserid(Users userid) {
this.userid = userid;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public float getPaid() {
return paid;
}
public void setPaid(float paid) {
this.paid = paid;
}
public Tickets getTicketid() {
return ticketid;
}
public void setTicketid(Tickets ticketid) {
this.ticketid = ticketid;
}
}
The full error:
2021-11-08 14:07:46.938 WARN 8180 --- [nio-8888-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `com.example.model.Tickets` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (2); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.example.model.Tickets` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (2)
at [Source: (PushbackInputStream); line: 1, column: 32] (through reference chain: com.example.model.TicketUser["ticketid"])]
And my ticket model
package com.example.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import java.util.Date;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#Entity
#Table(name = "tickets")
public class Tickets {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "price")
private Float price;
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "event_id", nullable = false)
#OnDelete(action = OnDeleteAction.CASCADE)
private Events eventid;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public Events getEventid() {
return eventid;
}
public void setEventid(Events eventid) {
this.eventid = eventid;
}
}
And finally my ticketuser controller
package com.example.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ModelAttribute;
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.servlet.ModelAndView;
import com.example.model.TicketUser;
import com.example.security.services.UserDetailsImp;
import com.example.model.Cities;
import com.example.model.Events;
import com.example.model.Halls;
import com.example.service.UsersticketService;
import com.example.service.EventsService;
import com.example.service.HallsService;
import com.example.service.UsersService;
import com.example.model.Users;
#Controller
#RequestMapping(value="/userticket")
#SpringBootApplication
#CrossOrigin(origins = "http://localhost:8889")
public class UsersTicketController {
#Autowired
UsersticketService usersticketService;
#Autowired
UsersService usersservice;
#RequestMapping(value="/list", method=RequestMethod.GET)
public ResponseEntity list()
{
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String usr= auth.getName();
Users user=usersservice.getUserByLogin(usr);
int id=user.getId();
List<TicketUser> ticketList=usersticketService.getTicketByUser(id);
// user.getId();
//System.out.println(user);
return new ResponseEntity<>(ticketList, HttpStatus.OK);
}
#RequestMapping(value="/add", method=RequestMethod.POST)
public ResponseEntity add(#RequestBody TicketUser ticket)
{
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String usr= auth.getName();
Users user=usersservice.getUserByLogin(usr);
Users userid=new Users();
userid.setId(user.getId());
ticket.setUserid(userid);
usersticketService.addTicket(ticket);
return new ResponseEntity<>(ticket, HttpStatus.CREATED);
}
#RequestMapping(value="/delete/{id}", method=RequestMethod.GET)
public ResponseEntity delete(#PathVariable("id") int id)
{
usersticketService.deleteTicket(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
As you can see I don't use any custom deserialize methods or somethin like that. How this problem can be solved?
I see this error if I try to use add method in my controller
Will add TicketuserRepository:
package com.example.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
//import org.springframework.boot.autoconfigure.data.web.SpringDataWebProperties.Pageable;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.model.TicketUser;
import com.example.model.Users;
import com.example.model.Events;
import com.example.model.Halls;
#Repository
public interface TicketsUserRepository extends CrudRepository<TicketUser, Integer> {
Page<Events> findByuserid(Integer userid, Pageable pageable);
Optional<Events> findByuseridAndId(Integer userid, Integer id);
Page<Events> findByticketid(Integer ticketid, Pageable pageable);
Optional<Events> findByticketidAndId(Integer ticketid, Integer id);
List<TicketUser> findByUserid(int id);
}
and the service
package com.example.service;
import java.util.List;
import com.example.model.TicketUser;
import com.example.model.Events;
import com.example.model.Halls;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.example.repository.TicketsUserRepository;
import com.example.repository.EventsRepository;
import com.example.repository.HallsRepository;
#Service
#Transactional
public class UsersticketServiceImplementation implements UsersticketService {
#Autowired
TicketsUserRepository ticketsuserRepository;
#Override
public List<TicketUser> getAllTickets() {
// TODO Auto-generated method stub
return (List<TicketUser>) ticketsuserRepository.findAll();
}
#Override
public TicketUser getTicketById(int id) {
// TODO Auto-generated method stub
return ticketsuserRepository.findById(id).get();
}
#Override
public void addTicket(TicketUser ticketuser) {
// TODO Auto-generated method stub
ticketsuserRepository.save(ticketuser);
}
#Override
public void deleteTicket(int id) {
// TODO Auto-generated method stub
ticketsuserRepository.deleteById(id);
}
#Override
public List<TicketUser> getTicketByUser(int id) {
// TODO Auto-generated method stub
return (List<TicketUser>) ticketsuserRepository.findByUserid(id);
}
}
This is my model userticket in angular:
import {Ticket} from "./ticket.model";
export class Userticket {
id?:any;
qty?:number;
paid?:number;
ticketid?:Ticket;
}
Will add my ticketuser comonent from angular
import { Component, OnInit } from '#angular/core';
import { EventService } from 'src/app/services/event.service';
import { Event } from 'src/app/models/event.model';
import {TicketService} from 'src/app/services/ticket.service';
import {Ticket} from "../../models/ticket.model";
import {Userticket} from "../../models/userticket.model";
import {UserticketService} from "../../services/userticket.service";
import {ActivatedRoute, Router} from "#angular/router";
#Component({
selector: 'app-userticket-buy',
templateUrl: './userticket-buy.component.html',
styleUrls: ['./userticket-buy.component.css']
})
export class UserticketBuyComponent implements OnInit {
currentTicket: Ticket = {
price: 0,
eventid:this.retrieveEvents()
};
eventid = this.currentTicket.eventid;
events?: Event[];
submitted = false;
currentUserTicket: Userticket = {
qty: 1,
paid:0,
};
//final current
//end
message = ''
constructor(
private eventService: EventService,
private ticketService:TicketService,
private userticketService:UserticketService,
private route: ActivatedRoute,
private router: Router) { }
ngOnInit(): void {
this.message = '';
this.getTicket(this.route.snapshot.params.id);
}
getTicket(id: string): void {
this.ticketService.get(id)
.subscribe(
data => {
this.currentTicket = data;
console.log(data);
},
error => {
console.log(error);
});
}
//save order
saveOrder(): void {
const data = {
qty: this.currentUserTicket.qty,
paid: this.currentUserTicket.paid,
ticketid: this.currentTicket.id
};
//console.log(data.eventid);
this.userticketService.create(data)
.subscribe(
response => {
console.log("city")
console.log(response);
this.submitted = true;
},
error => {
console.log(error);
});
}
//end
retrieveEvents(): any {
this.eventService.getAll()
.subscribe(
data => {
this.events = data;
console.log(data);
return data;
},
error => {
console.log(error);
return error;
});
}
calculatePrice($event:any){
let n1:number|undefined;
n1=this.currentTicket.price;
let n2:number|undefined;
n2=this.currentUserTicket.qty || 1;
let res:number|undefined;
res=n1 || 1 * n2 || 1;
console.log(this.currentUserTicket.qty);
// #ts-ignore: Object is possibly 'null'.
this.currentUserTicket.paid= this.currentUserTicket.qty*this.currentTicket.price
}
}
And the template:
<div>
<div *ngIf="currentTicket.id" class="edit-form">
<h4>Билет</h4>
<form>
<div class="form-group">
<label for="title">Количество</label>
<input type="number"
class="form-control"
id="title"
[(ngModel)]="currentUserTicket.qty"
name="qty"
(keyup)="calculatePrice($event)"
/>
<input
type="hidden"
class="form-control"
id="id"
[(ngModel)]="currentTicket"
name="ticketid"
/>
</div>
<div class="form-group">
<label for="title">Итого</label>
<input
type="number"
class="form-control"
id="paid"
[(ngModel)]="currentUserTicket.paid"
name="paid"
/>
</div>
<div class="form-group">
<p>Событие: {{currentTicket.eventid?.name}}</p>
<p>Зал: {{currentTicket.eventid?.hallid?.name}}</p>
<p>Город: {{currentTicket.eventid?.cityid?.name}}</p>
</div>
</form>
<button
type="submit"
class="badge badge-success mb-2"
(click)="saveOrder()"
>
Подтвердить
</button>
<p>{{ message }}</p>
</div>
<div *ngIf="!currentTicket.id">
<br />
<p>Нет доступа...</p>
</div>
</div>
Will add my working example from ticket model:
tickets.java
package com.example.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import java.util.Date;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#Entity
#Table(name = "tickets")
public class Tickets {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "price")
private Float price;
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "event_id", nullable = false)
#OnDelete(action = OnDeleteAction.CASCADE)
private Events eventid;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public Events getEventid() {
return eventid;
}
public void setEventid(Events eventid) {
this.eventid = eventid;
}
}
TicketsRepository:
package com.example.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
//import org.springframework.boot.autoconfigure.data.web.SpringDataWebProperties.Pageable;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.model.Tickets;
import com.example.model.Events;
import com.example.model.Halls;
#Repository
public interface TicketsRepository extends CrudRepository<Tickets, Integer>{
Page<Events> findByeventid(Integer eventid, Pageable pageable);
Optional<Events> findByeventidAndId(Integer eventid, Integer id);
}
TicketService:
package com.example.service;
import java.util.List;
import com.example.model.Tickets;
import com.example.model.Events;
import com.example.model.Halls;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.repository.EventsRepository;
import com.example.repository.HallsRepository;
import com.example.repository.TicketsRepository;
#Service
#Transactional
public class TicketsServiceImplementation implements TicketsService {
#Autowired
TicketsRepository ticketsRepository;
#Override
public List<Tickets> getAllTickets() {
// TODO Auto-generated method stub
return (List<Tickets>) ticketsRepository.findAll();
}
#Override
public Tickets getTicketById(int id) {
// TODO Auto-generated method stub
return ticketsRepository.findById(id).get();
}
#Override
public void addTicket(Tickets ticket) {
// TODO Auto-generated method stub
ticketsRepository.save(ticket);
}
#Override
public void deleteTicket(int id) {
// TODO Auto-generated method stub
ticketsRepository.deleteById(id);
}
}
And the controller:
package com.example.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ModelAttribute;
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.servlet.ModelAndView;
import com.example.model.Tickets;
import com.example.model.Events;
import com.example.model.Halls;
import com.example.service.TicketsService;
import com.example.service.EventsService;
import com.example.service.HallsService;
#Controller
#CrossOrigin(origins = "http://localhost:8889")
#RequestMapping(value="/ticket")
#SpringBootApplication
public class TicketsController {
#Autowired
TicketsService ticketsService;
#RequestMapping(value="/list", method=RequestMethod.GET)
public ResponseEntity list()
{
List<Tickets> ticketList=ticketsService.getAllTickets();
return new ResponseEntity<>(ticketList, HttpStatus.OK);
}
#RequestMapping(value="/add", method=RequestMethod.POST)
public ResponseEntity add(#RequestBody Tickets ticket)
{
ticketsService.addTicket(ticket);
return new ResponseEntity<>(ticket, HttpStatus.CREATED);
}
#RequestMapping(value="/delete/{id}", method=RequestMethod.GET)
public ResponseEntity delete(#PathVariable("id") int id)
{
ticketsService.deleteTicket(id);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
#RequestMapping(value="/getone/{id}", method=RequestMethod.GET)
public ResponseEntity getOne(#PathVariable("id") int id)
{
Tickets ticket= ticketsService.getTicketById(id);
return new ResponseEntity<>(ticket, HttpStatus.OK);
}
}
Basically this is the ticket table controller. It was basically made a same way as UserTicket. Why then I am getting this problem?
The error is that in the model you are using a full object of ticket and that is also marked as nullable = false so while saving the model in database you need to create an object of ticket using theticketId attribute in the request json or change the model’s attribute from type Tickets to int
You are already doing the same thing for user by setting user object.
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.
I wrote the following code and test cases has to be passed ... iam thrown java.lang.AssertionError: Status expected:<200> but was:<404> error please help out
controller this is the controller class
package com.example.project;
import com.example.project.HospitalService;
import com.example.project.Hospital;
import java.util.List;
import java.lang.*;
import org.springframework.http.ResponseEntity;
import java.util.*;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
//import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.DeleteMapping;
//import org.springframework.web.bind.annotation.PutMapping;
//import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#RestController
#RequestMapping("/test/")
public class HospitalController {
#Autowired
private HospitalService hospitalService;
#RequestMapping(value = "hospitals/{id}", method = RequestMethod.GET)
public #ResponseBody Hospital getHospital(#PathVariable("id") int id) throws Exception {
Hospital hospital = this.hospitalService.getHospital(id);
return hospital;
}
#RequestMapping(value = "hospitals/", method = RequestMethod.GET)
public #ResponseBody List<Hospital> getAllHospitals() throws Exception {
return this.hospitalService.getAllHospitals();
}
//#PostMapping("addHospital")
#RequestMapping(value = "hospitals/", method = RequestMethod.POST)
public ResponseEntity<String> addHospital(#RequestBody Hospital hospital ) {
return hospitalService.addHospital(hospital);
}
//#PutMapping("updateHospital")
#RequestMapping(value = "hospitals/", method = RequestMethod.PUT)
public ResponseEntity<String> updateHospital(#RequestBody Hospital hospital) {
return hospitalService.updateHospital(hospital);
}
//#DeleteMapping("deleteHospital")
#RequestMapping(value = "hospitals/", method = RequestMethod.DELETE)
public ResponseEntity<String> deleteHospital(#RequestBody Hospital hospital) {
return hospitalService.deleteHospital(hospital);
}
}
service : the below is the service class
package com.example.project;
import com.example.project.Hospital;
import org.springframework.http.ResponseEntity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.*;
import java.lang.*;
import java.util.List;
import com.example.project.HospitalRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
//import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatus;
#Service
public class HospitalService extends Exception{
#Autowired
private HospitalRepository hospitalRepository;
#Autowired
public HospitalService(HospitalRepository hospitalRepository){
this.hospitalRepository=hospitalRepository;
}
public List<Hospital> getAllHospitals(){
List<Hospital> x= (List)hospitalRepository.findAll();
return x;
}
public Hospital getHospital(int id){
Hospital x= hospitalRepository.findById(id);
return x;
}
public ResponseEntity<String> addHospital(Hospital hospital){
try{
Hospital h =hospitalRepository.save(hospital);
return new ResponseEntity<>(HttpStatus.OK);
}
catch(Exception e){
return new ResponseEntity<>(null,HttpStatus.INTERNAL_SERVER_ERROR);
}
}
public ResponseEntity<String> updateHospital(Hospital hospital){
try{
Hospital h = (hospitalRepository.save(hospital));
return new ResponseEntity<>(HttpStatus.OK);
}
catch(Exception e){
return new ResponseEntity<>(null,HttpStatus.INTERNAL_SERVER_ERROR);
}
}
public ResponseEntity<String> deleteHospital(Hospital hospital) {
try {
hospitalRepository.delete(hospital);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
catch(Exception e){
return new ResponseEntity<>(null,HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
Test cases the following is test class which needs to be passed for above given service and controller
package com.example.project;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.fasterxml.jackson.databind.ObjectMapper;
#SpringBootTest
#RunWith(SpringRunner.class)
public class HospitalControllerTest {
private MockMvc mockMvc;
#Autowired
WebApplicationContext context;
#Before
public void setup() {
//this.mockMvc = MockMvcBuilders.standaloneSetup(new WeatherApiController()).build();
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
#Test
public void retrievetestok() throws Exception {
addhospitalok();
mockMvc.perform(get("/test/hospitals/1000" )).andDo(print())
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1000))
.andExpect(MockMvcResultMatchers.jsonPath("$.name").value("Apollo Hospital"))
.andExpect(MockMvcResultMatchers.jsonPath("$.rating").value(3.8))
.andExpect(MockMvcResultMatchers.jsonPath("$.city").value("Chennai"));
}
#Test
public void addhospitalok() throws Exception {
Hospital hosp=new Hospital();
hosp.setId(1000);
hosp.setName("Apollo Hospital");
hosp.setCity("Chennai");
hosp.setRating(3.8);
byte[] hospJson = toJson(hosp);
Hospital hosp1=new Hospital();
hosp1.setId(1001);
hosp1.setName("Global Hospital");
hosp1.setCity("Bangalore");
hosp1.setRating(3.5);
byte[] hospJson1 = toJson(hosp1);
mockMvc.perform(post("/test/hospitals/" )//.andDo(print())
.content(hospJson)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
mockMvc.perform(post("/test/hospitals/" )//.andDo(print())
.content(hospJson1)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
#Test
public void updatehospitalok() throws Exception {
Hospital hosp1=new Hospital();
hosp1.setId(1001);
hosp1.setName("Global Hospitals");
hosp1.setCity("Goa");
hosp1.setRating(3.5);
byte[] hospJson1 = toJson(hosp1);
mockMvc.perform(post("/test/hospitals/" )//.andDo(print())
.content(hospJson1)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
mockMvc.perform(get("/test/hospitals/1001" )).andDo(print())
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.name").value("Global Hospitals"))
.andExpect(MockMvcResultMatchers.jsonPath("$.city").value("Goa"));
}
#Test
public void deleteHospitalok() throws Exception {
Hospital hosp=new Hospital();
hosp.setId(1000);
hosp.setName("Apollo Hospital");
hosp.setCity("Chennai");
hosp.setRating(3.8);
byte[] hospJson = toJson(hosp);
mockMvc.perform(delete("/test/hospitals/" )//.andDo(print())
.content(hospJson)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
}
private byte[] toJson(Object r) throws Exception {
ObjectMapper map = new ObjectMapper();
return map.writeValueAsString(r).getBytes();
}
}
ERROR THROWN this is the error which is thrown by the ide and it doesnt show any compilation or initialization error
-------------------------------------------------------------------------------
Test set: com.example.project.HospitalControllerTest
-------------------------------------------------------------------------------
Tests run: 4, Failures: 4, Errors: 0, Skipped: 0, Time elapsed: 10.718 sec <<< FAILURE! - in com.example.project.HospitalControllerTest
addhospitalok(com.example.project.HospitalControllerTest) Time elapsed: 0.257 sec <<< FAILURE!
java.lang.AssertionError: Status expected:<200> but was:<404>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81)
at org.springframework.test.web.servlet.result.StatusResultMatchers$10.match(StatusResultMatchers.java:665)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
at com.example.project.HospitalControllerTest.addhospitalok(HospitalControllerTest.java:75)
deleteHospitalok(com.example.project.HospitalControllerTest) Time elapsed: 0.02 sec <<< FAILURE!
java.lang.AssertionError: Status expected:<204> but was:<404>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81)
at org.springframework.test.web.servlet.result.StatusResultMatchers$10.match(StatusResultMatchers.java:665)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
at com.example.project.HospitalControllerTest.deleteHospitalok(HospitalControllerTest.java:116)
same is thrown for other tests as well but to keep short i am mentioning only 2 of them here
i am not understanding why am i getting this error and what could be reason for it.i tried removing unnecessary imports but yet it could not help me out. i have there is 404 error received instead of 200 and i am not able to understand what could be the reason
HospitalController.java
package com.example.project;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
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.PutMapping;
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;
#RestController
#RequestMapping("/test/")
public class HospitalController {
#Autowired
private HospitalService hospitalService;
#GetMapping("hospitals/{id}")
public #ResponseBody Hospital getHospital(#PathVariable("id") int id) throws Exception {
return hospitalService.getHospital(id);
}
#GetMapping("hospitals/")
public #ResponseBody List<Hospital> getAllHospitals() throws Exception {
return hospitalService.getAllHospitals();
}
#PostMapping("hospitals/")
public ResponseEntity<String> addHospital(#RequestBody Hospital hospital ) {
hospitalService.addHospital(hospital);
//URI location=ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(sevedUser.getId()).toUri();
return new ResponseEntity<>(HttpStatus.OK);
}
public ResponseEntity<String> updateHospital(#RequestBody Hospital hospital) {
hospitalService.updateHospital(hospital);
return ResponseEntity.ok("ok");
}
#DeleteMapping("hospitals/")
public ResponseEntity<String> deleteHospital(#RequestBody Hospital hospital) {
hospitalService.deleteHospital(hospital);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
HospitalService.java
package com.example.project;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class HospitalService {
#Autowired
private HospitalRepository hospitalRepository;
public List<Hospital> getAllHospitals(){
List<Hospital> hos = new ArrayList<Hospital>();
hospitalRepository.findAll().forEach(hos1 -> hos.add(hos1));
return hos;
}
public Hospital getHospital(int id){
return hospitalRepository.findOne(id);
}
public void addHospital(Hospital hospital){
hospitalRepository.save(hospital);
}
public void updateHospital(Hospital hos){
//if(hospitalRepository.findById(hos.getId()).isPresent())
// {
// Hospital hospital=hospitalRepository.findById(hos.getId()).get();
// hospital.setName(hos.getName());
// hospital.setCity(hos.getCity());
// hospital.setRating(hos.getRating());
hospitalRepository.save(hos);
// }
}
public void deleteHospital(Hospital hospital) {
hospitalRepository.delete(hospital);
}
}
Hospital.java
package com.example.demo.Hospital;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Hospital {
#Id
public int getId() {
return id;
}
public Hospital() {
super();
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public Hospital(int id, String name, String city, double rating) {
super();
this.id = id;
this.name = name;
this.city = city;
this.rating = rating;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
private int id;
private String name;
private String city;
private double rating;
}
HospitalRepository.java
package com.example.demo.Hospital;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface HospitalRepository extends JpaRepository<Hospital,Integer>{
}
application.properties
server.port=8080
spring.jpa.show-sql=true
spring.h2.console.enabled=true
spring.datasource.platform=h2
spring.datasource.url=jdbc:h2:mem:testdb
data.sql
insert into hospital values(1,'John','bihar',22);
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.