findAll() is not working in SpringBoot Rest MySql CRUD operations application - java

I am trying to perform CRUD operations using spring boot+REST+MySQL
along crudrepository interface,when i try to get data from database,i
am getting empty list back.I found that findAll() method in my application is not working as expected.
My Application class
#SpringBootApplication
public class Blog {
public static void main(String[] args) {
SpringApplication.run(Blog.class, args);
System.out.println("Application Started");
}}
My Entity class
#Entity
#Table(name="posts")
public class Post {
#Id
#Column(name="id")
int postId;
#Column(name="title")
String title;
#Column(name="body")
String body;
public Post() {}
public Post(int postId, String title, String body) {
this.postId = postId;
this.title = title;
this.body = body;
} //getters and setters and toString()
Controller Class
#RestController
public class PostsController {
#Autowired
private PostsService service;
#RequestMapping("/posts")
public List<Post> getPosts(){
return service.getPosts();
}
#RequestMapping("/posts/{id}")
public Post getPost(#PathVariable int id) {
return service.getPost(id);
}
#RequestMapping(method=RequestMethod.POST, value="/posts")
public void addPost(#RequestBody Post listElement) {
service.addPost(listElement);
}
#RequestMapping(method=RequestMethod.PUT, value="/posts/{id}")
public void updatePost(#RequestBody Post post) {
service.updatePost(post);
}
#RequestMapping(method=RequestMethod.DELETE, value="/posts/{id}")
public void deletePost(#PathVariable int id) {
service.deletePost(id);
}
Service Classs
#Service
public class PostsService {
#Autowired
private PostRepository repo;
public List<Post> getPosts(){
List<Post> list = new ArrayList<>();
System.out.println("at Service");
for(Post post: repo.findAll()) {
System.out.println("in for loop");
list.add(post);
}
return list;
}
public Post getPost(int id) {
return repo.findById(id).get();
}
public void addPost(Post listElement) {
repo.save(listElement);
}
public void updatePost(Post post) {
repo.save(post);
}
public void deletePost(int id) {
repo.deleteById(id);
}
}
Repository Interface
public interface PostRepository extends CrudRepository<Post, Integer>
{ }
Application.properties file
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/blog?useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.studyeasy</groupId>
<artifactId>06.01-RestfulMicroserviceWithDB</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>06.01-RestfulMicroserviceWithDB</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Outputs
when i perform get operation, out put was "[]"
when i perform get operation by id , out put was
{
"timestamp": "2019-03-29T02:44:00.768+0000",
"status": 500,
"error": "Internal Server Error",
"message": "No value present",
"path": "/posts/3" }
java.util.NoSuchElementException: No value present
when i perform delete operation ,i got this output
"org.springframework.dao.EmptyResultDataAccessException: No class org.studyeasy.entity.Post entity with id 3 exists!" in console and
output in postman was
{ "timestamp": "2019-03-29T02:48:51.423+0000",
"status": 500,
"error": "Internal Server Error",
"message": "No class org.studyeasy.entity.Post entity with id
3 exists!",
"path": "/posts/3" }

Do as follows :
PostController.java
#RestController
public class PostController {
#Autowired
private PostsService service;
#RequestMapping("/posts")
public List<Post> getPosts(){
return service.getPosts();
}
#RequestMapping("/posts/{id}")
public Post getPost(#PathVariable int id) {
return service.getPost(id);
}
#RequestMapping(method=RequestMethod.POST, value="/posts")
public void addPost(#RequestBody Post listElement) {
service.addPost(listElement);
}
#RequestMapping(method=RequestMethod.PUT, value="/posts/{id}")
public void updatePost(#RequestBody Post post) {
service.updatePost(post);
}
#RequestMapping(method=RequestMethod.DELETE, value="/posts/{id}")
public void deletePost(#PathVariable int id) {
service.deletePost(id);
}
}
PostService.java
#Service
public class PostsService {
#Autowired
private PostRepository repo;
public List<Post> getPosts(){
return (List<Post>) repo.findAll();
}
public Post getPost(int id) {
return repo.findById(id).get();
}
public void addPost(Post listElement) {
repo.save(listElement);
}
public void updatePost(Post post) {
repo.save(post);
}
public void deletePost(int id) {
repo.deleteById(id);
}
}
PostRepository.java
#Repository
public interface PostRepository extends CrudRepository<Post, Integer>{
}
Post.java
#Entity
#Table(name="posts")
public class Post implements Serializable{
#Id
#Column(name="id")
int postId;
#Column(name="title")
String title;
#Column(name="body")
String body;
public Post() {}
public Post(int postId, String title, String body) {
this.postId = postId;
this.title = title;
this.body = body;
}
//gettters & setters
}
You can also refer Best Practice to send response for other stuffs. . .
Issue was you have missed #ResponseBody annotation. So here i have used #RestController
Output:

Related

Error creating bean with name 'orderController'

I am studying Spring Boot and I want to create a Rest Controller, and using a sql database, but there is a problem when I start the project :
Error:
(the error text is great I will leave the link)
And code:
OrderController.java
package ***;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.Optional;
#RestController
public class OrderController {
#Autowired
private OrderRepository orderRep;
#GetMapping("/")
public List<Order> index(){
return (List<Order>) orderRep.findAll();
}
#GetMapping("/{id}")
public Order show(#PathVariable int id){
Optional<Order> orderId= orderRep.findById(id);
Order order = orderId.get();
return order;
}
#PostMapping("/search")
public List<Order> search(#RequestBody Map<String, String> body){
String searchItem = body.get("item");
return orderRep.findByTitleContainingOrContentContaining(searchItem);
}
#PostMapping("/")
public Order create(#RequestBody Map<String, String> body){
String item = body.get("item");
int price = Integer.parseInt(body.get("price"));
int quantity = Integer.parseInt(body.get("quantity"));
return orderRep.save(new Order(item, price,quantity));
}
#PutMapping("/{id}")
public Order update(#PathVariable String id, #RequestBody Map<String, String> body){
int orderId = Integer.parseInt(id);
// getting blog
Optional<Order> order = orderRep.findById(orderId);
order.get().setItem(body.get("item"));
order.get().setPrice(Integer.parseInt(body.get("price")));
order.get().setQuantity(Integer.parseInt("quantity"));
return orderRep.save(order.get());
}
#DeleteMapping("/{id}")
public boolean delete(#PathVariable int id){
//int orderId = Integer.parseInt(id);
orderRep.deleteById(id);
return true;
}
}
Order.java
package ***;
import javax.persistence.*;
#Entity
#Table(name = "orders")
public class Order {
//Fields
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column(name = "item")
private String item;
#Column(name = "price")
private int price;
#Column(name = "quantity")
private int quantity;
//Constructors
public Order() { }
public Order(String item, int price, int quantity) {
this.setItem(item);
this.setPrice(price);
this.setQuantity(quantity);
}
public Order(int id, String item, int price, int quantity) {
this.setId(id);
this.setItem(item);
this.setPrice(price);
this.setQuantity(quantity);
}
//Object to string data
#Override
public String toString() {
return "Order{" +
"id=" + getId() +
", item='" + getItem() + '\'' +
", price='" + getPrice() + '\'' +
", price='" + getQuantity() + '\'' +
'}';
}
//Getters & Setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
OrderRepository.java
package ***;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface OrderRepository extends CrudRepository<Order, Integer> {
// custom query to search to blog post by title or content
List<Order> findByTitleContainingOrContentContaining(String item);
}
application.properties
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/testvoy?useUnicode=true&serverTimezone=UTC&useSSL=true&verifyServerCertificate=false
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name =com.mysql.jdbc.Driver
#spring.jpa.show-sql: true
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.test</groupId>
<artifactId>project</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>project</name>
<description>project</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-mockmvc</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.asciidoctor</groupId>
<artifactId>asciidoctor-maven-plugin</artifactId>
<version>1.5.8</version>
<executions>
<execution>
<id>generate-docs</id>
<phase>prepare-package</phase>
<goals>
<goal>process-asciidoc</goal>
</goals>
<configuration>
<backend>html</backend>
<doctype>book</doctype>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-asciidoctor</artifactId>
<version>${spring-restdocs.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I would be grateful for any help, thanks in advance
If you check the error, you can see that it comes from there:
List<Order> findByTitleContainingOrContentContaining(String item);
and if you read more closely to the error, you will see:
No property title found for type Order!;
inside here:
Caused by: org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.util.List com.test.project.OrderRepository.findByTitleContainingOrContentContaining(java.lang.String)! Reason: Failed to create query for method public abstract java.util.List com.test.project.OrderRepository.findByTitleContainingOrContentContaining(java.lang.String)! No property title found for type Order!; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List com.test.project.OrderRepository.findByTitleContainingOrContentContaining(java.lang.String)! No property title found for type Order!
Infact, if you check your model, there is no title property

Getting null value in one column with "findById" in Java Spring although it exists in DB

I am very new in Java Spring and have a problem where I can not figure out what am I missing.
For the shake of brevity I will make it short:
I have a controller class with two methods for #GetMapping (get info from a patient in database) and #PostMapping (upload a photo from that patient).
In both methods, at some point I am calling through "findById" to database and populating a "Patient" model class object.
All the attributes of this class are retrieved successfully from Database but there is an attribute of this class (getPhoto()) that gets a null value only in the #PostMapping method.
What am I missing? The code is just the same in both methods.
Thanks very much in advance!!
Controller:
#CrossOrigin(origins="http://localhost:4200", maxAge = 3600)
#RestController
#RequestMapping({"/patients"})
public class PatientController {
#Autowired
IPatientService patientService;
#GetMapping("/{id}")
public ResponseEntity<?> listPatientId(#PathVariable("id") Integer id){
Optional<Patient> patient=null;
Map<String, Object> response=new HashMap<>();
try{
patient=patientService.findById(id);
}catch(DataAccessException e){
response.put("error", e.getMessage().concat(": "+e.getMostSpecificCause().toString()));
new ResponseEntity<Map<String, Object>>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
System.out.println("Patient with id: "+id+" / "+patient.get().getId()+" which photo is: "+patient.get().getPhoto());
/*Some other code*/
}
#PostMapping("/upload")
public ResponseEntity<?> upload(#RequestParam("archive")MultipartFile archive, #RequestParam("id") Integer id){
Optional<Paciente> paciente = Optional.empty();
Map<String, Object> respuesta= new HashMap<>();
try{
patient=patientService.findById(id);
}catch(DataAccessException e){
response.put("error", e.getMessage().concat(": "+e.getMostSpecificCause().toString()));
new ResponseEntity<Map<String, Object>>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
System.out.println("Patient with id: "+id+" / "+patient.get().getId()+" which photo is: "+patient.get().getPhoto());
/*Some other code*/
}
}
Patient class:
#Entity
#Table(name = "patients")
public class Patient {
#Id
#Column
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
#Column
private String photo;
(Getters and setters)
}
Repository:
#Repository
public interface PatientRepository extends JpaRepository<Patient, Integer> {
Iterable<Patient> findByNameContainingOrSurnameContaining(String name, String surname);
}
Service (Interface and Implemantation):
public interface IPatientService {
public List<Patient> findAll();
public Optional<Patient> findById(Integer id);
public Iterable<Patient> findByNameContainingOrSurnameContaining(String term);
}
#Service
public class PatientServiceImpl implements IPatientService {
#Autowired
private PatientRepository patientDao;
#Override
#Transactional(readOnly = true)
public List<Patient> findAll() {
return patientDao.findAll();
}
#Override
public Optional<Patient> findById(Integer id) {
return patienteDao.findById(id);
}
public Iterable<Patient> findByNameContainingOrSurnameContaining(String term){
return patientDao.findByNameContainingOrSurnameContaining(term, term);
}
#Override
public Patient save(Patient patient){
return patientDao.save(patient);
}
#Override
public void deleteById(Integer id) {
patientDao.deleteById(id);
}
}
As stated before, "patient.get().getPhoto()" returns in #GetMapping the actual value stored in the database. But in the method annotated with #PostMapping returns null for that value (Although other attributes seem to work just fine).
This was the backend, but in the frontend I am using Angular, where I call this method in component (I am showing just the parts involved in the uploading photo):
patient: Patient;
constructor(private route: ActivatedRoute, private router: Router, private service: ServiceServicee) {
this.paient = new Patient();
}
uploadPhoto() {
this.service.uploadPhoto(this.selectedPhoto,
this.patient.id).subscribe(patient => {
this.patient = patient;
});
}
Service:
constructor(private http:HttpClient, private router:Router) {
this.urlPatients='http://localhost:8080/patients';
}
uploadPhoto(file: File, id):Observable<Patient>{
let formData= new FormData();
formData.append("archive", file);
formData.append("id", id);
return this.http.post(`${this.urlPatients}/upload`, formData).pipe(
map((response:any)=> response.patient as Patient),
catchError(e=>{
console.error(e.error.mensaje);
return throwError(e);
})
);
}
UPDATE:
Using Postman and making a POST to http://localhost:8080/patients/upload and sending in the body a jpg file (form-data - "archive") and a id number("id"), I got a success with the inserts and the method it didn't worked previously in the backend (patient.get().getPhoto()) worked perfectly this time. With the same code, so I assume that it is as #BiteBat said and it is a problem of the Frontend and how it is calling the Backend.
I simulated the same environment that you created and it works for me as you expect, I leave the code for you to review what your problem. I would think you are incorrectly calling the POST method. Now, I would recommend that you do not save the images in a relational database, because there are alternatives with better performance, such as Google Storage / Local storage or any file storage service.
Structure:
EntryPoint:
package question;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#EnableJpaRepositories
public class JulianPelayoApplication {
public static void main(String[] args) {
SpringApplication.run(JulianPelayoApplication.class, args);
}
}
Controller:
package question.controller;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import question.repository.Patient;
import question.repository.PatientsRepository;
#CrossOrigin(origins="http://localhost:4200", maxAge = 3600)
#RestController
#RequestMapping("/patients")
public class PatientController {
private PatientsRepository patientsRepository;
#Autowired
public PatientController(PatientsRepository patientsRepository) {
this.patientsRepository = patientsRepository;
}
#GetMapping("/{id}")
public ResponseEntity<?> listPatientId(#PathVariable("id") Integer id){
Optional<Patient> patient=null;
Map<String, Object> response=new HashMap<>();
try{
patient = patientsRepository.findById(id);
}catch(DataAccessException e){
response.put("error", e.getMessage().concat(": "+e.getMostSpecificCause().toString()));
new ResponseEntity<Map<String, Object>>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
System.out.println("Patient with id: "+id+" / "+patient.get().getId()+" which photo is: "+patient.get().getPhoto());
return ResponseEntity.ok(patient);
}
#PostMapping(value="/upload")
public ResponseEntity<?> upload(#RequestParam("archive") MultipartFile archive, #RequestParam("id") Integer id){
Optional<Patient> patient = Optional.empty();
Map<String, Object> response = new HashMap<>();
try{
patient = patientsRepository.findById(id);
}catch(DataAccessException e){
response.put("error", e.getMessage().concat(": "+e.getMostSpecificCause().toString()));
new ResponseEntity<Map<String, Object>>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
System.out.println("Patient with id: "+id+" / "+patient.get().getId()+" which photo is: "+patient.get().getPhoto());
return ResponseEntity.ok(patient);
}
}
Repository:
package question.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface PatientsRepository extends CrudRepository<Patient, Integer>{
}
Patient:
#Entity
#Table(name = "patients", schema = "business")
#Getter #Setter
public class Patient {
#Id
#Column
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
#Column
private String photo;
}
Spring.properties:
spring.datasource.url=jdbc:postgresql://localhost/test
spring.datasource.username=test
spring.datasource.password=test
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
Pom:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>question</groupId>
<artifactId>JulianPelayo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>JulianPelayo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Response:
Get
Post

Spring boot ERROR "Field trepository in TrainerController required a bean of type TrainerRepo that could not be found." ."

Im making a Spring boot project and when running it says:
"Field trepository in com.example.trainerplanner.trainerController.TrainerController required a bean of type 'com.example.trainerplanner.model.domain.TrainerRepository' that could not be found."
I already cleaned the .m2 directory and tried to add/delete many different dependencies.
package com.example.trainerplanner;
#ComponentScan({"com.example.trainerplanner.model.domain"})
#EnableAutoConfiguration
#EnableJpaRepositories(basePackageClasses = {TrainerRepository.class, CategoryRepository.class})
#SpringBootApplication
public class TrainerplannerApplication {
private static final Logger log = LoggerFactory.getLogger(TrainerplannerApplication.class);
public static void main(String[] args) {
SpringApplication.run(TrainerplannerApplication.class, args);
}
#Bean
public CommandLineRunner trainerDemo(CategoryRepository crepository, TrainerRepository trepository) {
return (args) -> {
log.info("Save some exercises");
//Tässä kohdassa tehdään uudet kategoriat "c repositoryyn".
//Ensiksi on yläkropan päälihakset ja sitten alakropan
crepository.save(new Category("Biceps")); //Hauikset
crepository.save(new Category("Triceps")); //Ojentajat
crepository.save(new Category("Chest")); //Rinta
crepository.save(new Category("Shoulders")); //Olkapäät
crepository.save(new Category("Back")); //Selkä
crepository.save(new Category("Quadriceps")); //Etureidet
crepository.save(new Category("Hamstrings")); //Takareidet
crepository.save(new Category("Calves")); //Pohkeet
crepository.save(new Category("Glutes")); //Pakarat
trepository.save(new Trainer("Bicep curl", 8, 3, crepository.findByName("Biceps").get(0)));
trepository.save(new Trainer("Tricep extension", 8, 3, crepository.findByName("Triceps").get(0)));
trepository.save(new Trainer("Squat", 8, 3, crepository.findByName("Quadriceps").get(0)));
User userYksi = new User("user", "$2y$12$4iGWyQs5hC6ibe5Pq7ochekppUZcSfeIV.tjgZIuSobVA8B5vOhXK", "USER");
//Molemmat salasanat hashattu BCryptillä, roundit oli 12 ja 9
User userKaksi = new User("admin", "$2y$06$K9UJzObPGyroQKlkTzWWz.BlUurpYCMFelyvM/2AVYSbzogvd3.zq", "ADMIN");
urepository.save(userYksi);
urepository.save(userKaksi);
log.info("fetch all exercises");
for (Trainer trainer : trepository.findAll()) {
log.info(trainer.toString());
};
};}
This is the springbootapp
#Controller
#Component
#EnableJpaRepositories
public class TrainerController {
#Autowired
private TrainerRepository trepository;
#Autowired
private CategoryRepository crepository;
//Req. mappingeissä nähdään mikä menee urlin loppuun. esim. localhost:8080/trainerlist palauttaa trainerlist thymeleafsivun
//Metodit eri toiminnoille, esim lisää, poista, lista, tallenna.
#RequestMapping(value= {"/", "/trainerlist"})
public String trainerList(Model model) {
model.addAttribute("trainers", trepository.findAll());
return "trainerlist";
}
#RequestMapping(value = "/add")
public String addTrainer(Model model){
model.addAttribute("trainer", new Trainer());
model.addAttribute("category", crepository.findAll());
return "addtrainer";
}
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(Trainer trainer){
trepository.save(trainer);
return "redirect:trainerlist";
}
//Poistaa ID:n avulla trainerin ja palauttaa //trainerlist-sivun
#RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
public String deleteTrainer(#PathVariable("id") Long trainerId, Model model) {
trepository.deleteById(trainerId);
return "redirect:../trainerlist";
}
}
Controller class
#Repository
public interface CategoryRepository extends CrudRepository<Category, Long> {
List<Category> findByName(String name);
}
CategoryRepo, TrainerREpo is same but with different name.
#Component
public class TrainerModel {
public String Trainer(#RequestParam(value="name")String name, Integer reps, Integer sets, Model model) {
model.addAttribute("name", name);
model.addAttribute("reps", reps);
model.addAttribute("sets", sets);
return "index";
}
}
This is the TrainerModel class
#Component
#Entity
public class Trainer {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
private String name;
private Integer reps, sets;
#ManyToOne
#JoinColumn(name = "categoryid")
#JsonManagedReference
private Category category;
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public Trainer() {
//Tyhjä
}
public Trainer(String name, Integer reps, Integer sets, Category category) {
super();
this.name = name;
this.reps = reps;
this.sets = sets;
this.category =category;
}
//Asetetaan getterit ja setterit Traineriin.
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getReps() {
return reps;
}
public void setReps(Integer reps) {
this.reps = reps;
}
public Integer getSets() {
return sets;
}
public void setSets(Integer sets) {
this.sets = sets;
}
#Override
public String toString() { //Jos kategoria tyhjä niin palautetaan ensimmäinen kohta, muuten else-kohta.
if (this.category != null)
return "Trainer [id=" + id + ", name=" + name + ", reps=" + reps + ", =" + sets + " sets =" + this.getCategory() + "]";
else
return "Trainer [id=" + id + ", name=" + name + ", reps=" + reps + ", sets=" + sets + "]";
}
}
And This is the Trainer class
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>trainerplanner</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>trainerplanner</name>
<description>Trainer planner for exercising</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Pom xml, re did the whole project with spring initialzr but no effect.

spring boot repository throws an exception

I am new to spring boot.
I have created my web application as below.
SampleApplication.java
#SpringBootApplication
public class SampleApplication implements CommandLineRunner {
#Autowired
DataSource dataSource;
#Autowired
private UserRepository userRepository;
Logger logger = LoggerFactory.getLogger(SampleApplication.class);
public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
}
#Transactional(readOnly = true)
#Override
public void run(String... args) throws Exception {
UserLoginController userLoginController = new UserLoginController();
System.out.println("DATASOURCE = " + dataSource);
logger.debug("\nUser: "+userRepository.findByName("user").getName());
logger.debug(userLoginController.getUserInfo("user","pword"));
}
}
UserRepository.java
#EnableJpaRepositories
#Repository
public interface UserRepository extends CrudRepository<User,Long> {
User findByName(String name);
}
User.java
#Entity
#Table(name="USER")
public class User
implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(name="USER_ID_GENERATOR", sequenceName="USER_SEQ")
#GeneratedValue(strategy=GenerationType.AUTO, generator="USER_ID_GENERATOR")
private Long id;
#Column(name="NAME")
private String name;
#Column(name="PASSWORD")
private Long password;
public Long getId()
{
return this.id;
}
public void setId(Long id)
{
this.id = id;
}
public String getName()
{
return this.name;
}
public void setName(String name)
{
this.name = name;
}
public String getPassword()
{
return this.password;
}
public void setPassword(String password)
{
this.password = password;
}
UserLoginController.java
#Controller
public class UserLoginController {
Logger logger = LoggerFactory.getLogger(UserLoginController.class);
#RequestMapping(value = "/userLogin**", method = RequestMethod.POST)
public #ResponseBody String getUserInfo(#RequestParam("mobile") String uName, #RequestParam("pin") String pWord){
logger.debug("UserLoginController | uName: " + uName + " pWord: " + pWord);
UserLoginService userLoginService = new UserLoginService();
String user = null;
try {
logger.debug("UserLoginController | Validate user. uName: " + uName + " pWord: " + pWord);
user = userLoginService.validateSysUser(uName, pWord);
} catch (Exception e) {
logger.debug("UserLoginController | Validate user Exception: " + e.getMessage()+", "+e.getStackTrace());
}
if (user != null) {
logger.debug("UserLoginController | Returning aircash user");
return user;
} else {
logger.debug("UserLoginController | Returning NULL");
return null;
}
}
}
UserLoginService .java
public class UserLoginService {
Logger logger = LoggerFactory.getLogger(UserLoginService.class);
#Autowired
DataSource dataSource;
#Autowired
private UserRepository userRepository;
public String validateSysUser(String uName, String pWord) throws Exception{
logger.debug("UserLoginService | uName: "+uName+" pWord: "+pWord);
User user = new User();
String auser = userRepository.findByName(uName).getName();
if ((auser != null) && (validatePword(user.getPassword(),pWord)){
logger.debug("UserLoginService | User found: "+user.getName());
return auser;
}else {
logger.debug("UserLoginService | User not found");
return null;
}
}
public static boolean validatePword(String pWord,String pWord2){
return BCrypt.checkpw(pWord2,pWord);
}
}
Problem is, When I run the application,This part give me the intended response
logger.debug("\nUser: "+userRepository.findByName("user").getContactNo());
But, next line throws an exception. I also tried calling the controller using the postman too. But the same exception comes.
logger.debug(userLoginController.getUserInfo("user","pword"));
The exception is thrown from the UserLoginService.java class. The exception message is shown as null
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>robicash</groupId>
<artifactId>distributorcommision</artifactId>
<version>1.0</version>
<name>distributorcommission</name>
<description>commision for distributors</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mindrot</groupId>
<artifactId>jbcrypt</artifactId>
<version>0.3m</version>
</dependency>
<!--<dependency>-->
<!--<groupId>com.oracle</groupId>-->
<!--<artifactId>ojdbc8</artifactId>-->
<!--<version>11.2.0.4</version>-->
<!--</dependency>-->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc7</artifactId>
<version>12.1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I don't understand why the same repository give two results when called.
Can you please tell me how to get it working.
You cannot instantiate the UserLoginService userLoginService = new UserLoginService();
You have to inject it into the controller:
#Autowired
UserLoginService userLoginService;
Spring will only manage your service if it's instantiated by Spring and then injected.
And yes Kes is partially right. You must add #Service or #Component annotation in UserLoginService:
#Service
public class UserLoginService {

Can't create table with jpa+spring boot

I'm trying to generate table using JPA. but i can't create it. There is no error in the code, but it seems that there is configuration error. but i can't find it, i tried many configurations but nothing happen.
Thanks a lot.
This is application.property:
spring.datasource.url=jdbc:mysql://localhost:3306/springapp
spring.datasource.username= root
spring.datasource.password= me
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=create
this is my class:
#Entity
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
private String phone;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Customer(String name, String phone) {
super();
this.name = name;
this.phone = phone;
}
public Customer() {
super();
}
}
This is the application:
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
And this is the controller:
#RestController
#RequestMapping("/customer")
public class CustomerController {
#Autowired
CustomerRepository customerRepository;
#RequestMapping("/findall")
#ResponseBody
public List<Customer> findAll() {
return customerRepository.findAll();
}
}
Pom.xml
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>GStock-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>GStock-3</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Try to add #EntityScan
#EntityScan("<package with entities>")
#SpringBootApplication
public class Application { ... }
With the current information I have a couple of suggestions / Questions that might help you allong:
Does the "springapp" database exist with the correct user (root) and password (me) assigned to it in MySQL
Has MySQL been started?
I see no #Repository definition in your code e.g.
#Repository
public interface CustomerRepository extends JpaRepository{}
execute following on your mysql:
mysql> create database db_example; -- Create the new database
mysql> create user 'springuser'#'localhost' identified by 'ThePassword'; -- Creates the user
mysql> grant all on db_example.* to 'springuser'#'localhost'; -- Gives all the privileges to the new user on the newly created database
and add into application.xml:
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword
OR
you can go through this link

Categories

Resources