Spring Repository Bean Not Being Found - java

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.

Related

Error in fetching table through JpaRepository

I am trying to fetch data from a table in MySQL using JpaRepository.
I am geeting an error by running code like -
Error creating bean with name 'chassiscontroller': Unsatisfied dependency expressed through field 'service': Error creating bean with name 'chassisserviceimpl': Unsatisfied dependency expressed through field 'dao': Error creating bean with name 'chassisdao' defined in com.ChassisInfo.chassis.dao.chassisdao defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Not a managed type: class com.ChassisInfo.model.chassismodel.
Controller
package com.ChassisInfo.chassis.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ChassisInfo.chassis.model.ChassisModel;
import com.ChassisInfo.chassis.service.ChassisService;
#RestController
public class ChassisController {
#Autowired
private ChassisService service;
#GetMapping("/chnum")
public List<ChassisModel> getchassisnumberinfo(){
return service.getAll();
}
}
Service-
package com.ChassisInfo.chassis.service;
import java.util.List;
import com.ChassisInfo.chassis.model.ChassisModel;
public interface ChassisService{
List<ChassisModel> getAll();
}
ServiceImpl-
package com.ChassisInfo.chassis.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ChassisInfo.chassis.dao.ChassisDao;
import com.ChassisInfo.chassis.model.ChassisModel;
#Service
#lombok.AllArgsConstructor
#lombok.NoArgsConstructor
public class ChassisServiceimpl implements ChassisService {
#Autowired
private ChassisDao dao;
#Override
public List<ChassisModel> getAll() {
// TODO Auto-generated method stub
return dao.findAll();
}
Dao-
package com.ChassisInfo.chassis.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.stereotype.Repository;
import com.ChassisInfo.chassis.model.ChassisModel;
#Repository
#EnableJpaRepositories
public interface ChassisDao extends JpaRepository<ChassisModel,String> {
#Query(value = "Select * from chassis_master" ,nativeQuery = true)
List<ChassisModel> findAll();
}
Model-
package com.ChassisInfo.model;
public class chassismodel {
private String vin;
private String active;
private String chassisNumber;
private String chassisSeries;
private String statusChangedTime;
private String tag;
private String truckid;
private String id;
private String chassis_number;
private String chassis_series;
private String status_changed_time;
private String truck_id;
public String getVin() {
return vin;
}
public void setVin(String vin) {
this.vin = vin;
}
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
public String getChassisSeries() {
return chassisSeries;
}
public void setChassisSeries(String chassisSeries) {
this.chassisSeries = chassisSeries;
}
public String getStatusChangedTime() {
return statusChangedTime;
}
public void setStatusChangedTime(String statusChangedTime) {
this.statusChangedTime = statusChangedTime;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getTruckid() {
return truckid;
}
public void setTruckid(String truckid) {
this.truckid = truckid;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getChassis_number() {
return chassis_number;
}
public void setChassis_number(String chassis_number) {
this.chassis_number = chassis_number;
}
public String getChassis_series() {
return chassis_series;
}
public void setChassis_series(String chassis_series) {
this.chassis_series = chassis_series;
}
public String getStatus_changed_time() {
return status_changed_time;
}
public void setStatus_changed_time(String status_changed_time) {
this.status_changed_time = status_changed_time;
}
public String getTruck_id() {
return truck_id;
}
public void setTruck_id(String truck_id) {
this.truck_id = truck_id;
}
public String getChassisNumber() {
return chassisNumber;
}
public void setChassisNumber(String chassisNumber) {
this.chassisNumber = chassisNumber;
}
}
ChassisApplication-
package com.ChassisInfo.chassis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import com.ChassisInfo.chassis.controller.ChassisController;
#SpringBootApplication
#EnableJpaRepositories
public class ChassisApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(ChassisApplication.class, args);
ChassisController chassisController = context.getBean(ChassisController.class);
chassisController.getchassisnumberinfo();
}
}
Try to use #RequiredArgsConstructor (lombok) in chassisserviceimpl, since dao field is not accessible for autowiring. Also add final for the field:
private final chassisdao dao;
This is probably because you are missing the #EnableJpaRepositories(basePackages = "your.package.name") in you #SpringBootApplication
This is the Annotation to enable JPA repositories. Will scan the package of the annotated configuration class for Spring Data repositories by default.

How to create a JPA repository for Books, Clients, Orders

I am trying to create 3 JPA repositories with 3 according services, but I don't even know how to start. Id appreciate if any of u takes a loot at this.
The book DTO
package com.mile.pc.java8.book_api_jpa.DTO;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "books")
public class Book {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String name;
private String type;
private boolean available;
protected Book() {}
public Book(String name, String type, boolean available) {
super();
this.name = name;
this.type = type;
this.available = available;
}
public Long getID() {
return id;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public boolean isAvailable() {
return available;
}
#Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", type=" + type + ", available=" + available + "]";
}
}
the Order DTO:
package com.mile.pc.java8.book_api_jpa.DTO;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "orders")
public class Order {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String customerName;
protected Order() {}
public Order(Integer id, String customerName) {
super();
this.id = id;
this.customerName = customerName;
}
public int getId() {
return id;
}
public String getCustomerName() {
return customerName;
}
#Override
public String toString() {
return "Order [id=" + id + ", customerName=" + customerName + "]";
}
}
The client DTO:
package com.mile.pc.java8.book_api_jpa.DTO;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "clients")
public class Client {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private String clientEmail;
private String clientName;
protected Client() {}
public Client(String clientEmail, String clientName) {
super();
this.clientEmail = clientEmail;
this.clientName = clientName;
}
public String getClientEmail() {
return clientEmail;
}
public String getClientName() {
return clientName;
}
#Override
public String toString() {
return "Client [clientEmail=" + clientEmail + ", clientName=" + clientName + "]";
}
}
Book repo:
package com.mile.pc.java8.book_api_jpa.DTO.repo;
import java.util.ArrayList;
import java.util.List;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.mile.pc.java8.book_api_jpa.DTO.Book;
#EnableJpaRepositories
#Repository
public interface BookRepository extends CrudRepository<Book, Long> {
List<Book> books = new ArrayList<>();
}
Order repo:
package com.mile.pc.java8.book_api_jpa.DTO.repo;
import java.util.ArrayList;
import java.util.List;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.mile.pc.java8.book_api_jpa.DTO.Order;
#EnableJpaRepositories
#Repository
public interface OrderRepository extends CrudRepository<Order, Long> {
List<Order> orders = new ArrayList<Order>();
}
Client repo:
package com.mile.pc.java8.book_api_jpa.DTO.repo;
import java.util.HashMap;
import java.util.Map;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.mile.pc.java8.book_api_jpa.DTO.Client;
#EnableJpaRepositories
#Repository
public interface ClientRepository extends CrudRepository<Client, Long> {
Map<String, Client> clients = new HashMap<String, Client>();
}
Book Service:
package com.mile.pc.java8.book_api_jpa.DTO.repo.service;
import org.springframework.stereotype.Service;
#Service
public class BookService{
}
Order service:
package com.mile.pc.java8.book_api_jpa.DTO.repo.service;
import org.springframework.stereotype.Service;
#Service
public class OrderService {
}
Client Service:
package com.mile.pc.java8.book_api_jpa.DTO.repo.service;
import org.springframework.stereotype.Service;
#Service
public class ClientService {
}
I know It's a lot to ask. But I'd appreciate it a lot...Thank you :)

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.

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