Unable to recognize #Repository in Spring boot app - java

I am getting the below error when trying to run the Spring Boot app.
*************************** APPLICATION FAILED TO START
Description:
Field repository in com.javanovice.crud.example.service.ProductService
required a bean of type
'com.javanovice.crud.example.repository.ProductRepository' that could
not be found.
The injection point has the following annotations:
#org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type
'com.javanovice.crud.example.repository.ProductRepository' in your
configuration.
ProductRepository.java
package com.javanovice.crud.example.repository;
import com.javanovice.crud.example.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface ProductRepository extends JpaRepository<Product,Integer> {
Product findByName(String name);
}
ProductService.java
package com.javanovice.crud.example.service;
import com.javanovice.crud.example.entity.Product;
import com.javanovice.crud.example.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class ProductService {
#Autowired
private ProductRepository repository;
public Product saveProduct(Product product) {
return repository.save(product);
}
public List<Product> saveProducts(List<Product> products) {
return repository.saveAll(products);
}
public List<Product> getProducts() {
return repository.findAll();
}
public Product getProductById(int id) {
return repository.findById(id).orElse(null);
}
public Product getProductByName(String name) {
return repository.findByName(name);
}
public String deleteProduct(int id) {
repository.deleteById(id);
return "product removed !! " + id;
}
public Product updateProduct(Product product) {
Product existingProduct = repository.findById(product.getId()).orElse(null);
existingProduct.setName(product.getName());
existingProduct.setQuantity(product.getQuantity());
existingProduct.setPrice(product.getPrice());
return repository.save(existingProduct);
}
}
ProductController.java
package com.javanovice.crud.example.controller;
import com.javanovice.crud.example.entity.Product;
import com.javanovice.crud.example.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
public class ProductController {
#Autowired
private ProductService service;
#PostMapping("/addProduct")
public Product addProduct(#RequestBody Product product) {
return service.saveProduct(product);
}
#PostMapping("/addProducts")
public List<Product> addProducts(#RequestBody List<Product> products) {
return service.saveProducts(products);
}
#GetMapping("/products")
public List<Product> findAllProducts() {
return service.getProducts();
}
#GetMapping("/productById/{id}")
public Product findProductById(#PathVariable int id) {
return service.getProductById(id);
}
#GetMapping("/product/{name}")
public Product findProductByName(#PathVariable String name) {
return service.getProductByName(name);
}
#PutMapping("/update")
public Product updateProduct(#RequestBody Product product) {
return service.updateProduct(product);
}
#DeleteMapping("/delete/{id}")
public String deleteProduct(#PathVariable int id) {
return service.deleteProduct(id);
}
}
SpringBootCrudExampleApplication.java
package com.javanovice.crud.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })
public class SpringBootCrudExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootCrudExampleApplication.class, args);
}
}

You need to remove exclude = {DataSourceAutoConfiguration.class } as follows:
#SpringBootApplication
public class SpringBootCrudExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootCrudExampleApplication.class, args);
}
}
Otherwise, autoconfiguration will not kick in for Persistence related beans, including the Repositories.

Related

Error in fetching table through JpaRepository

I am trying to fetch data from a table in MySQL using JpaRepository.
I am geeting an error by running code like -
Error creating bean with name 'chassiscontroller': Unsatisfied dependency expressed through field 'service': Error creating bean with name 'chassisserviceimpl': Unsatisfied dependency expressed through field 'dao': Error creating bean with name 'chassisdao' defined in com.ChassisInfo.chassis.dao.chassisdao defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Not a managed type: class com.ChassisInfo.model.chassismodel.
Controller
package com.ChassisInfo.chassis.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ChassisInfo.chassis.model.ChassisModel;
import com.ChassisInfo.chassis.service.ChassisService;
#RestController
public class ChassisController {
#Autowired
private ChassisService service;
#GetMapping("/chnum")
public List<ChassisModel> getchassisnumberinfo(){
return service.getAll();
}
}
Service-
package com.ChassisInfo.chassis.service;
import java.util.List;
import com.ChassisInfo.chassis.model.ChassisModel;
public interface ChassisService{
List<ChassisModel> getAll();
}
ServiceImpl-
package com.ChassisInfo.chassis.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ChassisInfo.chassis.dao.ChassisDao;
import com.ChassisInfo.chassis.model.ChassisModel;
#Service
#lombok.AllArgsConstructor
#lombok.NoArgsConstructor
public class ChassisServiceimpl implements ChassisService {
#Autowired
private ChassisDao dao;
#Override
public List<ChassisModel> getAll() {
// TODO Auto-generated method stub
return dao.findAll();
}
Dao-
package com.ChassisInfo.chassis.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.stereotype.Repository;
import com.ChassisInfo.chassis.model.ChassisModel;
#Repository
#EnableJpaRepositories
public interface ChassisDao extends JpaRepository<ChassisModel,String> {
#Query(value = "Select * from chassis_master" ,nativeQuery = true)
List<ChassisModel> findAll();
}
Model-
package com.ChassisInfo.model;
public class chassismodel {
private String vin;
private String active;
private String chassisNumber;
private String chassisSeries;
private String statusChangedTime;
private String tag;
private String truckid;
private String id;
private String chassis_number;
private String chassis_series;
private String status_changed_time;
private String truck_id;
public String getVin() {
return vin;
}
public void setVin(String vin) {
this.vin = vin;
}
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
public String getChassisSeries() {
return chassisSeries;
}
public void setChassisSeries(String chassisSeries) {
this.chassisSeries = chassisSeries;
}
public String getStatusChangedTime() {
return statusChangedTime;
}
public void setStatusChangedTime(String statusChangedTime) {
this.statusChangedTime = statusChangedTime;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getTruckid() {
return truckid;
}
public void setTruckid(String truckid) {
this.truckid = truckid;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getChassis_number() {
return chassis_number;
}
public void setChassis_number(String chassis_number) {
this.chassis_number = chassis_number;
}
public String getChassis_series() {
return chassis_series;
}
public void setChassis_series(String chassis_series) {
this.chassis_series = chassis_series;
}
public String getStatus_changed_time() {
return status_changed_time;
}
public void setStatus_changed_time(String status_changed_time) {
this.status_changed_time = status_changed_time;
}
public String getTruck_id() {
return truck_id;
}
public void setTruck_id(String truck_id) {
this.truck_id = truck_id;
}
public String getChassisNumber() {
return chassisNumber;
}
public void setChassisNumber(String chassisNumber) {
this.chassisNumber = chassisNumber;
}
}
ChassisApplication-
package com.ChassisInfo.chassis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import com.ChassisInfo.chassis.controller.ChassisController;
#SpringBootApplication
#EnableJpaRepositories
public class ChassisApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(ChassisApplication.class, args);
ChassisController chassisController = context.getBean(ChassisController.class);
chassisController.getchassisnumberinfo();
}
}
Try to use #RequiredArgsConstructor (lombok) in chassisserviceimpl, since dao field is not accessible for autowiring. Also add final for the field:
private final chassisdao dao;
This is probably because you are missing the #EnableJpaRepositories(basePackages = "your.package.name") in you #SpringBootApplication
This is the Annotation to enable JPA repositories. Will scan the package of the annotated configuration class for Spring Data repositories by default.

Spring Repository Bean Not Being Found

I'm trying to do a simple CRUD in postgres with spring, but for no reason my IoD mechanism doesn't work and throws an error like this:
Description:
Parameter 0 of constructor in br.com.maptriz.formulario_dinamico.service.FormularioDinamicoService required a bean of type 'br.com.maptriz.formulario_dinamico.repository.FormularioDinamicoRepository' that could not be found.
Action:
Consider defining a bean of type 'br.com.maptriz.formulario_dinamico.repository.FormularioDinamicoRepository' in your configuration.
Here's my code:
FormularioDinamicoApplication.java
package br.com.maptriz.formulario_dinamico;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
// #EnableJpaRepositories("br.com.maptriz.formulario_dinamico.repository")
// #EnableScheduling
// #EnableDiscoveryClient
// #ComponentScan
#SpringBootApplication
public class FormularioDinamicoApplication {
public static void main(String[] args) {
SpringApplication.run(FormularioDinamicoApplication.class, args);
}
}
FormularioDinamico
package br.com.maptriz.formulario_dinamico.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "formulario_dinamico")
public class FormularioDinamico {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne
#JoinColumn(name="tipo_tabela")
private Long tabelaId;
private String name;
private String campos;
protected FormularioDinamico() {}
public FormularioDinamico(Long tabelaId, String name, String campos) {
this.tabelaId = tabelaId;
this.name = name;
this.campos = campos;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getTabelaId() {
return this.tabelaId;
}
public void setTabelaId(Long tabelaId) {
this.tabelaId = tabelaId;
}
public String getName() {
return this.name;
}
public void setObservacao(String name) {
this.name = name;
}
public String getCampos() {
return this.campos;
}
public void setCampos(String campos) {
this.campos = campos;
}
#Override
public String toString() {
return "EntidadeGenerica{" +
"id=" + id +
", dataAtualizacao=" + tabelaId +
", dataCadastro=" + name +
", observacao='" + campos + '}';
}
}
FormlarioDinamicoController.java
package br.com.maptriz.formulario_dinamico.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import br.com.maptriz.formulario_dinamico.model.FormularioDinamico;
import br.com.maptriz.formulario_dinamico.service.FormularioDinamicoService;
#RestController
#RequestMapping
public class FormularioDinamicoController {
private final FormularioDinamicoService service;
#Autowired
public FormularioDinamicoController(FormularioDinamicoService service) {
this.service = service;
}
// #GetMapping
// public List<DynamicForm> getDynamicForm() {
// return dynamicFormService.getDynamicForm();
// }
#PostMapping("/create")
public void registrarNovoFormularioDinamico(#RequestBody FormularioDinamico formularioDinamico) {
System.out.println("TEST");
service.adicionarNovoFormularioDinamico(formularioDinamico);
}
}
FormularioDinamicoService.java
package br.com.maptriz.formulario_dinamico.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.maptriz.formulario_dinamico.model.FormularioDinamico;
import br.com.maptriz.formulario_dinamico.repository.FormularioDinamicoRepository;
#Service
public class FormularioDinamicoService {
private final FormularioDinamicoRepository repository;
#Autowired
public FormularioDinamicoService(FormularioDinamicoRepository repository) {
this.repository = repository;
}
// public List<DynamicForm> getDynamicForm() {
// return dynamicFormRepository.findAll();
// }
public void adicionarNovoFormularioDinamico(FormularioDinamico formularioDinamico) {
List<FormularioDinamico> topicos = repository.findAll();
System.out.println("HEREEEE");
System.out.println(topicos);
}
}
And finally FormularioDinamicoRepository.java
package br.com.maptriz.formulario_dinamico.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import br.com.maptriz.formulario_dinamico.model.FormularioDinamico;
public interface FormularioDinamicoRepository
extends JpaRepository<FormularioDinamico, Long> {
List<FormularioDinamico> findAll();
}
My Folder Structure:
src
main
java/br/com/maptriz/formulario_dinamico
controller
model
repository
service
FormularioDinamicoApplication.java
Add #Repository annotation on the interface FormularioDinamicoRepository. It should be working seamlessly.
The moment you add it spring identifies it as a bean and creates an object and injects the bean wherever autowired.

Spring Boot URL mapping not working when files are present in multiple packages

I tried making a simple REST API using Spring Boot. I have put the classes in separate packages. In this case, the URL mapping is not working (checked using Postman), whereas its working fine if I put them all in the same package as that of the main class.
""" Hierarchy of the packages :
com.example.ProductCRUD
|-----ProductCrudApplication.java (main)
com.example.ProductCRUD.Controller
|-----ProductController.java(controller)
com.example.ProductCRUD.Entity
|------Product.java(model class)
com.example.Repository
|-----ProductRepo.java(Repository interface)
com.example.Service
|-------ProductService.java(Service class) """
I tried including #componentscan("com.example") in the main class. But in that case, it throws an error.
If somebody could help me in finding out where I went wrong, it would be helpful.
Thanks in advance for your help.
//PRODUCT MODEL CLASS (Product.java)
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
//MODEL CLASS
#Entity
public class Product {
#Id
#GeneratedValue
private int id;
private String name;
private int quantity;
private int price;
public Product() {
super();
// TODO Auto-generated constructor stub
}
public Product(int id, String name, int quantity, int price) {
super();
this.id = id;
this.name = name;
this.quantity = quantity;
this.price = price;
}
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 int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
//Repository (ProductRepo.java) :interface
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.Entity.Product;
public interface ProductRepo extends JpaRepository<Product,Integer> {
Product findByName(String name);
}
//Service class(ProductService.java)
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.Entity.Product;
import com.example.Repository.ProductRepo;
#Service
public class ProductService {
#Autowired
private ProductRepo repo; //service--> repository
//PUT
public Product create(Product product) {
Product p=repo.save(product); //default method of JPA to make the data persist in the DB
return p;
}
public List<Product> createproducts(List<Product> products) {
List<Product> p=repo.saveAll(products);
return p;
}
//GET
public List<Product> getProducts(){
List<Product> p=repo.findAll();
return p;
}
public Product getProductByid(int id){
Product p=repo.findById(id).orElse(null); //return id , if id not found then return null
return p;
}
public Product getProductByName(String name){
Product p=repo.findByName(name); //customized method in JPA (declared in the interface)
return p;
}
//DELETE
public String deleteProduct(int id) {
repo.deleteById(id);
return "Product removed : "+id;
}
//UPDATE
public Product updateProduct(Product product) {
Product existing=repo.findById(product.getId()).orElse(null);
existing.setName(product.getName());
existing.setPrice(product.getPrice());
existing.setQuantity(product.getQuantity());
Product p=repo.save(existing);
return p;
}
}
//Controller class (ProductController.java)
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
import com.example.Entity.Product;
import com.example.Service.ProductService;
#RestController
public class ProductController {
#Autowired
private ProductService service; //controller --> service
#PostMapping("/create")
public Product addProduct(#RequestBody Product product) {
return service.create(product);
}
#PostMapping("/createProducts")
public List<Product> addProducts(#RequestBody List<Product> products) {
return service.createproducts(products);
}
#GetMapping("/getproducts/{id}")
public Product getProductById(#PathVariable int id){
return service.getProductByid(id);
}
#GetMapping("/getproducts/{name}")
public Product getProductByName(#PathVariable String name){
return service.getProductByName(name);
}
#GetMapping("/getproducts")
public List<Product> getProducts(){
return service.getProducts();
}
#DeleteMapping("/delete/{id}")
public String delete(#PathVariable int id) {
return service.deleteProduct(id);
}
#PutMapping("/update/{id}")
public Product update(#RequestBody Product product) {
return service.updateProduct(product);
}
}
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
#ComponentScan("com.example")
public class ProductCrudApplication {
public static void main(String[] args) {
SpringApplication.run(ProductCrudApplication.class, args);
}
}
-- If I include the #Componentscan this is the error I am receiving :
Field repo in com.example.Service.ProductService required a bean of type 'com.example.Repository.ProductRepo' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.example.Repository.ProductRepo' in your configuration.
moving the main class from
com/example/ProductCRUD
to
com/example
fixes your issue.
diff:
rename from ProductCRUD/src/main/java/com/example/ProductCRUD/ProductCrudApplication.java
rename to ProductCRUD/src/main/java/com/example/ProductCrudApplication.java
index 1633cbf..93294a2 100644
--- a/ProductCRUD/src/main/java/com/example/ProductCRUD/ProductCrudApplication.java
+++ b/ProductCRUD/src/main/java/com/example/ProductCrudApplication.java
## -1,4 +1,4 ##
-package com.example.ProductCRUD;
+package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

UnsatisfiedDependencyException: Error creating bean with name 'procjectController': Unsatisfied dependency expressed through field

I am building simple ManyToOne relationship using spring JAP. i get UnsatisfiedDependencyException Error with bean name Unsatisfied dependency expressed through field
UnsatisfiedDependencyException: Error creating bean with name 'procjectController': Unsatisfied
Here is my file.
project.java
package com.ganesh.dto;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
public class Project {
#Id
private int projectId;
private String projectName;
//Relation establish
#ManyToOne(
fetch = FetchType.LAZY,
optional = false
)
#JoinColumn(
name = "employee_id",
nullable = false
)
#JsonIgnore
private Employee employee;
public Project() {
}
public Project(int projectId, String projectName, int eId) {
super();
this.projectId = projectId;
this.projectName = projectName;
//Adding employee
this.employee = new Employee(eId,"","");
}
public int getProjectId() {
return projectId;
}
public void setProjectId(int projectId) {
this.projectId = projectId;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
//Adding getter and setters Employee reference
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
}
ProjectDao.java
package com.ganesh.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.ganesh.dto.Project;
#Repository
public interface ProjectDao extends JpaRepository<Project, Integer> {
List<Project> findEmployeeById(int eId);
}
ImpProjectService.java
package com.ganesh.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ganesh.dao.*;
import com.ganesh.dto.Project;
#Service
public class ImpProjectService implements ProjectService {
#Autowired
private ProjectDao projectDao;
#Override
public List<Project> getProjectList(int eId) {
System.out.println("in Dao class employee id"+ eId);
return projectDao.findEmployeeById(eId);
}
#Override
public Project getProjectById(int id) {
return projectDao.getOne(id);
}
#Override
public void addProject(Project project) {
projectDao.save(project);
}
#Override
public void updateProject(Project project) {
projectDao.save(project);
}
#Override
public void deleteProjectById(int id) {
projectDao.deleteById(id);
}
#Override
public List<Project> getAllProject() {
return projectDao.findAll();
}
}
ProcjectController.java
package com.ganesh.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.ganesh.dto.*;
import com.ganesh.service.*;
#RestController
public class ProcjectController {
#Autowired
private ImpProjectService projectService;
#RequestMapping("/projects")
public List<Project> getProjectList(){
return projectService.getAllProject();
}
#RequestMapping("/employees/{eId}/projects")
public List<Project> getAllProjects(#PathVariable int eId){
System.out.println("In Project Controller");
List<Project> projList = projectService.getProjectList(eId);
System.out.println(projList);
return projList;
}
#RequestMapping("/employees/{eId}/projects/{id}")
public Project getProjectById(#PathVariable int id) {
return projectService.getProjectById(id);
}
#RequestMapping(method = RequestMethod.POST, value="/employees/{eId}/projects")
public void addProject(#RequestBody Project project, #PathVariable int eId) {
project.setEmployee(new Employee(eId,"",""));
projectService.addProject(project);
}
#RequestMapping(method = RequestMethod.PUT, value="/employees/{eId}/projects/{id}")
public void updateProject(#RequestBody Project project, #PathVariable int eId) {
project.setEmployee(new Employee(eId,"",""));
projectService.updateProject(project);
}
#RequestMapping(method = RequestMethod.DELETE, value="/projects/{id}")
public void deleteProjecstById(#PathVariable int id) {
projectService.deleteProjectById(id);
}
}
Note: This answer is based on insufficient data, because stack trace is not available. With correct and complete stacktrace, we might be able to provide more precise answer.
Answer:
Looks like a problem in your Dao class.
You have written
#Repository
public interface ProjectDao extends JpaRepository<Project, Integer> {
List<Project> findEmployeeById(int eId);
}
Which means you are creating a repository of type Project and trying to fire a query as findEmployeeById, It should either be findByEmployee, which accepts Employee as a parameter, or should not be there in place at all. Because the query syntax and the Template parameters do not match. So Spring will not be able to initialize the query handlers for the same.
Try changing it as below, if is satisfies your purpose.
#Repository
public interface ProjectDao extends JpaRepository {
List<Project> findAllByEmployee(Employee emp);
}
Please check the same, and correct. If it still doesn't work, please post the full stack trace, and we can help you out.

Spring Boot can't connect to MySql

this is my first exercise with Spring Boot and this is my application.properties:
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto=update
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc.mysql://localhost:3306/notedb
spring.datasource.username=root
spring.datasource.password=*******
These are my classes:
DemoMySqlApplication.java
package com.example.demomysql;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
#ComponentScan(basePackages={"com.joydeep.springboot"})
public class DemoMysqlApplication {
public static void main(String[] args) {
SpringApplication.run(DemoMysqlApplication.class, args);
}
NoteRepository.java (interface):
package com.example.demomysql;
import org.springframework.data.repository.CrudRepository;
public interface NoteRepository extends CrudRepository <Note, Integer>{
}
NoteController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
#RestController
#RequestMapping(value="/note")
public class NoteController {
#Autowired
private NoteRepository noteRepository;
#GetMapping(value="/all")
public String getAllNotes(Model model) {
model.addAttribute("notes", noteRepository.findAll());
return "list";
}
#GetMapping(value="/debug")
public #ResponseBody Iterable<Note> getNotes(){
return noteRepository.findAll();
}
}
Note.java (Entity class)
package com.example.demomysql;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.springframework.data.repository.CrudRepository;
#Entity
public class Note {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String title;
private String description;
private Boolean done;
public Integer getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Boolean getDone() {
return done;
}
public void setDone(Boolean done) {
this.done = done;
}
}
From the console, I don't see errors. Tomcat starts normally. These are the last two information:
Tomcat started on port(s): 8080 (http) with context path ''
Started DemoMysqlApplication in 0.731 seconds (JVM running for 480.726)
But on my MySQL database (I created a DB named "notedb" and a table named "note", before to launch this application). I have one row with the data in note. But when I try to connect to:
http://localhost:8080/note/debug
I see:
I think I have a problem with Controller class.
Please, can you help me?
Thanks
pring.jpa.hibernate.ddl-auto=update
spring.datasource.platform=mysql
spring.datasource.url=jdbc:mysql://localhost:3306/notedb?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=****
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
Remove
exclude={DataSourceAutoConfiguration.class}
#ComponentScan(basePackages={"com.joydeep.springboot"})
Keep #RestController remove #ResponseBody
For #Controller keep #ResponseBody or ResponseEntity<T>
Change return type Iterable<Note> to List<Note>
Application
#SpringBootApplication
public class DemoMysqlApplication {
public static void main(String[] args) {
SpringApplication.run(DemoMysqlApplication.class, args);
}
Rest Controller
#RestController
#RequestMapping(value="/note")
public class NoteController {
#Autowired
private NoteRepository noteRepository;
#GetMapping(value="/debug")
public List<Note> getNotes(){
return noteRepository.findAll();
}
}
Controller
#Controller
#RequestMapping(value="/note")
public class NoteController {
#Autowired
private NoteRepository noteRepository;
#GetMapping(value="/debug")
public ResponseEntity<List<Note>> getNotes(){
return new ResponseEntity<List<Note>>(noteRepository.findAll(),HttpStatus.OK);
}
}

Categories

Resources