Error creating bean with name 'orderController' - java

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

Related

No operations defined in spec!! and 404 error in postman. The spring boot don't show any error from my code. yet i can't establish the connection

This is a simple code that i got from youtube for practice. well i did the code correcly but i cant get the explicit mapping correclty, that what the 404 error in the postman says.
I don't know if its my Spring boot app problem or the code error. please have a look at this , Since spring boot is not giving a proper answer.
//CONTROLLER
#Slf4j
#RestController
#RequestMapping("/api/v1")
public class RestuController {
#Autowired
private RestuService restuService;
/////////////////////////////////////POST MAPPING//////////////////////////////////////////////////////////////////////
#PostMapping("/POST/save")
Restaurant addRestaurant(#RequestBody Restaurant restaurant) {
return restuService.saveRestu(restaurant);
}
#PostMapping("/POST/saves")
List<Restaurant> addRestaurants(#RequestBody List<Restaurant> restaurants) {
return restuService.saveRestaurants(restaurants);
}
#GetMapping("/GET/resturants")
List<Restaurant> findAllRestaurants(){
log.debug("reached /GET/resturants");
return restuService.getRestaurants();
}
#GetMapping("/GET/{id}")
Restaurant findRestaurantById(#PathVariable int id) {
log.debug("reached /GET/{id} :" + id);
return restuService.getRestaurantById(id);
}
#GetMapping("/GET/{name}")
Restaurant findRestaurantByName(#PathVariable String name) {
log.debug("reached /GET/{name}:" + name);
return restuService.getRestaurantByname(name);
}
#GetMapping("/GET/{dist}")
List<Restaurant> findRestaurantByDist(#PathVariable int distance) {
log.debug("reached /GET/{dist} :" + distance);
return restuService.getRestaurantbyDist(distance);
}
#GetMapping("/GET/{loc}")
List<Restaurant> findRestaurantByLocation(#PathVariable String location) {
log.debug("reached /GET/{loc} : " + location);
return restuService.getRestaurantbyLocation(location);
}
#GetMapping("/GET/{cuisine}")
List<Restaurant> findRestaurantByCuisine(#PathVariable String cuisine) {
log.debug("reached /GET/{cuisine} : " + cuisine);
return restuService.getRestaurantbyCuisine(cuisine);
}
#GetMapping("/GET/{budget}")
List<Restaurant> findRestaurantByBudget(#PathVariable int budget) {
log.debug("reached /GET/{Budget} : " + budget);
return restuService.getRestaurantbyBudget(budget);
}
}
//SERVICE
package SERVICE;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ENTITY.Restaurant;
import REPOSITORY.RestuRepository;
#Service
public class RestuService {
#Autowired
RestuRepository restuRepository;
///////////////////postmethods//////////////////////////////////////
public Restaurant saveRestu(Restaurant restaurant) {
return restuRepository.save(restaurant);
}
public List<Restaurant> saveRestaurants(List<Restaurant> restaurants) {
return restuRepository.saveAll(restaurants);
}
///////////////////////////////////////////////////////////////////////////////////////
//////////////////GET METHODS//////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////
public List<Restaurant> getRestaurants(){
return restuRepository.findAll();
}
public Restaurant getRestaurantById(int id){
return restuRepository.findById(id).orElse(null);
}
public Restaurant getRestaurantByname(String name){
return restuRepository.findByName(name);
}
public List<Restaurant> getRestaurantbyDist(int distance){
return restuRepository.findByDist(distance);
}
public List<Restaurant> getRestaurantbyLocation(String location){
return restuRepository.findByLocation(location);
}
public List<Restaurant> getRestaurantbyCuisine(String cuisine){
return restuRepository.findBycuisine(cuisine);
}
public List<Restaurant> getRestaurantbyBudget(int budget){
return restuRepository.findBybudget(budget);
}
}
//REPOSITORY
package REPOSITORY;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import ENTITY.Restaurant;
#Repository
public interface RestuRepository extends JpaRepository<Restaurant, Integer> {
Restaurant findByName(String name);
List<Restaurant> findByDist(int distance);
List<Restaurant> findByLocation(String location);
List<Restaurant> findBycuisine(String cuisine);
List<Restaurant> findBybudget(int budget);
}
//ENTITY OR MODEL CLASS
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name = "restaurant_tbl")
public class Restaurant {
#Id
#GeneratedValue
private int id;
private String name;
private String cuisine;
private String location;
private int distance;
private int budget;
}
//APPLICATION.PROPERTIES
server.port = 6282
spring.datasource.dbcp2.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url =jdbc:mysql://localhost:3306/restaurants
spring.datasource.username = root
spring.datasource.password = ****
spring.jpa.show-sql =true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
springdoc.api-docs.path=/api-docs
springdoc.swagger-ui.path=/swagger-ui.html
//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.7.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.sangamam</groupId>
<artifactId>RESTAURANT-SERVICE</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>RESTAURANT-SERVICE</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</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>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.4</version>
</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>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>

JAX-RS gives status code 500 for GET operation for XML type response

I have just begun to learn RESTful services and this is the issue I have been facing recently.
When I run the application to GET an XML type response, I get status code 500 and I don't see any stack trace for this as well. Am I missing anything in the dependency list ? Please help me figure this.
Here is the entity class :
import java.util.Date;
import jakarta.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Message {
private int id;
private String message;
private String author;
private Date date;
public Message() {}
public Message(int id, String message, String author) {
super();
this.id = id;
this.message = message;
this.author = author;
this.date = new Date();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
#Override
public String toString() {
return "Message [id=" + id + ", message=" + message + ", author=" + author + ", date=" + date + "]";
}
}
And then I have my service class : MessageService.java :
import java.util.ArrayList;
import java.util.List;
import org.aravind.restful.messenger.model.Message;
public class MessageService {
public List<Message> getMessages()
{
Message m1 = new Message(1,"Hello World!","aravind");
Message m2 = new Message(2,"First step towards the goal!","aravind");
List <Message> messageList = new ArrayList<Message>();
messageList.add(m1);
messageList.add(m2);
return messageList;
}
}
And then I have the resource class : MessengerResouce.java
package org.aravind.restful.messenger.resources;
import java.util.List;
import org.aravind.restful.messenger.model.Message;
import org.aravind.restful.messenger.service.MessageService;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
#Path("/messages")
public class MessengerResource {
#GET
#Produces(MediaType.APPLICATION_XML)
public List<Message> getMessages()
{
MessageService msgService = new MessageService();
return msgService.getMessages();
}
}
And here is how my pom.xml looks :
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.aravind.restful</groupId>
<artifactId>messenger</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>messenger</name>
<build>
<finalName>messenger</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<inherited>true</inherited>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<!-- use the following artifactId if you don't need servlet 2.x compatibility -->
<!-- artifactId>jersey-container-servlet</artifactId -->
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
</dependency>
<!-- uncomment this to get JSON support
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-binding</artifactId>
</dependency>
-->
</dependencies>
<properties>
<jersey.version>3.0.0-M1</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
Please help me figure this out. Thanks.
The link Sam suggested answers your question. You have to wrap your response as a GenericEntity. Here is the documentation from the Response class:
"It is the callers responsibility to wrap the actual entity with GenericEntity if preservation of its generic type is required."
So your code should look something like this:
#GET
#Produces(MediaType.APPLICATION_XML)
public Response getMessages()
{
MessageService msgService = new MessageService();
return Response.status(Status.OK)
.entity(new GenericEntity<>(msgService.getMessages(), List.class))
.build(); ;
}

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.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userResource

I've been having this issue for days now on my eclipse console:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userResource'
followed by
Caused by: java.lang.IllegalStateException: Failed to introspect Class
and
Caused by: java.lang.NoClassDefFoundError: org/springframework/data/jpa/repository/JpaRepository
then
Caused by: java.lang.ClassNotFoundException:
org.springframework.data.jpa.repository.JpaRepository
this is my
user.java
package com.example.SpringMVC4.webservices.SpringMVC04webservices;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class User {
#Id
#GeneratedValue
private Integer id;
private String name;
private Date birthDate;
public User(Integer id, String name, Date birthDate) {
super();
this.id = id;
this.name = name;
this.birthDate = birthDate;
}
public User(String string, String string2) {
// TODO Auto-generated constructor stub
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
#Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", birthDate=" + birthDate + "]";
}
}
Below:
UserRepository.java
package com.example.SpringMVC4.webservices.SpringMVC04webservices;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UserRepository extends JpaRepository<User, Integer>{
User findOne(int id);
}
Below is
UserResource.java
package com.example.SpringMVC4.webservices.SpringMVC04webservices;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class UserResource {
#Autowired
private UserRepository userRepository;
// retrieve All Users GET
#GetMapping("/users")
public List<User> retrieveAllUsers(){
return userRepository.findAll();
}
//retrieve specific user
#GetMapping("/users/{id}")
public User retrieveUser(#PathVariable int id){
return userRepository.findOne(id);
}
}
Below is my 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>
<groupId>com.example.SpringMVC.04.webservices</groupId>
<artifactId>SpringMVC-04-webservices</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringMVC-04-webservices</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.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-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

Getting the error : Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException

I am new to spring and I wanted to communicate with mongodb via spring. I tried and tested the following code on SPRING TOOL SUITE but I am getting the following error:
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [hello.PersonRepository] is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:371)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:331)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:968)
at hello.Runhere.main(Runhere.java:19)
Kindly tell me where is the problem.
Here is Person.java class
package hello;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document
public class Person {
#Id
private String personId;
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getPersonId() {
return personId;
}
public void setPersonId(final String personId) {
this.personId = personId;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(final int age) {
this.age = age;
}
#Override
public String toString() {
return "Person [id=" + personId + ", name=" + name + ", age=" + age
+ "]";
}
}
Here is my PersonRepository.java file
package hello;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;
#Repository
public class PersonRepository {
#Autowired
MongoTemplate mongoTemplate;
public void countUnderAge() {
List<Person> results = null;
Query query = new Query();
Criteria criteria = new Criteria();
criteria = criteria.and("age").lte(21);
query.addCriteria(criteria);
results = mongoTemplate.find(query, Person.class);
System.out.println(results.size());
}
public void countAllPersons() {
List<Person> results = mongoTemplate.findAll(Person.class);
System.out.println("The total number of players " + results.size());
}
public void insertPersonWithNameAayushAndRandomAge() {
double age = Math.ceil(Math.random() * 100);
Person p = new Person("Aayush", (int) age);
mongoTemplate.insert(p);
}
public void createPersonCollection() {
if (!mongoTemplate.collectionExists(Person.class)) {
mongoTemplate.createCollection(Person.class);
}
}
public void dropPersonCollection() {
if (mongoTemplate.collectionExists(Person.class)) {
mongoTemplate.dropCollection(Person.class);
}
}
}
Here is my springconfig.java file:
package hello;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
import com.mongodb.Mongo;
#Configuration
#EnableMongoRepositories
#Import(RepositoryRestMvcConfiguration.class)
#EnableAutoConfiguration
public class springconfig extends AbstractMongoConfiguration {
#Override
protected String getDatabaseName() {
return "demo";
}
#SuppressWarnings("deprecation")
#Override
public Mongo mongo() throws Exception {
return new Mongo();
}
}
Here is my class which contains the main method :
package hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Runhere {
public static void main(String[] args) {
#SuppressWarnings("resource")
ApplicationContext context = new AnnotationConfigApplicationContext(springconfig.class);
PersonRepository personRepository = context.getBean(PersonRepository.class);
personRepository.dropPersonCollection();
personRepository.createPersonCollection();
for (int i = 0; i < 10000; i++) {
personRepository.insertPersonWithNameAayushAndRandomAge();
}
personRepository.countAllPersons();
personRepository.countUnderAge();
}
}
And finally here is my 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>
<groupId>org.test</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>integration_with_mongo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<start-class>demo.IntegrationWithMongoApplication</start-class>
<java.version>1.7</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-repository</artifactId>
<version>1.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.webflow</groupId>
<artifactId>spring-webflow</artifactId>
<version>2.4.1.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
try to add bean in the application config.xml
<mvc:resources mapping="" location="" />
<bean id="PersonRepository" class="(complete package path)hello.PersonRepository" />
SpringBoot - In hope it will help any SpringBoot developer
This error mostly hits when the bean you are calling from another package.
Specifically for Spring boot, you can try an annotation for it, to scan the component you want to get bean of it.
#ComponentScan("your package")
place the #Componentscan annotation in the main class where you are getting the bean.
Example
#ComponentScan("com.spring.crud.controller")
public class SpringCrudApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(SpringCrudApplication.class, args);
HomeController bean1 = context.getBean(HomeController.class);
System.out.println(bean1.HomePage());
}
}
so, in the above example I am taking controller bean which I created in the package of com.spring.crud.controller
if you are interested in explanation see this article:
https://baidar-sabaoon.medium.com/how-to-handle-nosuchbeandefinitionexception-in-spring-boot-7255170d702c

Categories

Resources