SpringBootApplication not scanning components - java

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.

Related

Error in creating bean userController caused by Could not create query for public abstract java.util.optional

Stack trace:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController':
Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'userRepository' defined in br.com.allen.flashfood.domain.repository.UserRepository defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed;
nested exception is org.springframework.data.repository.query.QueryCreationException:
Could not create query for public abstract java.util.Optional br.com.allen.flashfood.domain.repository.CustomJpaRepository.findFirst()!
Reason: Failed to create query for method public abstract java.util.Optional br.com.allen.flashfood.domain.repository.CustomJpaRepository.findFirst()!
No property findFirst found for type User!; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.Optional
br.com.allen.flashfood.domain.repository.CustomJpaRepository.findFirst()!
No property findFirst found for type User!
Classes:
Controller:
package br.com.allen.flashfood.api.controller;
import br.com.allen.flashfood.api.assembler.UserModelAssembler;
import br.com.allen.flashfood.api.assembler.UserRequestDisassembler;
import br.com.allen.flashfood.api.model.request.PasswordRequest;
import br.com.allen.flashfood.api.model.request.UserPasswordRequest;
import br.com.allen.flashfood.api.model.request.UserRequest;
import br.com.allen.flashfood.api.model.response.UserResponse;
import br.com.allen.flashfood.domain.model.User;
import br.com.allen.flashfood.domain.repository.UserRepository;
import br.com.allen.flashfood.domain.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
#RestController
#RequestMapping("/users")
public class UserController {
#Autowired
private UserRepository userRepository;
#Autowired
private UserService userService;
#Autowired
private UserModelAssembler userModelAssembler;
#Autowired
private UserRequestDisassembler userRequestDisassembler;
#GetMapping
public List<UserResponse> getAllUsers() {
List<User> allUsers = userRepository.findAll();
return userModelAssembler.toCollectionModel(allUsers);
}
#GetMapping("/{userId}")
public UserResponse getUserById(#PathVariable Long userId) {
User user = userService.findUserOrElseThrow(userId);
return userModelAssembler.toModel(user);
}
#PostMapping
#ResponseStatus(HttpStatus.CREATED)
public UserResponse addUser(#RequestBody #Valid UserPasswordRequest userPasswordRequest) {
User user = userRequestDisassembler.toDomainObject(userPasswordRequest);
user = userService.saveUser(user);
return userModelAssembler.toModel(user);
}
#PutMapping("/{userId}")
public UserResponse updateUser(#PathVariable Long userId,
#RequestBody #Valid UserRequest userRequest) {
User actualUser = userService.findUserOrElseThrow(userId);
userRequestDisassembler.copyToDomainObject(userRequest, actualUser);
actualUser = userService.saveUser(actualUser);
return userModelAssembler.toModel(actualUser);
}
#PutMapping("/{userId}/password")
#ResponseStatus(HttpStatus.NO_CONTENT)
public void userPassword(#PathVariable Long userId,
#RequestBody #Valid PasswordRequest passwordRequest) {
userService.changePassword(userId, passwordRequest.getActualPassword(), passwordRequest.getNewPassword());
}
}
Repository:
package br.com.allen.flashfood.domain.repository;
import br.com.allen.flashfood.domain.model.User;
import org.springframework.stereotype.Repository;
#Repository
public interface UserRepository extends CustomJpaRepository<User, Long> {
}
CustomJpaRepository
package br.com.allen.flashfood.domain.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;
import java.util.Optional;
#NoRepositoryBean
public interface CustomJpaRepository<T, ID> extends JpaRepository<T, ID> {
Optional<T> findFirst();
}
User:
package br.com.allen.flashfood.domain.model;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.hibernate.annotations.CreationTimestamp;
import javax.persistence.*;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.List;
#Entity
#Data
#EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#EqualsAndHashCode.Include
private Long id;
#Column(nullable = false)
private String name;
#Column(nullable = false)
private String email;
#Column(nullable = false)
private String password;
#CreationTimestamp
#Column(nullable = false, columnDefinition = "datetime")
private OffsetDateTime registrationDate;
#ManyToMany
#JoinTable(name = "user_group",
joinColumns = #JoinColumn(name = "user_id"),
inverseJoinColumns = #JoinColumn(name = "group_id"))
private List<Family> groups = new ArrayList<>();
public boolean passwordConfirmed(String password) {
return getPassword().equals(password);
}
public boolean passwordNotConfirmed(String password) {
return !passwordConfirmed(password);
}
}
Edit 1:
I had forgotten to put the implementation in question because I thought it couldn't be that by editing the question now.
package br.com.allen.flashfood.infrastructure.repository;
import br.com.allen.flashfood.domain.repository.CustomJpaRepository;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import javax.persistence.EntityManager;
import java.util.Optional;
public class CustomJpaRepositoryImpl<T, ID> extends SimpleJpaRepository<T, ID> implements CustomJpaRepository<T, ID> {
private EntityManager entityManager;
public CustomJpaRepositoryImpl(JpaEntityInformation<T, ?> entityInformation,
EntityManager entityManager) {
super(entityInformation, entityManager);
this.entityManager = entityManager;
}
#Override
public Optional<T> findFirst() {
var jpql = "from " + getDomainClass().getName();
T entity = entityManager.createQuery(jpql, getDomainClass())
.setMaxResults(1)
.getSingleResult();
return Optional.ofNullable(entity);
}
}
The method findFirst() does not exist by itself. You need to add more expressions to this, such as findFirstByName(String name). In other words, you won't be able to create a superclass with a findFirst method that can be properly inherited. I don't really see a case here where I would create yet another interface to extend, you'll probably be better off just extending JpaRepository from your UserRepository.

json object returns null spring boot

І 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

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.

Application problem with cycle form beans

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.

Repository not autowiring with MongoDB and spring

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

Categories

Resources