I have problem with my Spring project. I just started with Spring Boot and i try to make ez controller which redirect me to another web.
When i started my application and go to browser on
localhost:8080/person
there is problem with mapping idk why
enter image description here
This is my structure
enter image description here
PersonController
package Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import Model.Person;
public class PersonController {
#RequestMapping("/person")
public String person(Model model)
{
Person p = new Person();
p.setFirstName("John");
p.setLastName("BonJovi");
p.setAge(23);
model.addAttribute("person", p);
return "personview";
}
}
Person Class
package Model;
public class Person {
String firstName;
String lastName;
int age;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
And "Main"
package demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
#Configuration
#EnableAutoConfiguration
#ComponentScan({"demo","controller"})
public class EducationProjectApplication {
public static void main(String[] args) {
SpringApplication.run(EducationProjectApplication.class, args);
}
}
Add a #Controller to the top of your PersonController
Also - just check, your #ComponentScan({"demo","controller"})
"controller" is not capitalized, but your package is declared "Controller"
You must annotated your PersonController class as #RestController.
Like Rafael said you need to put annotations above PersonController class. #RestController if you want to build a REST controller, #Controller if you want to build normal website. Make sure you already configure your view resolver so it will return a jsp files.
Related
I've built a spring boot rest api. However, when I try to test it in Postman, I am getting a 404 error. I have linked the code below. Please note that there might be a random #component annotation in some files. This was my tired brain trying anything it can.
Student.java
package StudentModel;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name = "Student")
public class Student {
public enum status {
PAID,
UNPAID,
PARTIAL
}
#Column
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long Id;
#Column(nullable = false)
private String FirstName;
#Column(nullable = false)
private String LastName;
#Column(nullable = false)
private long Phone;
#Column(nullable = false)
private String Email;
#Column(nullable = false)
private status PaymentStatus;
public long getId() {
return Id;
}
public void setId(long id) {
Id = id;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String firstName) {
FirstName = firstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public long getPhone() {
return Phone;
}
public void setPhone(long phone) {
Phone = phone;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public status getPaymentStatus() {
return PaymentStatus;
}
public void setPaymentStatus(status paymentStatus) {
PaymentStatus = paymentStatus;
}
}
StudentController.java
package StudentController;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import StudentModel.Student;
import StudentService.StudentService;
#Component
#RestController
#RequestMapping("/api/v1")
public class StudentController {
#Autowired
private StudentService studentService;
#PostMapping("/api/v1/addStudent")
public Student addStudent(#RequestBody Student student) {
return studentService.saveStudent(student);
}
#PostMapping("/api/v1/addStudents")
public List<Student> addStudents(#RequestBody List<Student> students) {
return studentService.saveStudents(students);
}
#GetMapping("/api/v1/students")
public List<Student> findAllStudents(){
return studentService.getStudents();
}
#GetMapping("/api/v1/students/{id}")
public Student findStudentById(#PathVariable long id) {
return studentService.getStudentById(id);
}
#GetMapping("/api/v1/students/{name}")
public Student findStudentByFirstName(#PathVariable String FirstName) {
return studentService.getStudentByFirstName(FirstName);
}
#PutMapping("/api/v1/update")
public Student updateStudent(#RequestBody Student student) {
return studentService.updateStudent(student);
}
#DeleteMapping("/api/v1/delete/{id}")
public String deleteStudent(#PathVariable long id) {
return studentService.deleteStudent(id);
}
}
StudentService.java
package StudentService;
import java.util.List;
import java.util.Optional;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import StudentModel.Student;
import StudentRepository.StudentRepository;
#Component
#Service
#Transactional
public class StudentService {
#Autowired
private StudentRepository studentRepository;
public Student saveStudent(Student student) {
return studentRepository.save(student);
}
public List<Student> saveStudents(List<Student> students) {
return studentRepository.saveAll(students);
}
public List<Student> getStudents() {
return studentRepository.findAll();
}
public Student getStudentById(long id){
return studentRepository.getById(id);
}
public Student getStudentByFirstName(String FirstName){
return studentRepository.findByFirstName(FirstName);
}
public Student getStudentByLastName(String LastName){
return studentRepository.findByLastName(LastName);
}
public Student getStudentByEmail(String Email){
return studentRepository.findByEmail(Email);
}
public Student getStudentByPhone(long Phone){
return studentRepository.findByPhone(Phone);
}
public String deleteStudent(long id) {
studentRepository.deleteById(id);
return "Student Deleted";
}
public Student updateStudent (Student student) {
Student existingStudent = studentRepository.getById(student.getId());
existingStudent.setFirstName(student.getFirstName());
existingStudent.setLastName(student.getLastName());
existingStudent.setEmail(student.getEmail());
existingStudent.setPhone(student.getPhone());
existingStudent.setPaymentStatus(student.getPaymentStatus());
return studentRepository.save(existingStudent);
}
}
StudentRepository.java
package StudentRepository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
import StudentModel.Student;
#Component
public interface StudentRepository extends JpaRepository <Student, Long>{
// Student saveStudent (Student student);
Student findByFirstName(String FirstName);
Student findByLastName(String LastName);
Student findByEmail(String Email);
Student findByPhone(long Phone);
// Student findById(long id);
}
StudentApplication.java
package com.BusyQA;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
#SpringBootApplication
#ComponentScan
public class BusyQaApplication extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(BusyQaApplication.class, args);
}
}
Any help would be greatly appreciated. Thank you.
To make it work, you need some improvements:
For Controller (REST API requests):
remove #Component annotation;
remove /api/v1/ from request mappings;
add DTO to only transfer the required information;
fix the name of the variables, following the convention.
import java.util.ArrayList;
import java.util.List;
import com.example.demo.dto.StudentDTO;
import com.example.demo.entity.Student;
import com.example.demo.service.StudentService;
import org.springframework.web.bind.annotation.*;
#RestController
#RequestMapping("/api/v1")
public class StudentController {
private final StudentService studentService;
public StudentController(StudentService studentService) {
this.studentService = studentService;
}
#PostMapping("/addStudent")
public Student addStudent(#RequestBody StudentDTO studentDTO) {
Student student = new Student(studentDTO);
return studentService.saveStudent(student);
}
#PostMapping("/addStudents")
public List<Student> addStudents(#RequestBody List<Student> students) {
return studentService.saveStudents(students);
}
#GetMapping("/students")
public List<StudentDTO> findAllStudents() {
List<StudentDTO> studentDTOList = new ArrayList<>();
List<Student> studentList = studentService.getStudents();
for (Student student : studentList) {
StudentDTO studentDTO = new StudentDTO(student);
studentDTOList.add(studentDTO);
}
return studentDTOList;
}
#GetMapping("/students/id/{id}")
public Student findStudentById(#PathVariable long id) {
return studentService.getStudentById(id);
}
#GetMapping("/students/firstName/{firstName}")
public Student findStudentByFirstName(#PathVariable String firstName) {
return studentService.getStudentByFirstName(firstName);
}
#PutMapping("/update")
public Student updateStudent(#RequestBody StudentDTO studentDTO) {
Student student = new Student(studentDTO);
return studentService.updateStudent(student);
}
#DeleteMapping("/delete/{id}")
public String deleteStudent(#PathVariable long id) {
return studentService.deleteStudent(id);
}
}
For Service class (Business logic):
remove #Component annotation;
remove #Transactional annotation;
use findById() to retrieve an entity by its Id;
import java.util.List;
import java.util.Optional;
import com.example.demo.entity.Student;
import com.example.demo.repository.StudentRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityNotFoundException;
#Service
public class StudentService {
private final StudentRepository studentRepository;
public StudentService(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}
public Student saveStudent(Student student) {
return studentRepository.save(student);
}
public List<Student> saveStudents(List<Student> students) {
return studentRepository.saveAll(students);
}
public List<Student> getStudents() {
return studentRepository.findAll();
}
public Student getStudentById(long id) {
return studentRepository.findById(id).orElseThrow(EntityNotFoundException::new);
}
public Student getStudentByFirstName(String firstName) {
return studentRepository.findByFirstName(firstName);
}
public Student getStudentByLastName(String lastName) {
return studentRepository.findByLastName(lastName);
}
public Student getStudentByEmail(String email) {
return studentRepository.findByEmail(email);
}
public Student getStudentByPhone(long phone) {
return studentRepository.findByPhone(phone);
}
public String deleteStudent(long id) {
studentRepository.deleteById(id);
return "Student Deleted";
}
public Student updateStudent(Student student) {
Student existingStudent = studentRepository.getById(student.getId());
existingStudent.setFirstName(student.getFirstName());
existingStudent.setLastName(student.getLastName());
existingStudent.setEmail(student.getEmail());
existingStudent.setPhone(student.getPhone());
existingStudent.setPaymentStatus(student.getPaymentStatus());
return studentRepository.save(existingStudent);
}
}
The Model class:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import com.example.demo.dto.StudentDTO;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Builder;
#Data
#Builder
#AllArgsConstructor
#NoArgsConstructor
#Entity
public class Student {
public Student(StudentDTO studentDTO) {
this.id = studentDTO.getId();
this.firstName = studentDTO.getFirstName();
this.lastName = studentDTO.getLastName();
this.phone = studentDTO.getPhone();
this.email = studentDTO.getEmail();
this.paymentStatus = studentDTO.getPaymentStatus();
}
public enum Status {
PAID,
UNPAID,
PARTIAL
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column
private long id;
private String firstName;
private String lastName;
private long phone;
private String email;
private Status paymentStatus;
}
DTO class:
import com.example.demo.entity.Student;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL;
#Builder
#Data
#NoArgsConstructor
#AllArgsConstructor
#JsonInclude(NON_NULL)
public class StudentDTO implements Serializable {
public StudentDTO(Student student) {
this.id = student.getId();
this.firstName = student.getFirstName();
this.lastName = student.getLastName();
this.phone = student.getPhone();
this.email = student.getEmail();
this.paymentStatus = student.getPaymentStatus();
}
private long id;
private String firstName;
private String lastName;
private long phone;
private String email;
private Student.Status paymentStatus;
}
The Repository class:
import com.example.demo.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
Student findByFirstName(String firstName);
Student findByLastName(String lastName);
Student findByEmail(String email);
Student findByPhone(long phone);
}
and the main class of a Spring Boot application:
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);
}
}
To test it, you can use endpoints by the same principle:
POST: localhost:8080/api/v1/addStudent
POST: localhost:8080/api/v1/addStudents
GET: localhost:8080/api/v1/students
GET: localhost:8080/api/v1/students/id/1
GET: localhost:8080/api/v1/students/firstName/testName
PUT: localhost:8080/api/v1/update
DELETE: localhost:8080/api/v1/delete/1
As Dilermando mentioned in the comments, your #RequestMapping("/api/v1") is setting its mapping, then you're extending onto that with #PostMapping("/api/v1/addStudent") making the address {url}/api/v1/api/v1/addStudent. You can resolve this by removing the /api/v1 from the Post/get mappings:
#RequestMapping("/api/v1")
public class StudentController {
#Autowired
private StudentService studentService;
#PostMapping("/addStudent")
public Student addStudent(#RequestBody Student student) {
return studentService.saveStudent(student);
}
...etc
}
There are 2 reason behind 404 not found
Problem 1
You main class is in com.BusyQA package and Controller class is in StudentController package so you have to scan controller class in main class.
Your StudentApplication.java class should become:
#SpringBootApplication
#ComponentScan(basePackageClasses = StudentController.class) // Scan the controller class in main class.
public class BusyQaApplication extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(BusyQaApplication.class, args);
}
}
Problem 2
Remove pre path /api/v1 from all url mapping in controller. Now your mapping url should become
#RestController
#RequestMapping("/api/v1")
public class StudentController {
#Autowired
private StudentService studentService;
#PostMapping("/addStudent")
#PostMapping("/addStudents")
#GetMapping("/students")
#GetMapping("/students/{id}")
#GetMapping("/students/{name}")
#PutMapping("/update")
#DeleteMapping("/delete/{id}")
}
This is another mistake in your code:
Remove the #Component annotation from controller.
Remove the #Component annotation from Service class.
Remove the #Component annotation from Repository interface and add #Repository annotation.
I am building this Spring Boot application with Hibernate and MySQL. I know this is pretty basic and the same question is asked multiple times but I can't figure out why my controller isn't hitting and gives 404 error. As I see, the problem is with ComponentScan where my #SpringBootApplication and #RestController reside within one package while my #Repository and #Entity lie in another package.
When I include the package as #ComponentScan(basePackages = "com.sample.user"), the project builds and runs successfully but does not hit the GET method getUser() and no console output of an error as well. The GET method hits only when I omit the
#Autowired private UserRepository userRepository; from the controller class along with #ComponentScan in application class.
Controller
package com.sample.rest.controller;
import com.sample.user.entity.User;
import com.sample.user.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#RequestMapping ("user")
public class UserController {
#Autowired
private UserRepository userRepository;
#GetMapping("/")
public User getUser() {
User user = new User();
user.setFirstName("Lady");
user.setLastName("Gaga");
user.setEmail("l.gaga#ymail.com");
userRepository.save(user);
return user;
}
}
Application
package com.sample.rest;
import com.sample.rest.controller.UserController;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan(basePackages = "com.sample.user")
public class RestServicesApplication {
public static void main(String[] args) {
SpringApplication.run(RestServicesApplication.class, args);
}
}
Repository Interface
package com.sample.user.repository;
import com.sample.user.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.stereotype.Repository;
#EnableJpaRepositories
#Repository
public interface UserRepository extends JpaRepository<User, Long> {}
Entity
package com.sample.user.entity;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
#Entity
#Table(name = "user")
#EntityListeners(AuditingEntityListener.class)
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "first_name", nullable = false)
private String firstName;
#Column(name = "last_name", nullable = false)
private String lastName;
#Column(name = "email_address", nullable = false)
private String email;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Browser Page
https://ibb.co/KDsqLn3
With #ComponentScan(basePackages = "com.sample.user") you are overwriting the default behavior.
So either remove this and put the packages below the package where you have #SpringBootApplication or add all packages to #ComponentScan.
I recommend not to use the default Spring Boot behavior.
So remove ComponentScan an move RestServicesApplication to the com.sample package
Use this it will resolve your Issue.
#ComponentScan(basePackages = "com.sample")
or use multiple package sacn somthing like
#ComponentScan({ "com.sample", "com.sample.user" })
I am new to Boot-Spring apparently, I mostly copy some code from youtube on this case. However, after modification, in the end, I got a message like this;
APPLICATION FAILED TO START
Description:
Field postService in com.example.demo.BlogController required a bean of type 'Server.PostService' that could not be found.
Action:
Consider defining a bean of type 'Server.PostService' in your configuration.
.....Any idea how to deal with this situation. Thank you for the support.
1stclass-BlogApplciation-----com.example.demo(package)
2nd-Blog Controller--------same package as BlogApplication
3rdclass-Post---entities
4rthclass-PostRepositories---Repositories
**package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class BlogApplication {
public static void main(String[] args) {
SpringApplication.run(BlogApplication.class, args);
}
}**
**package com.example.demo;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import Server.PostService;
import entities.Post;
import java.util.Date;
#RestController
public class BlogController {
#Autowired
private PostService postService;
#GetMapping(value="/")
public String index() {
return "index";
}
#GetMapping(value="/posts")
public List<Post>posts(){
return postService.getAllPosts();
}
#PostMapping(value="/post")
public void publishPost(#RequestBody Post post) {
if(post.getDatecreation() == null)
post.setDatecreation(new Date());
postService.insert(post);
}
}**
**package entities;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Post {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String title;
private String body;
private Date Datecreation;
public Post() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String gettitle() {
return title;
}
public void settitle(String title) {
this.title= title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public Date getDatecreation() {
return Datecreation;
}
public void setDatecreation(Date datecreation) {
this.Datecreation = datecreation;
}
}**
**package Repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import entities.Post;
#Repository
public interface PostRepository extends JpaRepository<Post,Long>{
}**
Your BlogApplication Class, which is the class annotated with #SpringBootApplication is in the package com.example.demo. That means that, by default, Spring is going to launch a Component Scan starting from that package.
The problem is that your class PostService and your interface PostRepository are not in the same package as (or in a sub-package of) com.example.demo, so Spring can't find them and won't automatically create these beans for you.
To correct this issue, move the packages you created inside your root package (com.example.demo).
You can find more information about the use of #SpringBootApplication here.
EDIT:
You are missing PostService class or you have imported incorrect class as Server.PostService.
try to create a service like this one:
#Component
public class PostService {
public List<Post> getAllPosts(){
//your code
}
}
I am building a very simple Spring boot app with mvc + mongodb. I used Spring initializer to create the proj with web, thymeleaf and mongo dependencies. I have one controller, one model and a view but I keep on getting an error when trying to execute the app:
Description:
Field repo in com.example.CustomerController required a bean named 'mongoTemplate' that could not be found.
Action:
Consider defining a bean named 'mongoTemplate' in your configuration.
CustomerController:
import model.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Created by Hello on 25/04/2017.
*/
#Controller
#RequestMapping("/home")
public class CustomerController {
#Autowired
CustomerMongoRepo repo;
#RequestMapping(value = "/home", method= RequestMethod.GET)
public String viewingHome(Model model){
//initDB();
model.addAttribute("key", "THIS IS FROM THE MODEL");
return "homepage";
}
}
CustomerMongoRepo:
import org.springframework.data.repository.CrudRepository;
import model.Customer;
public interface CustomerMongoRepo extends CrudRepository {}
MainApp:
import org.springframework.boot.SpringApplication;
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.web.WebMvcAutoConfiguration;
#SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
public class DemoApplication extends WebMvcAutoConfiguration {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Customer Model:
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
/**
* Created by Hello on 25/04/2017.
*/
#Document(collection = "customerCollection")
public class Customer {
#Id
private int id;
private String fName;
private String sName;
public Customer(){}
public Customer(int id, String fName, String sName){
setfName(fName);
setsName(sName);
setId(id);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getsName() {
return sName;
}
public void setsName(String sName) {
this.sName = sName;
}
}
My Application Properties:
spring.data.mongodb.database=customer
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.uri=mongodb://localhost:27018/mydb
spring.data.mongo.repositories.enabled=true
You are excluding Mongo Configuration.
#SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
Then how will spring create mongoTemplate for you. Remove this exclusion or create MongoTemplate manually and register it with application context(using #Bean)
I recently ran into this same problem and my solution was to remove spring-data-mongodb:
<!--<dependency>-->
<!-- <groupId>org.springframework.data</groupId>-->
<!-- <artifactId>spring-data-mongodb</artifactId>-->
<!-- <version>3.2.1</version>-->
<!--</dependency>-->
and I kept spring-boot-starter-data-mongodb:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
It is seen that either the two together gave conflict or I need to add 'something' that I did not know.
Happy code !!! And I hope to be of help to you
Update
Later I found something related to what could be described by the problem although I would never finish checking it:
https://stackoverflow.com/a/12389842/7911776
User.java:
package com.hodor.booking.jpa.domain;
import javax.persistence.Entity;
import java.util.Date;
#Entity
public class User extends AbstractPersistable {
private String firstName;
private String lastName;
private String email;
private Date birthday;
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getEmail() {
return email;
}
public Date getBirthday() {
return birthday;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setEmail(String email) {
this.email = email;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
UserRepository.java:
package com.hodor.booking.jpa.repository;
import com.hodor.booking.jpa.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* For Spring Data JPA query methods see:
* http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods
*/
public interface UserRepository extends JpaRepository<User, Long> {
public User findByEmail(String email);
public User findByLastname(String lastName);
}
UserService.java:
package com.hodor.booking.service;
import com.hodor.booking.jpa.domain.User;
import com.hodor.booking.jpa.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import java.util.List;
#Service
public class UserService {
#Autowired
private UserRepository userRepository;
public User saveUser(User user) {
Assert.notNull(user);
return userRepository.saveAndFlush(user);
}
public List<User> findAll() {
return userRepository.findAll();
}
public User findOne(Long id) {
Assert.notNull(id);
return userRepository.findOne(id);
}
public User findByEmail(String email) {
Assert.hasLength(email);
return userRepository.findByEmail(email);
}
public User findByLastname(String lastName) {
Assert.hasLength(lastName);
return userRepository.findByLastname(lastName);
}
}
UserController:
package com.hodor.booking.controller;
import com.hodor.booking.jpa.domain.User;
import com.hodor.booking.service.UserService;
import com.wordnik.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
#RequestMapping("/api/v1/users")
#Api(value = "users", description = "User resource endpoint")
public class UserController {
private static final Logger log = LoggerFactory.getLogger(UserController.class);
#Autowired
private UserService userService;
#RequestMapping(method = RequestMethod.GET)
public List<User> index() {
log.debug("Getting all users");
return userService.findAll();
}
#RequestMapping(value = "/{id}", method = RequestMethod.GET)
public User get(#PathVariable("id") Long id) {
return userService.findOne(id);
}
#RequestMapping(value = "/{lastName}", method = RequestMethod.GET)
public User get(#PathVariable("lastName") String lastName) {
return userService.findByLastname(lastName);
}
}
StackTrace:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.hodor.booking.jpa.repository.UserRepository com.hodor.booking.service.UserService.userRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property lastname found for type User!
Problem:
I added the findByLastname Method and I can't find the problem (I am new to this).
I had never used Spring... but reading the docs about org.springframework.data.jpa.repository.JpaRepository, I suggest to rename your method: findByLastname as findByLastName in the UserRepository interface...
It seems this functionalty generates JPA queries by reading and parsing the defined methods at a given interface that extends from JpaRepository ... and by saying "findByLastname", Spring expects to find a property at User Entity as: lastname and not lastName