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.
Related
І am developing a REST API app with Spring Boot. I have 2 tables in the database, the first is called TblEmployees, the second is called TblDepartments. From these 2 tables I made a class Employees_DTO which should return data in JSON format. And from the TblEmployees table it will return data and from the TblDepartments table it returns null. dbID is a foreign key I did as I thought but at me it doesn't work:
public class TblDepartments {
private Integer dbID;
private String dep_name;
public class TblEmployees {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int emp_id;
private String empName;
private Boolean empActive;
private Integer dbID;
public class Employees_DTO {
private int emp_id;
private String empName;
private Boolean empActive;
private String dep_name;
}
package com.example.test_task.exceptions;
import com.example.test_task.*;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import org.modelmapper.spi.MatchingStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
#Service
public class EmployessServise {
#Autowired
private EmplployeesRepository repo;
#Autowired
private ModelMapper modelMapper;
public EmployessServise() {
}
public List<Employees_DTO> getAll_Emp(){
return repo.findAll()
.stream()
.map(this::convertEntityToDto)
.collect(Collectors.toList());
}
private Employees_DTO convertEntityToDto(TblEmployees tblEmployees){
modelMapper.getConfiguration()
.setMatchingStrategy(MatchingStrategies.LOOSE);
Employees_DTO employees_dto=new Employees_DTO();
employees_dto=modelMapper.map(tblEmployees,Employees_DTO.class);
return employees_dto;
}
private TblEmployees convertEntityToDto(Employees_DTO employees_dto){
modelMapper.getConfiguration()
.setMatchingStrategy(MatchingStrategies.LOOSE);
TblEmployees tblEmployees=new TblEmployees();
tblEmployees=modelMapper.map(employees_dto,TblEmployees.class);
return tblEmployees;
}
}
#ManyToOne is available:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Entity
public class TblEmployees {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int emp_id;
private String empName;
private Boolean empActive;
#ManyToOne
#JoinColumn(name = "dbid")
private TblDepartments department;
// Getters and Setters
}
full sample code
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.
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.
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.
I am having some issues with trying to autowire a repository into the main class. I am getting the following error :-
***************************
APPLICATION FAILED TO START
***************************
Description:
Field userRepository in com.talkable_bm234.App required a bean of type 'com.talkable_bm234.repository.UserRepository' that could not be found.
Action:
Consider defining a bean of type 'com.talkable_bm234.repository.UserRepository' in your configuration.
Here are my files, I've been able to succeed with this before but struggling to set it up with Mongo:
App.java
package com.talkable_bm234;
import org.apache.log4j.Logger;
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.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories;
import com.talkable_bm234.domain.User;
import com.talkable_bm234.repository.UserRepository;
import reactor.core.publisher.Flux;
#SpringBootApplication
#EnableReactiveMongoRepositories({"com.talkable_bm234.repository"})
#ComponentScan(basePackages = {"com.talkable_bm234"})
public class App {
#Autowired
UserRepository userRepository;
final static Logger logger = Logger.getLogger(App.class.getName());
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
#Bean
public CommandLineRunner administrators(ApplicationContext ctx) {
return args -> {
// Add administrator account type on boot
logger.info("preparing to add admin accounts...");
final User administratorA = new User("John", "Doe", "adminA#admins.co.uk", "12345", "ADMIN");
final User administratorB = new User("Wendy", "Doe", "adminB#admins.co.uk", "12345", "ADMIN");
userRepository.saveAll(Flux.just(administratorA, administratorB)).subscribe();
};
}
}
UserRepository.java
package com.talkable_bm234.repository;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;
import com.talkable_bm234.domain.User;
import reactor.core.publisher.Mono;
/**
* Reactive Repository class for handling users
* #author Ben
*/
#Repository
public interface UserRepository extends ReactiveMongoRepository<User, String> {
//Find by Email Address
Mono<User> findByEmailAddress(String emailAddress);
}
MongoConfig.java
package com.talkable_bm234.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.mongodb.config.AbstractReactiveMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories;
import com.mongodb.async.client.MongoClient;
import com.mongodb.async.client.MongoClients;
/**
* Reactive MongoDB Configuration for Cloud Database
* #author Ben
*
*/
#Configuration
#EnableReactiveMongoRepositories
#PropertySource("classpath:application.properties")
public abstract class MongoConfig extends AbstractReactiveMongoConfiguration {
//Values taken from 'application.properties'
//------------------------------------------
#Value("${spring.data.mongodb.username}")
private String userName;
#Value("${spring.data.mongodb.password}")
private String password;
#Value("${spring.data.mongodb.database}")
private String database;
#Value("${spring.data.mongodb.host}")
private String host;
#Value("${spring.data.mongodb.port}")
private Integer port;
//----------------------------------------
#Override
protected String getDatabaseName() {
return database;
}
#Bean
#DependsOn("embeddedMongoServer")
public MongoClient mongoClient() {
return (MongoClient) MongoClients.create(String.format("mongodb://%s:%d", host, port));
}
protected String getMappingBasePackage() {
return "com.talkable_bm234.domain";
}
}
User.java - Lombok Getters & Setters
package com.talkable_bm234.domain;
import javax.persistence.Id;
import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
/**
* Domain Class for a registered User.
* User Types: "USER", "PRESENTER", "ADMIN"
* #author Ben
* MongoDB & Lombok Annotations
*/
//Name of collection, user objects are mapped to! ->
#Document(collection="users")
public class User {
#Id
#Getter #Setter
private long ObjID;
#Getter #Setter #NonNull
private String firstName;
#Getter #Setter #NonNull
private String lastName;
#Getter #Setter #NonNull
#Indexed(name="emailAddress", unique=true)
private String emailAddress;
#Getter #Setter #NonNull
private String password;
#Getter #Setter #NonNull
private String type;
#PersistenceConstructor
public User(String firstName, String lastName,
String emailAddress, String password, String type) {
this.firstName = firstName;
this.lastName = lastName;
this.emailAddress = emailAddress;
this.password = password;
this.type = type;
}
public User() {}
}
Any ideas ?
Regards,
Ben