Application problem with cycle form beans - java

My application won't start with the message :
The dependencies of some of the beans in the application context form a cycle:
bookController
↓
bookServiceImpl
┌─────┐
bookCommandToBook
↑ ↓
authorCommandToAuthor
└─────┘
BookController
package pl.springwebapp.webapp.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import pl.springwebapp.webapp.command.BookCommand;
import pl.springwebapp.webapp.service.BookService;
#Slf4j
#Controller
public class BookController {
private BookService bookService;
public BookController(BookService bookService) {
this.bookService = bookService;
}
#RequestMapping("/book/show/{id}")
public String showDescriptionById(#PathVariable long id, Model model){
model.addAttribute("book",bookService.findByID(id));
return "/book/show";
}
#RequestMapping("book/new")
public String newBook(Model model){
model.addAttribute("book", new BookCommand());
return "book/bookform";
}
#PostMapping
#RequestMapping(name = "book")
public String saveOrUpdate(#ModelAttribute BookCommand bookCommand){
bookService.saveBookCommand(bookCommand);
return "redirect:/index";
}
}
BookServiceImpl
package pl.springwebapp.webapp.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import pl.springwebapp.webapp.command.BookCommand;
import pl.springwebapp.webapp.converter.BookCommandToBook;
import pl.springwebapp.webapp.converter.BookToBookCommand;
import pl.springwebapp.webapp.model.Book;
import pl.springwebapp.webapp.repository.BookRepository;
import javax.transaction.Transactional;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
#Slf4j
#Service
public class BookServiceImpl implements BookService {
private BookRepository bookRepository;
private BookCommandToBook bookCommandToBook;
private BookToBookCommand bookToBookCommand;
public BookServiceImpl(BookRepository bookRepository, BookCommandToBook bookCommandToBook, BookToBookCommand bookToBookCommand) {
this.bookRepository = bookRepository;
this.bookCommandToBook = bookCommandToBook;
this.bookToBookCommand = bookToBookCommand;
}
#Override
public Set<Book> getBooks(){
Set<Book> bookSet = new HashSet<>();
bookRepository.findAll().iterator().forEachRemaining(bookSet::add);
return bookSet;
}
#Override
public Book findByID(long id) {
Optional<Book> optionalBook = bookRepository.findById((id));
if(!optionalBook.isPresent()){
throw new RuntimeException("Book not found");
}
return optionalBook.get();
}
#Transactional
#Override
public BookCommand saveBookCommand(BookCommand bookCommand) {
Book receivedBook = bookCommandToBook.convert(bookCommand);
Book savedBook = bookRepository.save(receivedBook);
return bookToBookCommand.convert(savedBook);
}
}
BookCommandToBook
package pl.springwebapp.webapp.converter;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import pl.springwebapp.webapp.command.BookCommand;
import pl.springwebapp.webapp.model.Book;
#Component
public class BookCommandToBook implements Converter<BookCommand, Book> {
private AuthorCommandToAuthor authorConverter;
private CategoryCommandToCategory categoryConverter;
public BookCommandToBook(AuthorCommandToAuthor authorConverter, CategoryCommandToCategory categoryConverter) {
this.authorConverter = authorConverter;
this.categoryConverter = categoryConverter;
}
#Override
public Book convert(BookCommand bookCommand) {
Book book = new Book();
book.setId(bookCommand.getId());
book.setTitle(bookCommand.getTitle());
book.setIsbn(bookCommand.getIsbn());
book.setDescription(bookCommand.getDescription());
book.setAuthor(authorConverter.convert(bookCommand.getAuthor()));
if(bookCommand.getCategorySet() != null && bookCommand.getCategorySet().size() > 0 ){
bookCommand.getCategorySet().forEach(categoryCommand -> book.getCategories().add(categoryConverter.convert(categoryCommand)));
}
return book;
}
}
AuthorCommandToAuthor
package pl.springwebapp.webapp.converter;
import lombok.Synchronized;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import pl.springwebapp.webapp.command.AuthorCommand;
import pl.springwebapp.webapp.model.Author;
#Component
public class AuthorCommandToAuthor implements Converter<AuthorCommand, Author> {
private BookCommandToBook bookConverter;
public AuthorCommandToAuthor(BookCommandToBook bookConverter) {
this.bookConverter = bookConverter;
}
#Synchronized
#Override
public Author convert(AuthorCommand authorCommand) {
if(authorCommand==null){
return null;
}
Author author = new Author();
author.setId(authorCommand.getId());
author.setName(authorCommand.getName());
author.setLastName(authorCommand.getLastName());
if(authorCommand.getBookCommandSet() != null && authorCommand.getBookCommandSet().size() > 0){
authorCommand.getBookCommandSet()
.forEach(bookCommand -> author.getBooks().add(bookConverter.convert(bookCommand)));
}
return author;
}
}
AuthorCommand
#Setter
#Getter
#NoArgsConstructor
public class AuthorCommand {
private long id;
private String name;
private String lastName;
private Set<BookCommand> bookCommandSet = new HashSet<>();
}
BookCommand
#Setter
#Getter
#NoArgsConstructor
public class BookCommand {
private long id;
private String title;
private String isbn;
private String description;
private Set<CategoryCommand> categorySet = new HashSet<>();
private AuthorCommand author;
}
Can you help me solve this problem?

You have a cycle in your application context. That means that one bean depends on another and vice versa. Spring will be unable to create those beans, since one bean always has to be created first. More specifically, AuthorCommandToAuthor requires BookCommandToBook and BookCommandToBook requires AuthorCommandToAuthor.
To solve your problem, refactor shared code to a thrid component and inject it into both dependencies. This will eliminate the cycle.

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.

SpringBootApplication not scanning components

I read many people asked the same question but I have followed all the rules, and I don't know what am I missing
I have following:
Main
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Model
package com.example.demo.model;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
#Entity
#Table(name = "ivsd_account")
public class Account implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "acc_id")
private Long accId;
#Column(name = "acc_uid", unique = true, nullable = false)
private String accUid;
#Column(name = "acc_created_by_acc_uid")
private String accCreatedByAccUid;
#CreationTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "acc_created_date")
private Date accCreatedDate;
#Column(name = "acc_updated_by_acc_uid")
private String accUpdatedByAccUid;
#UpdateTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "acc_updated_date")
private Date accUpdatedDate;
#UpdateTimestamp
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "acc_sync_tst")
private Date accSyncTst;
#Column(name = "acc_enabled")
private Boolean accEnabled;
#Column(name = "acc_name")
private String accName;
#Column(name = "acc_email")
private String accEmail;
#Column(name = "acc_username")
private String accUsername;
#Column(name = "acc_password")
private String accPassword;
getters and setters
DTO
package com.example.demo.dto;
import com.example.demo.model.Account;
import java.util.Date;
public class AccountDTO {
private Long accId;
private String accUid;
private String accCreatedByAccUid;
private Date accCreatedDate;
private String accUpdatedByAccUid;
private Date accUpdatedDate;
private Date accSyncTst;
private Boolean accEnabled;
private String accName;
private String accEmail;
private String accUsername;
private String accPassword;
getters and setters
Repository
package com.example.demo.repository;
import com.example.demo.model.Account;
import org.springframework.stereotype.Repository;
#Repository
public interface AccountRepository extends CustomRepository<Account, Long> {
Account findOneByAccName(String name);
Account findByAccUid(String uid);
Account findByAccEmail(String email);
void deleteAccountByAccUid(String uid);
}
Service
package com.example.demo.service;
import com.example.demo.dto.AccountDTO;
import com.example.demo.mapper.AccountMapper;
import com.example.demo.model.Account;
import com.example.demo.repository.AccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
#Service
public class AccountService {
#Autowired
private AccountRepository accountRepository;
#Autowired
private AccountMapper accountMapper; // Could not autowire. No beans of AccountMapper type found
#Transactional(readOnly = true)
public List<AccountDTO> loadAll() {
List<Account> res = accountRepository.findAll();
List<AccountDTO> resF = accountMapper.entitiesToDto(res);
return resF;
}
Controller
package com.example.demo.controller;
import com.example.demo.service.AccountService;
import com.example.demo.dto.AccountDTO;
import com.example.demo.system.ResponseWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
#RequestMapping("/api")
public class AccountController {
#Autowired
private AccountService accountService;
#RequestMapping(value = "/accounts", method = RequestMethod.GET)
public ResponseEntity<?> loadAll() {
List<AccountDTO> res = accountService.loadAll();
return new ResponseEntity(new ResponseWrapper(res), HttpStatus.OK);
}
Mapper
package com.example.demo.mapper;
import com.example.demo.dto.AccountDTO;
import com.example.demo.model.Account;
import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;
import org.mapstruct.ReportingPolicy;
import java.util.List;
#Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE, componentModel = "spring")
public interface AccountMapper {
AccountDTO entityToDto(Account entity);
Account dtoToEntity(AccountDTO entity);
Account updateEntityFromDto(AccountDTO dto, #MappingTarget Account entity);
List<AccountDTO> entitiesToDto(List<Account> entities);
}
I get an error in Service:
Field accountMapper in com.example.demo.service.AccountService required a bean of type 'com.example.demo.mapper.AccountMapper' that could not be found.
I have placed all the classes in sub packages of the package from Main class.
If I add annotation #ComponentScan("com.example.demo.mapper") then it works only for mapper package, other packages are not scanned. Sorry for stupid question. Any help I appreciate
Thank you
Check if you have properly configured mapstruct.
Run a mvn clean install before starting the application, mapstruct will generate the mapper class that will be annotated with #Component.

Not working lombok #NoArgsConstructor on a class?

Class where I create the empty constructor com lombok:
Notes.java:
package com.udacity.jwdnd.course1.cloudstorage.modelo;
import lombok.*;
import java.io.Serializable;
#Getter
#Setter
#NoArgsConstructor(access = AccessLevel.PUBLIC)
#AllArgsConstructor
public class Notes implements Serializable {
private Integer noteId;
private String noteTitle;
private String noteDescription;
private Integer userId;
public Notes(Integer noteId, String noteTitle
, String noteDescription, Integer userId) {
this.noteId = noteId;
this.noteTitle = noteTitle;
this.noteDescription = noteDescription;
this.userId = userId;
}
}
I use an object of Class Notes.java. In the following file an instance was created applying the empty constructor, but it throws me the error in the image:
import com.udacity.jwdnd.course1.cloudstorage.modelo.Notes;
import com.udacity.jwdnd.course1.cloudstorage.services.NoteService;
import com.udacity.jwdnd.course1.cloudstorage.services.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
#Controller
#RequestMapping("/home")
public class InicioController {
#Autowired
private UsersService usuarioService;
#Autowired
private NoteService notaService;
#Autowired
private CredentialService credencialService;
#Autowired
private ArchivoService archivoService;
#GetMapping()
public String irPaginaHome(Authentication auth, Model model){
model.addAttribute("noteForm", new Notes());
Integer idUsuario = usuarioService.obtenerIdusuario(auth.getName());
List<Notes> notas = notaService.notas(idUsuario);
model.addAttribute("notas",notas);
return "home";
}
}
model.addAttribute("noteForm", new Notes());
Can't find empty constructor, what would be the problem.

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.

inferred type 'S' for type parameter 'S' is not within its bound;

I got this error in Userservice.java file
'inferred type 'S' for type parameter 'S' is not within its bound;'
I don't know what is talking about and where I should change..
please check my file and give me some advice
enter image description here
package com.therealdanvega.service;
import com.therealdanvega.domain.User;
import com.therealdanvega.repository.UserRepository;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class UserService {
private UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public Iterable<User> list() {
return userRepository.findAll();
}
public User save(User user) {
return userRepository.save(user);
}
public void save(List<User> users) {
userRepository.save(users);
}
}
User
package com.therealdanvega.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import javax.persistence.*;
#Data
#AllArgsConstructor
#Entity
public class User {
#Id
#GeneratedValue( strategy = GenerationType.AUTO )
private Long id;
private String name;
private String username;
private String email;
private String phone;
private String website;
#Embedded
private Address address;
#Embedded
private Company company;
public User() {}
}
UserController
package com.therealdanvega.controller;
import com.therealdanvega.domain.User;
import com.therealdanvega.service.UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping("/users")
public class UserController {
private UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
#GetMapping("/list")
public Iterable < User > list() {
return userService.list();
}
}
JsondbApplication
package com.therealdanvega;
import com.fasterxml.jackson.core.type.TypeReference;
import com.therealdanvega.domain.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.therealdanvega.service.UserService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
#SpringBootApplication
public class JsondbApplication {
public static void main(String[] args) {
SpringApplication.run(JsondbApplication.class, args);
}
#Bean
CommandLineRunner runner(UserService userService){
return args -> {
// read JSON and load json
ObjectMapper mapper = new ObjectMapper();
TypeReference<List<User>> typeReference = new TypeReference<List<User>>(){};
InputStream inputStream = TypeReference.class.getResourceAsStream("/json/users.json");
try {
List<User> users = mapper.readValue(inputStream,typeReference);
userService.save(users);
System.out.println("Users Saved!");
} catch (IOException e){
System.out.println("Unable to save users: " + e.getMessage());
}
};
}
}
UserRepository
package com.therealdanvega.repository;
import com.therealdanvega.domain.User;
import org.springframework.data.repository.CrudRepository;
public interface UserRepository extends CrudRepository<User,Long> {
}
In class UserService in save(List users) method userRepository.save(users) throw error Inferred type 'S' for type parameter 'S' is not within its bound; should extend 'com.therealdanvega.domain.User'
I faced similar issue and by using repository.saveAll() method, it resolved.

Categories

Resources